refactor user accounts structure

This commit is contained in:
2026-03-16 00:35:34 +03:30
parent 20be653499
commit 3c9f6eed1d
286 changed files with 2812 additions and 1133 deletions
@@ -0,0 +1,42 @@
<p-dialog
header="فرم کاربر"
[(visible)]="visible"
[modal]="true"
[style]="{ width: '500px' }"
[closable]="true"
(onHide)="close()"
>
<form [formGroup]="form" (submit)="submit()" class="flex flex-col gap-4">
<app-input label="نام کاربری" [control]="form.controls.username" name="username" />
<app-enum-select [control]="form.controls.type" name="type" type="accountType" />
<uikit-field label="رمز عبور" class="" [control]="form.controls.password">
<p-password
id="password1"
name="password"
formControlName="password"
autocomplete="password"
[toggleMask]="true"
[fluid]="true"
[feedback]="false"
[invalid]="form.controls.password.touched && form.controls.password.invalid"
/>
<span class="text-xs mt-2 text-muted-color">
رمز باید حداقل ۸ کاراکتر بوده و شامل حداقل یک حرف بزرگ، یک حرف کوچک، یک عدد و یک کاراکتر ویژه باشد.
</span>
</uikit-field>
<uikit-field label="تکرار رمز عبور" class="" [control]="form.controls.confirmPassword">
<p-password
id="confirmPassword"
name="confirmPassword"
formControlName="confirmPassword"
autocomplete="new-password"
[toggleMask]="true"
[fluid]="true"
[feedback]="false"
[invalid]="form.controls.confirmPassword.touched && form.controls.confirmPassword.invalid"
/>
</uikit-field>
<app-form-footer-actions [submitLabel]="'ذخیره'" [loading]="submitLoading()" (onCancel)="close()" />
</form>
</p-dialog>
@@ -0,0 +1,83 @@
import { MustMatch, password } from '@/core/validators';
// import { CatalogRolesComponent } from '@/shared/catalog/roles';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import { EnumSelectComponent } from '@/shared/apiEnum/select.component';
import { InputComponent } from '@/shared/components';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { UikitFieldComponent } from '@/uikit';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { Dialog } from 'primeng/dialog';
import { Password } from 'primeng/password';
import { IAccountRequest, IAccountResponse } from '../../models';
import { AdminUserAccountsService } from '../../services/accounts.service';
@Component({
selector: 'superAdmin-user-account-form',
templateUrl: './form.component.html',
imports: [
ReactiveFormsModule,
Dialog,
InputComponent,
FormFooterActionsComponent,
UikitFieldComponent,
Password,
EnumSelectComponent,
],
})
export class UserAccountFormComponent extends AbstractFormDialog<
IAccountRequest,
IAccountResponse
> {
private readonly service = inject(AdminUserAccountsService);
@Input() userId!: string;
@Input() accountId!: string;
initForm = () => {
if (this.editMode) {
return this.fb.group(
{
username: [this.initialValues?.username || '', [Validators.required]],
// @ts-ignore
type: [this.initialValues?.type, [Validators.required]],
password: ['', [password()]],
confirmPassword: [''],
},
{
validators: [MustMatch('password', 'confirmPassword')],
},
);
}
return this.fb.group(
{
username: [this.initialValues?.username || '', [Validators.required]],
// @ts-ignore
type: [this.initialValues?.type, [Validators.required]],
password: ['', [Validators.required, password()]],
confirmPassword: ['', [Validators.required]],
},
{
validators: [MustMatch('password', 'confirmPassword')],
},
);
};
form = this.initForm();
override ngOnChanges(): void {
this.form = this.initForm();
}
submitForm() {
const formValue = this.form.value as IAccountRequest;
// @ts-ignore
const { confirmPassword, ...rest } = formValue;
if (this.editMode) {
return this.service.update(this.userId, this.accountId, rest);
}
return this.service.create(this.userId, rest);
}
}
@@ -0,0 +1,22 @@
<app-page-data-list
pageTitle="مدیریت حساب‌های کاربری"
[addNewCtaLabel]="'افزودن حساب کاربری جدید'"
[columns]="columns"
[showAdd]="true"
emptyPlaceholderTitle="حساب کاربری‌ای یافت نشد."
emptyPlaceholderDescription="برای افزودن حساب کاربری جدید، روی دکمهٔ بالا کلیک کنید."
[items]="items()"
[loading]="loading()"
[showDetails]="true"
[showAdd]="true"
(onAdd)="openAddForm()"
>
</app-page-data-list>
<superAdmin-user-account-form
[(visible)]="visibleForm"
[editMode]="editMode()"
[userId]="userId"
[accountId]="selectedItemForEdit()?.id || ''"
[initialValues]="selectedItemForEdit() || undefined"
(onSubmit)="refresh()"
/>
@@ -0,0 +1,39 @@
// import { CatalogRoleTagComponent } from '@/shared/catalog/roles';
import { AbstractList } from '@/shared/abstractClasses/abstract-list';
import {
IColumn,
PageDataListComponent,
} from '@/shared/components/pageDataList/page-data-list.component';
import { Component, inject, Input } from '@angular/core';
import { IAccountResponse } from '../../models';
import { AdminUserAccountsService } from '../../services/accounts.service';
import { UserAccountFormComponent } from './form.component';
@Component({
selector: 'superAdmin-user-account-list',
templateUrl: './list.component.html',
imports: [PageDataListComponent, UserAccountFormComponent],
})
export class UsersComponent extends AbstractList<IAccountResponse> {
@Input() userId!: string;
@Input() fullHeight?: boolean;
@Input() header: IColumn[] = [
{ field: 'id', header: 'شناسه' },
{ field: 'username', header: 'نام کاربری' },
{ field: 'type', header: 'نوع حساب' },
{
field: 'created_at',
header: 'تاریخ ایجاد',
type: 'date',
},
];
private readonly service = inject(AdminUserAccountsService);
override setColumns(): void {
this.columns = this.header;
}
override getDataRequest() {
return this.service.getAll(this.userId);
}
}
@@ -0,0 +1,45 @@
<p-dialog
header="فرم کاربر"
[(visible)]="visible"
[modal]="true"
[style]="{ width: '500px' }"
[closable]="true"
(onHide)="close()"
>
<form [formGroup]="form" (submit)="submit()" class="flex flex-col gap-4">
<app-input label="نام" [control]="form.controls.first_name" name="first_name" />
<app-input label="نام خانوادگی" [control]="form.controls.last_name" name="last_name" />
<app-input label="شماره موبایل" [control]="form.controls.mobile_number" name="mobile_number" type="mobile" />
<!-- <app-enum-select [control]="form.controls.role" name="role" type="accountType" /> -->
<!-- <catalog-roles-select [control]="form.controls.roleId" /> -->
<!-- <uikit-field label="رمز عبور" class="" [control]="form.get('password')">
<p-password
id="password1"
name="password"
formControlName="password"
autocomplete="password"
[toggleMask]="true"
[fluid]="true"
[feedback]="false"
[invalid]="form.get('password')?.touched && form.get('password')?.invalid"
/>
<span class="text-xs mt-2 text-muted-color">
رمز باید حداقل ۸ کاراکتر بوده و شامل حداقل یک حرف بزرگ، یک حرف کوچک، یک عدد و یک کاراکتر ویژه باشد.
</span>
</uikit-field>
<uikit-field label="تکرار رمز عبور" class="" [control]="form.get('confirmPassword')">
<p-password
id="confirmPassword"
name="confirmPassword"
formControlName="confirmPassword"
autocomplete="new-password"
[toggleMask]="true"
[fluid]="true"
[feedback]="false"
[invalid]="form.get('confirmPassword')?.touched && form.get('confirmPassword')?.invalid"
/>
</uikit-field> -->
<app-form-footer-actions [submitLabel]="'ذخیره'" [loading]="submitLoading()" (onCancel)="close()" />
</form>
</p-dialog>
@@ -0,0 +1,76 @@
import { mobileValidator } from '@/core/validators';
// import { CatalogRolesComponent } from '@/shared/catalog/roles';
import { AbstractFormDialog } from '@/shared/abstractClasses';
import { InputComponent } from '@/shared/components';
import { FormFooterActionsComponent } from '@/shared/components/formFooterActions/form-footer-actions.component';
import { Component, inject, Input } from '@angular/core';
import { ReactiveFormsModule, Validators } from '@angular/forms';
import { Dialog } from 'primeng/dialog';
import { IUserRequest, IUserResponse } from '../models';
import { UsersService } from '../services/main.service';
@Component({
selector: 'superAdmin-user-form',
templateUrl: './form.component.html',
imports: [ReactiveFormsModule, Dialog, InputComponent, FormFooterActionsComponent],
})
export class UserAccountFormComponent extends AbstractFormDialog<IUserRequest, IUserResponse> {
private readonly service = inject(UsersService);
@Input() userId!: string;
@Input() accountId!: string;
initForm = () => {
if (this.editMode) {
return this.fb.group(
{
first_name: [this.initialValues?.first_name || '', [Validators.required]],
last_name: [this.initialValues?.last_name || '', [Validators.required]],
mobile_number: [
this.initialValues?.mobile_number || '',
[Validators.required, mobileValidator()],
],
// @ts-ignore
// role: [this.initialValues?.role || '', [Validators.required]],
// password: ['', [password()]],
// confirmPassword: [''],
},
// {
// validators: [MustMatch('password', 'confirmPassword')],
// },
);
}
return this.fb.group(
{
first_name: [this.initialValues?.first_name || '', [Validators.required]],
last_name: [this.initialValues?.last_name || '', [Validators.required]],
mobile_number: [
this.initialValues?.mobile_number || '',
[Validators.required, mobileValidator()],
],
// @ts-ignore
// role: [this.initialValues?.role || '', [Validators.required]],
// password: ['', [Validators.required, password()]],
// confirmPassword: ['', [Validators.required]],
},
// {
// validators: [MustMatch('password', 'confirmPassword')],
// },
);
};
form = this.initForm();
override ngOnChanges(): void {
this.form = this.initForm();
}
submitForm() {
const formValue = this.form.value as IUserRequest;
if (this.editMode) {
return this.service.update(this.userId, formValue);
}
return this.service.create(formValue);
}
}
@@ -0,0 +1,5 @@
@if (loading()) {
<shared-page-loading />
} @else {
<router-outlet></router-outlet>
}
@@ -0,0 +1,30 @@
import { PageLoadingComponent } from '@/shared/components/page-loading.component';
import pageParamsUtils from '@/utils/page-params.utils';
import { Component, computed, inject, signal } from '@angular/core';
import { ActivatedRoute, RouterOutlet } from '@angular/router';
import { UserStore } from '../store/user.store';
@Component({
selector: 'superAdmin-user-layout',
templateUrl: './layout.component.html',
imports: [PageLoadingComponent, RouterOutlet],
})
export class UserLayoutComponent {
private readonly store = inject(UserStore);
private readonly route = inject(ActivatedRoute);
readonly pageParams = computed(() => pageParamsUtils(this.route));
readonly userId = signal<string>(this.route.snapshot.paramMap.get('userId')!);
readonly loading = computed(() => this.store.loading());
readonly user = computed(() => this.store.entity());
getData() {
this.store.getData(this.userId());
}
ngOnInit() {
this.getData();
// this.setBreadcrumb();
}
}
@@ -0,0 +1,6 @@
const baseUrl = (userId: string) => `/api/v1/admin/users/${userId}/accounts`;
export const ACCOUNTS_API_ROUTES = {
list: (userId: string) => `${baseUrl(userId)}`,
single: (userId: string, accountId: string) => `${baseUrl(userId)}/${accountId}`,
};
@@ -0,0 +1,8 @@
export * from './accounts';
const baseUrl = '/api/v1/admin/users';
export const USERS_API_ROUTES = {
list: () => `${baseUrl}`,
single: (userId: string) => `${baseUrl}/${userId}`,
};
@@ -0,0 +1,2 @@
export * from './apiRoutes';
export * from './routes';
@@ -0,0 +1,47 @@
import { NamedRoutes } from '@/core';
import { Routes } from '@angular/router';
export type TAccountsRouteNames = 'accounts' | 'account';
export const superAdminUserAccountsNamedRoutes: NamedRoutes<TAccountsRouteNames> = {
accounts: {
path: 'accounts',
loadComponent: () =>
import('../../views/accounts/list.component').then((m) => m.UserAccountsComponent),
// @ts-ignore
meta: {
title: 'فعالیت‌های اقتصادی',
pagePath: (userId: string) => `/super_admin/users/${userId}/accounts`,
},
},
account: {
path: 'accounts/:accountId',
// loadComponent: () =>
// import('../../views/accounts/single.component').then(
// (m) => m.,
// ),
// @ts-ignore
meta: {
title: 'فعالیت اقتصادی',
pagePath: (userId: string, businessId: string) =>
`/super_admin/users/${userId}/accounts/${businessId}`,
},
},
};
export const SUPER_ADMIN_USER_ACCOUNTS_ROUTES: Routes = [
superAdminUserAccountsNamedRoutes.accounts,
// {
// path: superAdminUserAccountsNamedRoutes.account.path,
// loadComponent: () =>
// import('../../components/accounts/layout.component').then(
// (m) => m.SuperAdminUserBusinessActivityLayoutComponent,
// ),
// children: [
// {
// path: '',
// loadComponent: superAdminUserAccountsNamedRoutes.account.loadComponent,
// },
// ],
// },
];
@@ -0,0 +1,42 @@
import { NamedRoutes } from '@/core';
import { Routes } from '@angular/router';
import { SUPER_ADMIN_CONSUMER_BUSINESS_ACTIVITIES_ROUTES } from '../../../consumers/constants/routes/businessActivities';
import { SUPER_ADMIN_USER_ACCOUNTS_ROUTES } from './accounts';
export type TUsersRouteNames = 'users' | 'user';
export const usersNamedRoutes: NamedRoutes<TUsersRouteNames> = {
users: {
path: 'users',
loadComponent: () => import('../../views/list.component').then((m) => m.UsersComponent),
meta: {
title: 'کاربران',
pagePath: () => '/super_admin/users',
},
},
user: {
path: 'users/:userId',
loadComponent: () => import('../../views/single.component').then((m) => m.UserComponent),
meta: {
title: 'کاربر',
pagePath: (userId: string) => `/super_admin/users/${userId}`,
},
},
};
export const USERS_ROUTES: Routes = [
usersNamedRoutes.users,
{
path: usersNamedRoutes.user.path,
loadComponent: () =>
import('../../components/layout.component').then((m) => m.UserLayoutComponent),
children: [
{
path: '',
loadComponent: usersNamedRoutes.user.loadComponent,
},
...SUPER_ADMIN_USER_ACCOUNTS_ROUTES,
...SUPER_ADMIN_CONSUMER_BUSINESS_ACTIVITIES_ROUTES,
],
},
];
@@ -0,0 +1,13 @@
import { TAccountType } from '@/core/constants/accountTypes.const';
export interface IAccountRawResponse {
username: string;
id: string;
}
export interface IAccountResponse extends IAccountRawResponse {}
export interface IAccountRequest {
username: string;
password?: string;
type: TAccountType;
}
@@ -0,0 +1,2 @@
export * from './accounts_io';
export * from './io';
+18
View File
@@ -0,0 +1,18 @@
import { TRoles } from '@/core';
export interface IUserRawResponse {
mobile_number: string;
first_name: string;
last_name: string;
fullname: string;
id: string;
role: TRoles;
}
export interface IUserResponse extends IUserRawResponse {}
export interface IUserRequest {
first_name: string;
last_name: string;
mobile_number: string;
role: TRoles;
}
@@ -0,0 +1,28 @@
import { IPaginatedResponse } from '@/core/models/service.model';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ACCOUNTS_API_ROUTES } from '../constants';
import { IAccountRawResponse, IAccountRequest, IAccountResponse } from '../models';
@Injectable({ providedIn: 'root' })
export class AdminUserAccountsService {
constructor(private http: HttpClient) {}
private apiRoutes = ACCOUNTS_API_ROUTES;
getAll(userId: string): Observable<IPaginatedResponse<IAccountResponse>> {
return this.http.get<IPaginatedResponse<IAccountRawResponse>>(this.apiRoutes.list(userId));
}
getSingle(userId: string, accountId: string): Observable<IAccountResponse> {
return this.http.get<IAccountRawResponse>(this.apiRoutes.single(userId, accountId));
}
create(userId: string, data: IAccountRequest): Observable<IAccountResponse> {
return this.http.post<IAccountResponse>(this.apiRoutes.list(userId), data);
}
update(userId: string, accountId: string, data: IAccountRequest): Observable<IAccountResponse> {
return this.http.patch<IAccountResponse>(this.apiRoutes.single(userId, accountId), data);
}
}
@@ -0,0 +1,28 @@
import { IPaginatedResponse } from '@/core/models/service.model';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { USERS_API_ROUTES } from '../constants';
import { IUserRawResponse, IUserRequest, IUserResponse } from '../models';
@Injectable({ providedIn: 'root' })
export class UsersService {
constructor(private http: HttpClient) {}
private apiRoutes = USERS_API_ROUTES;
getAll(): Observable<IPaginatedResponse<IUserResponse>> {
return this.http.get<IPaginatedResponse<IUserRawResponse>>(this.apiRoutes.list());
}
getSingle(userId: string): Observable<IUserResponse> {
return this.http.get<IUserRawResponse>(this.apiRoutes.single(userId));
}
create(userData: IUserRequest): Observable<IUserResponse> {
return this.http.post<IUserResponse>(this.apiRoutes.list(), userData);
}
update(userId: string, userData: IUserRequest): Observable<IUserResponse> {
return this.http.patch<IUserResponse>(this.apiRoutes.single(userId), userData);
}
}
@@ -0,0 +1,53 @@
import { EntityState, EntityStore } from '@/core/state';
import { inject, Injectable } from '@angular/core';
import { catchError, finalize, throwError } from 'rxjs';
import { IUserResponse } from '../models';
import { UsersService } from '../services/main.service';
interface UserState extends EntityState<IUserResponse> {}
@Injectable({
providedIn: 'root',
})
export class UserStore extends EntityStore<IUserResponse, UserState> {
private readonly service = inject(UsersService);
constructor() {
super({
loading: false,
error: null,
entity: null,
initialized: false,
isRefreshing: false,
});
}
getData(userId: string) {
this.patchState({ loading: true });
this.service
.getSingle(userId)
.pipe(
finalize(() => {
this.patchState({ loading: false });
}),
catchError(() => {
this.patchState({
error: '',
});
return throwError('');
}),
)
.subscribe((entity) => {
this.patchState({ entity });
});
}
override reset(): void {
this.setState({
loading: false,
error: null,
entity: null,
initialized: false,
isRefreshing: false,
});
}
}
@@ -0,0 +1 @@
export * from './list.component';
@@ -0,0 +1 @@
<superAdmin-user-account-list [userId]="userId()" />
@@ -0,0 +1,15 @@
// import { CatalogRoleTagComponent } from '@/shared/catalog/roles';
import { Component, inject, signal } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UsersComponent } from '../../components/accounts/list.component';
@Component({
selector: 'superAdmin-user-accounts',
templateUrl: './list.component.html',
imports: [UsersComponent],
})
export class UserAccountsComponent {
private readonly route = inject(ActivatedRoute);
userId = signal<string>(this.route.snapshot.params['userId']);
}
@@ -0,0 +1,3 @@
export * from './accounts';
export * from './list.component';
export * from './single.component';
@@ -0,0 +1,23 @@
<app-page-data-list
[pageTitle]="'مدیریت کاربران'"
[addNewCtaLabel]="'افزودن کاربر جدید'"
[columns]="columns"
[showAdd]="true"
emptyPlaceholderTitle="کاربری یافت نشد"
emptyPlaceholderDescription="برای افزودن کاربر جدید، روی دکمهٔ بالا کلیک کنید."
[items]="items()"
[loading]="loading()"
[showDetails]="true"
[showAdd]="true"
[showEdit]="true"
(onAdd)="openAddForm()"
(onEdit)="onEditClick($event)"
(onDetails)="toSinglePage($event)"
/>
<superAdmin-user-form
[(visible)]="visibleForm"
[editMode]="editMode()"
[initialValues]="selectedItemForEdit() || undefined"
[userId]="selectedItemForEdit()?.id || ''"
(onSubmit)="refresh()"
/>
@@ -0,0 +1,41 @@
// import { CatalogRoleTagComponent } from '@/shared/catalog/roles';
import { AbstractList } from '@/shared/abstractClasses/abstract-list';
import { PageDataListComponent } from '@/shared/components/pageDataList/page-data-list.component';
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';
import { UserAccountFormComponent } from '../components/form.component';
import { usersNamedRoutes } from '../constants';
import { IUserResponse } from '../models';
import { UsersService } from '../services/main.service';
@Component({
selector: 'superAdmin-users',
templateUrl: './list.component.html',
imports: [PageDataListComponent, UserAccountFormComponent],
})
export class UsersComponent extends AbstractList<IUserResponse> {
private readonly service = inject(UsersService);
private readonly router = inject(Router);
override setColumns(): void {
this.columns = [
{ field: 'id', header: 'شناسه' },
{ field: 'fullname', header: 'نام' },
{ field: 'mobile_number', header: 'شماره موبایل' },
{ field: 'national_code', header: 'کد ملی' },
{
field: 'created_at',
header: 'تاریخ ایجاد',
type: 'date',
},
];
}
override getDataRequest() {
return this.service.getAll();
}
toSinglePage(item: IUserResponse) {
this.router.navigateByUrl(usersNamedRoutes.user.meta.pagePath!(item.id));
}
}
@@ -0,0 +1,20 @@
<div class="flex flex-col gap-6">
<app-card-data cardTitle="اطلاعات کاربر" [editable]="true" [(editMode)]="editMode">
<div class="flex flex-col gap-4">
<div class="grid grid-cols-3 gap-4 items-center">
<app-key-value label="نام" [value]="user()?.fullname" />
<app-key-value label="شماره تماس" [value]="user()?.mobile_number" />
</div>
</div>
</app-card-data>
<superAdmin-user-account-list [userId]="userId()" />
<superAdmin-user-form
[(visible)]="editMode"
[editMode]="true"
[userId]="userId()"
[initialValues]="user() || undefined"
(onSubmit)="getData()"
/>
</div>
@@ -0,0 +1,50 @@
import { BreadcrumbService } from '@/core/services';
import { AppCardComponent, KeyValueComponent } from '@/shared/components';
import { Component, computed, effect, inject, signal } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UsersComponent } from '../components/accounts/list.component';
import { UserAccountFormComponent } from '../components/form.component';
import { usersNamedRoutes } from '../constants';
import { UserStore } from '../store/user.store';
@Component({
selector: 'superAdmin-user',
templateUrl: './single.component.html',
imports: [AppCardComponent, KeyValueComponent, UserAccountFormComponent, UsersComponent],
})
export class UserComponent {
private readonly store = inject(UserStore);
private readonly route = inject(ActivatedRoute);
private readonly breadcrumbService = inject(BreadcrumbService);
readonly userId = signal<string>(this.route.snapshot.paramMap.get('userId')!);
editMode = signal<boolean>(false);
readonly loading = computed(() => this.store.loading());
readonly user = computed(() => this.store.entity());
constructor() {
effect(() => {
if (this.user()?.id) {
this.setBreadcrumb();
}
});
}
getData() {
this.store.getData(this.userId());
}
setBreadcrumb() {
this.breadcrumbService.setItems([
{
...usersNamedRoutes.users.meta,
routerLink: usersNamedRoutes.users.meta.pagePath!(),
},
{
title: this.user()?.fullname,
routerLink: usersNamedRoutes.user.meta.pagePath!(this.userId()),
},
]);
}
}