Compare commits

...

2 Commits

Author SHA1 Message Date
Leon 59c2cb828e feat: Estilizando tela de cliente e imputs 2026-03-02 15:27:21 -03:00
Eduardo 3f5c55162e Feat: Aplicando Alterações/Ajustes 2026-03-02 13:26:48 -03:00
17 changed files with 1078 additions and 290 deletions

View File

@ -43,7 +43,7 @@ export const routes: Routes = [
path: 'system/fornecer-usuario',
component: SystemProvisionUserPage,
canActivate: [authGuard, sysadminOnlyGuard],
title: 'Fornecer Usuário',
title: 'Criar Credenciais do Cliente',
},
// ✅ rota correta

View File

@ -11,10 +11,31 @@
</button>
<div class="app-select-panel" *ngIf="isOpen">
<div class="app-select-search" *ngIf="searchable" (click)="$event.stopPropagation()">
<i class="bi bi-search"></i>
<input
type="text"
class="app-select-search-input"
[value]="searchTerm"
[placeholder]="searchPlaceholder"
(input)="onSearchInput($any($event.target).value)"
(keydown)="onSearchKeydown($event)"
/>
<button
*ngIf="searchTerm"
type="button"
class="app-select-search-clear"
(click)="clearSearch($event)"
aria-label="Limpar pesquisa"
>
<i class="bi bi-x-lg"></i>
</button>
</div>
<button
type="button"
class="app-select-option"
*ngFor="let opt of options; trackBy: trackByValue"
*ngFor="let opt of filteredOptions; trackBy: trackByValue"
[class.selected]="isSelected(opt)"
(click)="selectOption(opt)"
>
@ -22,7 +43,7 @@
<i class="bi bi-check2" *ngIf="isSelected(opt)"></i>
</button>
<div class="app-select-empty" *ngIf="!options || options.length === 0">
<div class="app-select-empty" *ngIf="!filteredOptions || filteredOptions.length === 0">
Nenhuma opção
</div>
</div>

View File

@ -111,6 +111,59 @@
padding: 6px;
}
.app-select-search {
position: sticky;
top: 0;
z-index: 2;
display: flex;
align-items: center;
gap: 6px;
margin: 0 0 6px;
padding: 6px 8px;
border: 1px solid rgba(15, 23, 42, 0.1);
border-radius: 9px;
background: #fff;
i {
color: #64748b;
font-size: 12px;
}
}
.app-select-search-input {
flex: 1 1 auto;
min-width: 0;
border: none;
background: transparent;
outline: none;
font-size: 12px;
color: #0f172a;
padding: 0;
&::placeholder {
color: #94a3b8;
}
}
.app-select-search-clear {
width: 20px;
height: 20px;
border: none;
border-radius: 999px;
background: transparent;
color: #94a3b8;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0;
cursor: pointer;
&:hover {
background: rgba(148, 163, 184, 0.2);
color: #475569;
}
}
.app-select-option {
width: 100%;
border: none;

View File

@ -23,9 +23,12 @@ export class CustomSelectComponent implements ControlValueAccessor {
@Input() valueKey = 'value';
@Input() size: 'sm' | 'md' = 'md';
@Input() disabled = false;
@Input() searchable = false;
@Input() searchPlaceholder = 'Pesquisar...';
isOpen = false;
value: any = null;
searchTerm = '';
private onChange: (value: any) => void = () => {};
private onTouched: () => void = () => {};
@ -63,10 +66,12 @@ export class CustomSelectComponent implements ControlValueAccessor {
toggle(): void {
if (this.disabled) return;
this.isOpen = !this.isOpen;
if (!this.isOpen) this.searchTerm = '';
}
close(): void {
this.isOpen = false;
this.searchTerm = '';
}
selectOption(option: any): void {
@ -84,6 +89,26 @@ export class CustomSelectComponent implements ControlValueAccessor {
trackByValue = (_: number, option: any) => this.getOptionValue(option);
get filteredOptions(): any[] {
const opts = this.options || [];
const term = this.normalizeText(this.searchTerm);
if (!this.searchable || !term) return opts;
return opts.filter((opt) => this.normalizeText(this.getOptionLabel(opt)).includes(term));
}
onSearchInput(value: string): void {
this.searchTerm = value ?? '';
}
clearSearch(event?: Event): void {
event?.stopPropagation();
this.searchTerm = '';
}
onSearchKeydown(event: KeyboardEvent): void {
event.stopPropagation();
}
private getOptionValue(option: any): any {
if (option && typeof option === 'object') {
return option[this.valueKey];
@ -103,6 +128,14 @@ export class CustomSelectComponent implements ControlValueAccessor {
return (this.options || []).find((o) => this.getOptionValue(o) === value);
}
private normalizeText(value: string): string {
return (value ?? '')
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.toLowerCase()
.trim();
}
@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent): void {
if (!this.isOpen) return;

View File

@ -191,8 +191,11 @@
<button type="button" class="options-item" *ngIf="isSysAdmin" (click)="openManageUsersModal()">
<i class="bi bi-people"></i> Editar usuário
</button>
<button type="button" class="options-item" *ngIf="isSysAdmin" (click)="openManageClientCredentialsModal()">
<i class="bi bi-person-badge"></i> Credenciais de clientes
</button>
<button type="button" class="options-item" *ngIf="isSysAdmin" (click)="goToSystemProvisionUser()">
<i class="bi bi-shield-lock"></i> Fornecer usuário (cliente)
<i class="bi bi-shield-lock"></i> Criar credenciais do cliente
</button>
<div class="divider"></div>
<button type="button" class="options-item danger" (click)="logout()">
@ -293,7 +296,7 @@
<div class="modal-overlay" *ngIf="manageUsersOpen" (click)="closeManageUsersModal()"></div>
<div class="modal-card manage-users-modal" *ngIf="manageUsersOpen" (click)="$event.stopPropagation()">
<div class="modal-header">
<h3>Gestão de Usuários</h3>
<h3>{{ manageModalTitle }}</h3>
<button type="button" class="btn-icon close-x" (click)="closeManageUsersModal()" aria-label="Fechar">
<i class="bi bi-x-lg"></i>
</button>
@ -303,7 +306,7 @@
<div class="manage-search">
<div class="search-input-wrapper">
<i class="bi bi-search"></i>
<input type="text" placeholder="Buscar por nome ou email..." [(ngModel)]="manageSearch" (keyup.enter)="onManageSearch()" />
<input type="text" [placeholder]="manageSearchPlaceholder" [(ngModel)]="manageSearch" (keyup.enter)="onManageSearch()" />
</div>
</div>
@ -316,7 +319,7 @@
<thead>
<tr>
<th style="width: 40%;">Usuário</th>
<th style="width: 25%;" class="text-center">Permissão</th>
<th style="width: 25%;" class="text-center">Perfil</th>
<th style="width: 15%;" class="text-center">Status</th>
<th style="width: 20%;" class="text-center">Ações</th>
</tr>
@ -391,7 +394,7 @@
<div class="avatar-large">{{ target.nome.charAt(0).toUpperCase() }}</div>
<div class="info-text">
<h4>{{ target.nome }}</h4>
<span>Editando perfil</span>
<span>{{ isManageClientsMode ? 'Editando credencial do cliente' : 'Editando perfil' }}</span>
</div>
</div>
@ -403,13 +406,13 @@
<form class="user-form refined-form" id="editUserHeaderForm" [formGroup]="editUserForm" (ngSubmit)="submitEditUser()">
<div class="form-row">
<div class="form-field">
<label for="editHeaderNome">Nome Completo</label>
<label for="editHeaderNome">{{ isManageClientsMode ? 'Nome do responsável' : 'Nome Completo' }}</label>
<input id="editHeaderNome" type="text" formControlName="nome" />
</div>
</div>
<div class="form-field">
<label for="editHeaderEmail">Email Corporativo</label>
<label for="editHeaderEmail">{{ isManageClientsMode ? 'Email de acesso' : 'Email Corporativo' }}</label>
<input id="editHeaderEmail" type="email" formControlName="email" />
</div>
@ -427,7 +430,13 @@
<div class="form-row two-col align-end">
<div class="form-field">
<label for="editHeaderPermissao">Nível de Acesso</label>
<app-select id="editHeaderPermissao" formControlName="permissao" [options]="permissionOptions" labelKey="label" valueKey="value" placeholder="Selecione o nivel"></app-select>
<app-select
id="editHeaderPermissao"
formControlName="permissao"
[options]="editPermissionOptions"
labelKey="label"
valueKey="value"
placeholder="Selecione o nivel"></app-select>
</div>
<div class="form-field">
@ -452,7 +461,7 @@
(click)="confirmPermanentDeleteUser(target)"
[disabled]="editUserSubmitting"
[title]="target.ativo !== false ? 'Inative a conta antes de excluir permanentemente' : 'Excluir permanentemente'">
Excluir Permanentemente
{{ isManageClientsMode ? 'Excluir Credencial' : 'Excluir Permanentemente' }}
</button>
<button type="button" class="btn-ghost" (click)="cancelEditUser()" [disabled]="editUserSubmitting">Cancelar</button>
<button type="submit" form="editUserHeaderForm" class="btn-primary" [disabled]="editUserSubmitting || !editUserTarget">
@ -467,8 +476,8 @@
<div class="placeholder-icon">
<i class="bi bi-person-gear"></i>
</div>
<h3>Editar Usuário</h3>
<p>Selecione um usuário na lista para visualizar e editar os detalhes.</p>
<h3>{{ isManageClientsMode ? 'Editar Credencial' : 'Editar Usuário' }}</h3>
<p>{{ isManageClientsMode ? 'Selecione uma credencial de cliente para visualizar e editar os detalhes.' : 'Selecione um usuário na lista para visualizar e editar os detalhes.' }}</p>
</div>
</div>
</div>
@ -538,7 +547,7 @@
<i class="bi bi-arrow-left-right"></i> <span>Troca de número</span>
</a>
<a *ngIf="isSysAdmin" routerLink="/system/fornecer-usuario" routerLinkActive="active" class="side-item" (click)="closeMenu()">
<i class="bi bi-shield-lock-fill"></i> <span>Fornecer usuário</span>
<i class="bi bi-shield-lock-fill"></i> <span>Criar credenciais do cliente</span>
</a>
</div>
</aside>

View File

@ -62,6 +62,7 @@ export class Header implements AfterViewInit, OnDestroy {
manageUsersErrors: ApiFieldError[] = [];
manageUsersSuccess = '';
private manageUsersFeedbackTimer: ReturnType<typeof setTimeout> | null = null;
manageMode: 'users' | 'clients' = 'users';
manageUsers: any[] = [];
manageSearch = '';
managePage = 1;
@ -254,6 +255,16 @@ export class Header implements AfterViewInit, OnDestroy {
openManageUsersModal() {
if (!this.isSysAdmin) return;
this.manageMode = 'users';
this.manageUsersOpen = true;
this.closeOptions();
this.resetManageUsersState();
this.fetchManageUsers(1);
}
openManageClientCredentialsModal() {
if (!this.isSysAdmin) return;
this.manageMode = 'clients';
this.manageUsersOpen = true;
this.closeOptions();
this.resetManageUsersState();
@ -263,6 +274,7 @@ export class Header implements AfterViewInit, OnDestroy {
closeManageUsersModal() {
this.manageUsersOpen = false;
this.resetManageUsersState();
this.manageMode = 'users';
}
toggleNotifications() {
@ -660,6 +672,7 @@ export class Header implements AfterViewInit, OnDestroy {
this.usersService
.list({
search: this.manageSearch?.trim() || undefined,
permissao: this.isManageClientsMode ? 'cliente' : undefined,
page: this.managePage,
pageSize: this.managePageSize,
})
@ -720,17 +733,23 @@ export class Header implements AfterViewInit, OnDestroy {
this.usersService.getById(user.id).subscribe({
next: (full) => {
this.editUserTarget = full;
const permissao = this.isManageClientsMode ? 'cliente' : (full.permissao ?? '');
this.editUserForm.reset({
nome: full.nome ?? '',
email: full.email ?? '',
senha: '',
confirmarSenha: '',
permissao: full.permissao ?? '',
permissao,
ativo: full.ativo ?? true,
});
if (this.isManageClientsMode) {
this.editUserForm.get('permissao')?.disable({ emitEvent: false });
} else {
this.editUserForm.get('permissao')?.enable({ emitEvent: false });
}
},
error: () => {
this.editUserErrors = [{ message: 'Erro ao carregar usuario.' }];
this.editUserErrors = [{ message: this.isManageClientsMode ? 'Erro ao carregar credencial do cliente.' : 'Erro ao carregar usuário.' }];
},
});
}
@ -750,12 +769,21 @@ export class Header implements AfterViewInit, OnDestroy {
const payload: any = {};
const nome = (this.editUserForm.get('nome')?.value || '').toString().trim();
const email = (this.editUserForm.get('email')?.value || '').toString().trim();
const permissao = (this.editUserForm.get('permissao')?.value || '').toString().trim();
const permissao = this.isManageClientsMode
? 'cliente'
: (this.editUserForm.get('permissao')?.value || '').toString().trim();
const ativo = !!this.editUserForm.get('ativo')?.value;
if (nome && nome !== (this.editUserTarget.nome || '').trim()) payload.nome = nome;
if (email && email !== (this.editUserTarget.email || '').trim()) payload.email = email;
if (permissao && permissao !== (this.editUserTarget.permissao || '').trim()) payload.permissao = permissao;
if (this.isManageClientsMode) {
const targetPermissao = String(this.editUserTarget.permissao || '').trim().toLowerCase();
if (targetPermissao !== 'cliente') {
payload.permissao = 'cliente';
}
} else if (permissao && permissao !== (this.editUserTarget.permissao || '').trim()) {
payload.permissao = permissao;
}
if ((this.editUserTarget.ativo ?? true) !== ativo) payload.ativo = ativo;
const senha = (this.editUserForm.get('senha')?.value || '').toString();
@ -794,18 +822,25 @@ export class Header implements AfterViewInit, OnDestroy {
const merged = this.mergeUserUpdate(currentTarget, payload);
this.editUserSubmitting = false;
this.setEditFormDisabled(false);
this.editUserSuccess = `Usuario ${merged.nome} atualizado com sucesso.`;
this.editUserSuccess = this.isManageClientsMode
? `Credencial de ${merged.nome} atualizada com sucesso.`
: `Usuario ${merged.nome} atualizado com sucesso.`;
this.editUserTarget = merged;
this.editUserForm.patchValue({
nome: merged.nome ?? '',
email: merged.email ?? '',
permissao: merged.permissao ?? '',
permissao: this.isManageClientsMode ? 'cliente' : (merged.permissao ?? ''),
ativo: merged.ativo ?? true,
senha: '',
confirmarSenha: '',
});
this.upsertManageUser(merged);
this.showManageUsersFeedback(`Usuario ${merged.nome} atualizado com sucesso.`, 'success');
this.showManageUsersFeedback(
this.isManageClientsMode
? `Credencial de ${merged.nome} atualizada com sucesso.`
: `Usuario ${merged.nome} atualizado com sucesso.`,
'success'
);
},
error: (err: HttpErrorResponse) => {
this.editUserSubmitting = false;
@ -814,12 +849,17 @@ export class Header implements AfterViewInit, OnDestroy {
if (Array.isArray(apiErrors)) {
this.editUserErrors = apiErrors.map((e: any) => ({
field: e?.field,
message: e?.message || 'Erro ao atualizar usuario.',
message: e?.message || (this.isManageClientsMode ? 'Erro ao atualizar credencial do cliente.' : 'Erro ao atualizar usuario.'),
}));
} else {
this.editUserErrors = [{ message: err?.error?.message || 'Erro ao atualizar usuario.' }];
this.editUserErrors = [{
message: err?.error?.message || (this.isManageClientsMode ? 'Erro ao atualizar credencial do cliente.' : 'Erro ao atualizar usuario.')
}];
}
this.showManageUsersFeedback(this.editUserErrors[0]?.message || 'Erro ao atualizar usuario.', 'error');
this.showManageUsersFeedback(
this.editUserErrors[0]?.message || (this.isManageClientsMode ? 'Erro ao atualizar credencial do cliente.' : 'Erro ao atualizar usuario.'),
'error'
);
},
});
}
@ -827,11 +867,13 @@ export class Header implements AfterViewInit, OnDestroy {
async confirmToggleUserStatus(user: any) {
const nextActive = user.ativo === false;
const actionLabel = nextActive ? 'reativar' : 'inativar';
const entity = this.isManageClientsMode ? 'Credencial do Cliente' : 'Usuário';
const entityLower = this.isManageClientsMode ? 'credencial do cliente' : 'usuário';
const confirmed = await confirmActionModal({
title: nextActive ? 'Reativar Usuário' : 'Inativar Usuário',
title: nextActive ? `Reativar ${entity}` : `Inativar ${entity}`,
message: nextActive
? `Deseja reativar o usuário ${user.nome}? Ele voltará a ter acesso ao sistema.`
: `Deseja inativar o usuário ${user.nome}? A conta ficará sem acesso até ser reativada.`,
? `Deseja reativar ${entityLower} ${user.nome}? O acesso ao sistema será liberado novamente.`
: `Deseja inativar ${entityLower} ${user.nome}? O acesso ao sistema ficará bloqueado até reativação.`,
confirmLabel: nextActive ? 'Reativar' : 'Inativar',
tone: nextActive ? 'neutral' : 'warning',
});
@ -845,11 +887,13 @@ export class Header implements AfterViewInit, OnDestroy {
this.editUserTarget = { ...this.editUserTarget, ativo: nextActive };
this.editUserForm.patchValue({ ativo: nextActive, senha: '', confirmarSenha: '' });
this.editUserErrors = [];
this.editUserSuccess = `Usuario ${user.nome} ${nextActive ? 'reativado' : 'inativado'} com sucesso.`;
this.editUserSuccess = this.isManageClientsMode
? `Credencial de ${user.nome} ${nextActive ? 'reativada' : 'inativada'} com sucesso.`
: `Usuario ${user.nome} ${nextActive ? 'reativado' : 'inativado'} com sucesso.`;
}
},
error: (err: HttpErrorResponse) => {
const message = err?.error?.message || `Erro ao ${actionLabel} usuario.`;
const message = err?.error?.message || `Erro ao ${actionLabel} ${this.isManageClientsMode ? 'credencial do cliente' : 'usuario'}.`;
if (this.editUserTarget?.id === user.id) {
this.editUserSuccess = '';
this.editUserErrors = [{ message }];
@ -860,7 +904,9 @@ export class Header implements AfterViewInit, OnDestroy {
async confirmPermanentDeleteUser(user: any) {
if (user?.ativo !== false) {
const message = 'Inative a conta antes de excluir permanentemente.';
const message = this.isManageClientsMode
? 'Inative a credencial antes de excluir permanentemente.'
: 'Inative a conta antes de excluir permanentemente.';
if (this.editUserTarget?.id === user?.id) {
this.editUserSuccess = '';
this.editUserErrors = [{ message }];
@ -870,7 +916,9 @@ export class Header implements AfterViewInit, OnDestroy {
return;
}
const confirmed = await confirmDeletionWithTyping(`o usuário ${user.nome}`);
const confirmed = await confirmDeletionWithTyping(
this.isManageClientsMode ? `a credencial do cliente ${user.nome}` : `o usuário ${user.nome}`
);
if (!confirmed) return;
this.usersService.delete(user.id).subscribe({
@ -883,8 +931,8 @@ export class Header implements AfterViewInit, OnDestroy {
error: (err: HttpErrorResponse) => {
const apiErrors = err?.error?.errors;
const message = Array.isArray(apiErrors)
? (apiErrors[0]?.message || 'Erro ao excluir usuario.')
: (err?.error?.message || 'Erro ao excluir usuario.');
? (apiErrors[0]?.message || (this.isManageClientsMode ? 'Erro ao excluir credencial do cliente.' : 'Erro ao excluir usuario.'))
: (err?.error?.message || (this.isManageClientsMode ? 'Erro ao excluir credencial do cliente.' : 'Erro ao excluir usuario.'));
if (this.editUserTarget?.id === user.id) {
this.editUserSuccess = '';
@ -936,6 +984,30 @@ export class Header implements AfterViewInit, OnDestroy {
this.cancelEditUser();
}
get isManageClientsMode(): boolean {
return this.manageMode === 'clients';
}
get manageModalTitle(): string {
return this.isManageClientsMode ? 'Credenciais de Clientes' : 'Gestão de Usuários';
}
get manageListTitle(): string {
return this.isManageClientsMode ? 'Credenciais de Cliente' : 'Usuários';
}
get manageSearchPlaceholder(): string {
return this.isManageClientsMode
? 'Buscar por cliente, nome ou email...'
: 'Buscar por nome ou email...';
}
get editPermissionOptions() {
return this.isManageClientsMode
? [{ value: 'cliente', label: 'Cliente' }]
: this.permissionOptions;
}
private normalizeField(field?: string | null): string {
return (field || '').trim().toLowerCase();
}
@ -947,7 +1019,12 @@ export class Header implements AfterViewInit, OnDestroy {
private setEditFormDisabled(disabled: boolean) {
if (disabled) this.editUserForm.disable({ emitEvent: false });
else this.editUserForm.enable({ emitEvent: false });
else {
this.editUserForm.enable({ emitEvent: false });
if (this.isManageClientsMode) {
this.editUserForm.get('permissao')?.disable({ emitEvent: false });
}
}
}
private upsertManageUser(user: any) {

View File

@ -231,34 +231,31 @@
<div class="edit-sections">
<details open class="detail-box">
<summary class="box-header">
<span><i class="bi bi-link-45deg me-2"></i> Vínculo com GERAL</span>
<span><i class="bi bi-link-45deg me-2"></i> Vínculo com Reserva</span>
<i class="bi bi-chevron-down ms-auto transition-icon"></i>
</summary>
<div class="box-body">
<div class="form-grid">
<div class="form-field span-2">
<label>Cliente (GERAL)</label>
<app-select
class="form-select"
size="sm"
[options]="clientsFromGeral"
[(ngModel)]="createModel.selectedClient"
(ngModelChange)="onCreateClientChange()"
[disabled]="createClientsLoading"
></app-select>
</div>
<div class="form-field span-2">
<label>Linha (GERAL)</label>
<label>Linha (RESERVA)</label>
<app-select
class="form-select"
size="sm"
[options]="lineOptionsCreate"
labelKey="label"
valueKey="id"
[searchable]="true"
searchPlaceholder="Pesquisar linha da reserva..."
[(ngModel)]="createModel.mobileLineId"
(ngModelChange)="onCreateLineChange()"
[disabled]="createLinesLoading || !createModel.selectedClient"
[disabled]="createLinesLoading"
placeholder="Selecione uma linha da Reserva..."
></app-select>
<small class="field-hint" *ngIf="createLinesLoading">Carregando linhas da Reserva...</small>
</div>
<div class="form-field">
<label>Total Franquia Line</label>
<input class="form-control form-control-sm bg-light" [value]="formatFranquiaLine(createFranquiaLineTotal)" readonly />
</div>
</div>
</div>
@ -291,7 +288,10 @@
<label>Razão Social</label>
<input class="form-control form-control-sm" [(ngModel)]="createModel.razaoSocial" />
</div>
<div class="form-field field-line"><label>Linha</label><input class="form-control form-control-sm" inputmode="numeric" [(ngModel)]="createModel.linha" /></div>
<div class="form-field field-line">
<label>Linha</label>
<input class="form-control form-control-sm bg-light" [value]="createModel.linha || ''" readonly />
</div>
<div class="form-field field-item field-auto">
<label>Item (Automático)</label>
<input class="form-control form-control-sm bg-light" type="number" [(ngModel)]="createModel.item" readonly title="Gerado automaticamente pelo sistema" />
@ -357,7 +357,26 @@
<label>Razão Social</label>
<input class="form-control form-control-sm" [(ngModel)]="editModel.razaoSocial" />
</div>
<div class="form-field field-line"><label>Linha</label><input class="form-control form-control-sm" inputmode="numeric" [(ngModel)]="editModel.linha" /></div>
<div class="form-field field-line">
<label>Linha (Reserva)</label>
<app-select
class="form-select"
size="sm"
[options]="editLineOptions"
labelKey="label"
valueKey="id"
[searchable]="true"
searchPlaceholder="Pesquisar linha da reserva..."
[(ngModel)]="editSelectedLineId"
(ngModelChange)="onEditLineChange()"
[disabled]="createLinesLoading"
placeholder="Selecione uma linha da Reserva..."
></app-select>
</div>
<div class="form-field field-auto">
<label>Total Franquia Line</label>
<input class="form-control form-control-sm bg-light" [value]="formatFranquiaLine(editFranquiaLineTotal)" readonly />
</div>
<div class="form-field field-item field-auto">
<label>Item (Automático)</label>
<input class="form-control form-control-sm bg-light" type="number" [(ngModel)]="editModel.item" readonly title="Gerado automaticamente pelo sistema" />

View File

@ -24,6 +24,7 @@ interface LineOptionDto {
item: number;
linha: string | null;
usuario: string | null;
franquiaLine?: number | null;
label?: string;
}
@ -94,13 +95,15 @@ export class DadosUsuarios implements OnInit {
createSaving = false;
createModel: any = null;
createDateNascimento = '';
clientsFromGeral: string[] = [];
createFranquiaLineTotal = 0;
editFranquiaLineTotal = 0;
editSelectedLineId = '';
editLineOptions: LineOptionDto[] = [];
lineOptionsCreate: LineOptionDto[] = [];
readonly tipoPessoaOptions: SimpleOption[] = [
{ label: 'Pessoa Física', value: 'PF' },
{ label: 'Pessoa Jurídica', value: 'PJ' },
];
createClientsLoading = false;
createLinesLoading = false;
isSysAdmin = false;
@ -295,7 +298,11 @@ export class DadosUsuarios implements OnInit {
razaoSocial: fullData.razaoSocial || (tipo === 'PJ' ? fullData.cliente : '')
};
this.editDateNascimento = this.toDateInput(fullData.dataNascimento);
this.editFranquiaLineTotal = 0;
this.editSelectedLineId = '';
this.editLineOptions = [];
this.editOpen = true;
this.loadReserveLinesForSelects();
},
error: () => this.showToast('Erro ao abrir edição', 'danger')
});
@ -307,6 +314,9 @@ export class DadosUsuarios implements OnInit {
this.editModel = null;
this.editDateNascimento = '';
this.editingId = null;
this.editSelectedLineId = '';
this.editLineOptions = [];
this.editFranquiaLineTotal = 0;
}
onEditTipoChange() {
@ -369,13 +379,14 @@ export class DadosUsuarios implements OnInit {
if (!this.isSysAdmin) return;
this.resetCreateModel();
this.createOpen = true;
this.preloadGeralClients();
this.loadReserveLinesForSelects();
}
closeCreate() {
this.createOpen = false;
this.createSaving = false;
this.createModel = null;
this.createFranquiaLineTotal = 0;
}
private resetCreateModel() {
@ -397,33 +408,9 @@ export class DadosUsuarios implements OnInit {
telefoneFixo: ''
};
this.createDateNascimento = '';
this.createFranquiaLineTotal = 0;
this.lineOptionsCreate = [];
this.createLinesLoading = false;
this.createClientsLoading = false;
}
private preloadGeralClients() {
this.createClientsLoading = true;
this.linesService.getClients().subscribe({
next: (list) => {
this.clientsFromGeral = list ?? [];
this.createClientsLoading = false;
},
error: () => {
this.clientsFromGeral = [];
this.createClientsLoading = false;
}
});
}
onCreateClientChange() {
const c = (this.createModel?.selectedClient ?? '').trim();
this.createModel.mobileLineId = '';
this.createModel.linha = '';
this.createModel.cliente = c;
this.lineOptionsCreate = [];
if (c) this.loadLinesForClient(c);
}
onCreateTipoChange() {
@ -438,12 +425,9 @@ export class DadosUsuarios implements OnInit {
}
}
private loadLinesForClient(cliente: string) {
const c = (cliente ?? '').trim();
if (!c) return;
private loadReserveLinesForSelects(onDone?: () => void) {
this.createLinesLoading = true;
this.linesService.getLinesByClient(c).subscribe({
this.linesService.getLinesByClient('RESERVA').subscribe({
next: (items: any[]) => {
const mapped: LineOptionDto[] = (items ?? [])
.filter(x => !!String(x?.id ?? '').trim())
@ -457,12 +441,16 @@ export class DadosUsuarios implements OnInit {
.filter(x => !!String(x.linha ?? '').trim());
this.lineOptionsCreate = mapped;
if (this.editModel) this.syncEditLineOptions();
this.createLinesLoading = false;
onDone?.();
},
error: () => {
this.lineOptionsCreate = [];
this.editLineOptions = [];
this.createLinesLoading = false;
this.showToast('Erro ao carregar linhas da GERAL.', 'danger');
this.showToast('Erro ao carregar linhas da Reserva.', 'danger');
onDone?.();
}
});
}
@ -477,13 +465,56 @@ export class DadosUsuarios implements OnInit {
});
}
onEditLineChange() {
const id = String(this.editSelectedLineId ?? '').trim();
if (!id || id === '__CURRENT__') return;
this.linesService.getById(id).subscribe({
next: (d: MobileLineDetail) => this.applyLineDetailToEdit(d),
error: () => this.showToast('Erro ao carregar dados da linha.', 'danger')
});
}
private syncEditLineOptions() {
if (!this.editModel) {
this.editLineOptions = [];
this.editSelectedLineId = '';
return;
}
const currentLine = String(this.editModel.linha ?? '').trim();
const fromReserva = this.lineOptionsCreate.find((x) => String(x.linha ?? '').trim() === currentLine);
const options = [...this.lineOptionsCreate];
if (currentLine && !fromReserva) {
options.unshift({
id: '__CURRENT__',
item: Number(this.editModel.item ?? 0),
linha: currentLine,
usuario: this.editModel.cliente ?? null,
label: `Atual • ${currentLine}`
});
}
this.editLineOptions = options;
this.editSelectedLineId = fromReserva?.id ?? (currentLine ? '__CURRENT__' : '');
if (fromReserva?.id) {
this.onEditLineChange();
}
}
private applyLineDetailToCreate(d: MobileLineDetail) {
this.createModel.linha = d.linha ?? '';
this.createModel.cliente = d.cliente ?? this.createModel.cliente ?? '';
this.createFranquiaLineTotal = this.toNullableNumber(d.franquiaLine) ?? 0;
if (!String(this.createModel.item ?? '').trim() && d.item) {
this.createModel.item = String(d.item);
}
const lineClient = String(d.cliente ?? '').trim();
const isReserva = lineClient.localeCompare('RESERVA', 'pt-BR', { sensitivity: 'base' }) === 0;
if (!isReserva && lineClient) {
this.createModel.cliente = lineClient;
}
if ((this.createModel.tipoPessoa ?? '').toUpperCase() === 'PJ') {
if (!this.createModel.razaoSocial) this.createModel.razaoSocial = this.createModel.cliente;
} else {
@ -491,6 +522,15 @@ export class DadosUsuarios implements OnInit {
}
}
private applyLineDetailToEdit(d: MobileLineDetail) {
if (!this.editModel) return;
this.editModel.linha = d.linha ?? this.editModel.linha;
this.editFranquiaLineTotal = this.toNullableNumber(d.franquiaLine) ?? 0;
if (!String(this.editModel.item ?? '').trim() && d.item) {
this.editModel.item = d.item;
}
}
saveCreate() {
if (!this.createModel) return;
this.createSaving = true;
@ -584,6 +624,11 @@ export class DadosUsuarios implements OnInit {
return Number.isNaN(n) ? null : n;
}
formatFranquiaLine(value: any): string {
const n = this.toNullableNumber(value) ?? 0;
return `${n.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 2 })} GB`;
}
private normalizeTipo(row: UserDataRow | null | undefined): 'PF' | 'PJ' {
const t = (row?.tipoPessoa ?? '').toString().trim().toUpperCase();
if (t === 'PJ') return 'PJ';

View File

@ -7,10 +7,12 @@
<div class="page-head fade-in-up">
<div class="head-content">
<div class="badge-pill">
<i class="bi bi-grid-1x2-fill"></i> Visão Geral
<i class="bi bi-grid-1x2-fill"></i> {{ isCliente ? 'Visão Cliente' : 'Visão Geral' }}
</div>
<h1 class="page-title">Dashboard de Gestão de Linhas</h1>
<p class="page-subtitle">Painel operacional com foco em status, cobertura e histórico da base.</p>
<h1 class="page-title">{{ isCliente ? 'Dashboard do Cliente' : 'Dashboard de Gestão de Linhas' }}</h1>
<p class="page-subtitle">
{{ isCliente ? 'Acompanhe suas linhas em tempo real com foco em operação e disponibilidade.' : 'Painel operacional com foco em status, cobertura e histórico da base.' }}
</p>
</div>
<div class="head-actions">
@ -27,7 +29,7 @@
</div>
</div>
<div class="hero-grid fade-in-up" [style.animation-delay]="'100ms'">
<div class="hero-grid fade-in-up" [style.animation-delay]="'100ms'" *ngIf="!isCliente || clientOverview.hasData">
<div class="hero-card" *ngFor="let k of kpis; trackBy: trackByKpiKey">
<div class="hero-icon">
<i [class]="k.icon"></i>
@ -326,45 +328,120 @@
</ng-container>
<ng-template #clienteDashboard>
<div class="dashboard-section fade-in-up" [style.animation-delay]="'180ms'">
<div class="section-top-row">
<div class="card-modern card-status">
<div class="card-header-clean">
<div class="header-icon brand"><i class="bi bi-pie-chart-fill"></i></div>
<div class="header-text">
<h3>Status da Base</h3>
<p>Distribuição atual das linhas</p>
<ng-container *ngIf="clientOverview.hasData; else clienteSemDados">
<div class="context-title fade-in-up" [style.animation-delay]="'180ms'">
<h2>Monitoramento da Sua Base</h2>
<p>Visão operacional das suas linhas para acompanhar uso, status e disponibilidade.</p>
</div>
<div class="dashboard-section fade-in-up" [style.animation-delay]="'220ms'">
<div class="section-top-row">
<div class="card-modern card-status">
<div class="card-header-clean">
<div class="header-icon brand"><i class="bi bi-pie-chart-fill"></i></div>
<div class="header-text">
<h3>Status das Linhas</h3>
<p>Distribuição atual da sua base</p>
</div>
</div>
<div class="card-body-split">
<div class="chart-wrapper-pie">
<canvas #chartStatusPie></canvas>
</div>
<div class="status-list">
<div class="status-item">
<span class="dot d-active"></span>
<span class="lbl">Ativas</span>
<span class="val">{{ statusResumo.ativos | number:'1.0-0' }}</span>
</div>
<div class="status-item">
<span class="dot d-blocked-soft"></span>
<span class="lbl">Demais Linhas</span>
<span class="val">{{ clientDemaisLinhas | number:'1.0-0' }}</span>
</div>
<div class="status-item total-row">
<span class="lbl">Total</span>
<span class="val">{{ statusResumo.total | number:'1.0-0' }}</span>
</div>
</div>
</div>
</div>
<div class="card-body-split">
<div class="chart-wrapper-pie">
<canvas #chartStatusPie></canvas>
<div class="card-modern">
<div class="card-header-clean">
<div class="header-icon blue"><i class="bi bi-wifi"></i></div>
<div class="header-text">
<h3>Faixa de Franquia Line</h3>
<p>Quantidade de linhas por faixa de franquia contratada</p>
</div>
</div>
<div class="status-list">
<div class="status-item">
<span class="dot d-active"></span>
<span class="lbl">Ativas</span>
<span class="val">{{ statusResumo.ativos | number:'1.0-0' }}</span>
</div>
<div class="status-item">
<span class="dot d-blocked"></span>
<span class="lbl">Bloqueadas</span>
<span class="val">{{ statusResumo.bloqueadas | number:'1.0-0' }}</span>
</div>
<div class="status-item">
<span class="dot d-reserve"></span>
<span class="lbl">Reserva</span>
<span class="val">{{ statusResumo.reservas | number:'1.0-0' }}</span>
</div>
<div class="status-item total-row">
<span class="lbl">Total</span>
<span class="val">{{ statusResumo.total | number:'1.0-0' }}</span>
</div>
<div class="chart-wrapper-bar compact-half">
<canvas #chartLinhasPorFranquia></canvas>
</div>
</div>
</div>
</div>
</div>
<div class="dashboard-section fade-in-up" [style.animation-delay]="'260ms'">
<div class="card-modern full-width">
<div class="card-header-clean">
<div class="header-text">
<h3>Top Planos (Qtd. Linhas)</h3>
<p>Planos com maior volume na sua operação</p>
</div>
</div>
<div class="chart-wrapper-bar compact">
<canvas #chartResumoTopPlanos></canvas>
</div>
</div>
<div class="grid-halves mt-3 client-secondary-grid">
<div class="card-modern">
<div class="card-header-clean">
<div class="header-text">
<h3>Top Usuários (Qtd. Linhas)</h3>
<p>Apenas usuários de fato (sem bloqueados/aguardando)</p>
</div>
</div>
<div class="chart-wrapper-bar compact">
<canvas #chartResumoTopClientes></canvas>
</div>
</div>
<div class="card-modern">
<div class="card-header-clean">
<div class="header-icon brand"><i class="bi bi-sim"></i></div>
<div class="header-text">
<h3>Tipo de Chip</h3>
<p>Distribuição entre e-SIM, SIMCARD e outros</p>
</div>
</div>
<div class="chart-wrapper-pie">
<canvas #chartTipoChip></canvas>
</div>
</div>
</div>
</div>
</ng-container>
<ng-template #clienteSemDados>
<div class="dashboard-section fade-in-up" [style.animation-delay]="'180ms'">
<div class="card-modern full-width">
<div class="card-header-clean">
<div class="header-icon warning"><i class="bi bi-info-circle-fill"></i></div>
<div class="header-text">
<h3>Sem dados para exibição</h3>
<p>Não encontramos linhas vinculadas ao seu acesso no momento.</p>
</div>
</div>
<div class="card-body-grid">
<p class="mb-0 text-muted">
Assim que a base deste cliente estiver disponível na página Geral, os KPIs e gráficos serão atualizados automaticamente.
</p>
</div>
</div>
</div>
</ng-template>
</ng-template>
</div>
</section>

View File

@ -163,6 +163,10 @@
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 16px;
margin-bottom: 32px;
@media (min-width: 1500px) {
grid-template-columns: repeat(6, minmax(0, 1fr));
}
}
.hero-card {

View File

@ -111,6 +111,7 @@ type InsightsChartSeries = {
type InsightsKpisVivo = {
qtdLinhas?: number | null;
totalFranquiaGb?: number | null;
totalFranquiaLine?: number | null;
totalBaseMensal?: number | null;
totalAdicionaisMensal?: number | null;
totalGeralMensal?: number | null;
@ -155,6 +156,13 @@ type DashboardGeralInsightsDto = {
};
type DashboardLineListItemDto = {
linha?: string | null;
cliente?: string | null;
usuario?: string | null;
skil?: string | null;
planoContrato?: string | null;
status?: string | null;
franquiaLine?: number | null;
gestaoVozDados?: number | null;
skeelo?: number | null;
vivoNewsPlus?: number | null;
@ -164,13 +172,6 @@ type DashboardLineListItemDto = {
tipoDeChip?: string | null;
};
type DashboardLinesPageDto = {
page: number;
pageSize: number;
total: number;
items: DashboardLineListItemDto[];
};
type ResumoTopCliente = {
cliente: string;
linhas: number;
@ -193,6 +194,18 @@ type ResumoDiferencaPjPf = {
totalLinhas: number | null;
};
type ClientDashboardOverview = {
hasData: boolean;
totalLinhas: number;
ativas: number;
bloqueadas: number;
reservas: number;
franquiaLineTotalGb: number;
planosContratados: number;
usuariosComLinha: number;
outrosStatus: number;
};
@Component({
selector: 'app-dashboard',
standalone: true,
@ -286,6 +299,17 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
resumo: ResumoResponse | null = null;
resumoTopN = 5;
resumoTopOptions = [5, 10, 15];
clientOverview: ClientDashboardOverview = {
hasData: false,
totalLinhas: 0,
ativas: 0,
bloqueadas: 0,
reservas: 0,
franquiaLineTotalGb: 0,
planosContratados: 0,
usuariosComLinha: 0,
outrosStatus: 0,
};
// Resumo Derived Data
resumoTopClientes: ResumoTopCliente[] = [];
@ -348,11 +372,14 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
const isGestor = this.authService.hasRole('gestor');
this.isCliente = !(isSysAdmin || isGestor);
this.loadDashboard();
if (!this.isCliente) {
this.loadInsights();
this.loadResumoExecutive();
if (this.isCliente) {
this.loadClientDashboardData();
return;
}
this.loadDashboard();
this.loadInsights();
this.loadResumoExecutive();
}
ngAfterViewInit(): void {
@ -389,6 +416,245 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
}
}
private async loadClientDashboardData() {
this.loading = true;
this.errorMsg = null;
this.dataReady = false;
this.resumoLoading = true;
this.resumoError = null;
this.resumoReady = false;
try {
const [operacionais, reservas] = await Promise.all([
this.fetchAllDashboardLines(false),
this.fetchAllDashboardLines(true),
]);
const allLines = [...operacionais, ...reservas];
this.applyClientLineAggregates(allLines);
this.loading = false;
this.resumoLoading = false;
this.dataReady = true;
this.resumoReady = true;
this.tryBuildCharts();
this.tryBuildResumoCharts();
} catch (error) {
this.loading = false;
this.resumoLoading = false;
this.resumoReady = false;
this.dataReady = false;
this.errorMsg = this.isNetworkError(error)
? 'Falha ao carregar o Dashboard. Verifique a conexão.'
: 'Falha ao carregar os dados do cliente.';
this.clearClientDashboardState();
}
}
private async fetchAllDashboardLines(onlyReserva: boolean): Promise<DashboardLineListItemDto[]> {
const pageSize = 500;
let page = 1;
const all: DashboardLineListItemDto[] = [];
while (true) {
let params = new HttpParams()
.set('page', String(page))
.set('pageSize', String(pageSize));
if (onlyReserva) {
params = params.set('skil', 'RESERVA');
}
const response = await firstValueFrom(this.http.get<any>(`${this.baseApi}/lines`, { params }));
const itemsRaw = this.readNode(response, 'items', 'Items');
const items = Array.isArray(itemsRaw) ? (itemsRaw as DashboardLineListItemDto[]) : [];
all.push(...items);
const total = this.toNumberOrNull(this.readNode(response, 'total', 'Total'));
if (!items.length) break;
if (total !== null && all.length >= total) break;
if (items.length < pageSize) break;
page += 1;
}
return all;
}
private applyClientLineAggregates(
allLines: DashboardLineListItemDto[]
): void {
const planMap = new Map<string, number>();
const userMap = new Map<string, number>();
const franquiaBandMap = new Map<string, number>();
let totalLinhas = 0;
let ativas = 0;
let bloqueadas = 0;
let reservas = 0;
let outrosStatus = 0;
let franquiaLineTotalGb = 0;
let eSim = 0;
let simCard = 0;
let outrosChip = 0;
for (const line of allLines) {
totalLinhas += 1;
const isReserva = this.isReservaLine(line);
const status = this.normalizeSeriesKey(this.readLineString(line, 'status', 'Status'));
const planoContrato = this.readLineString(line, 'planoContrato', 'PlanoContrato').trim();
const usuario = this.readLineString(line, 'usuario', 'Usuario').trim();
const usuarioKey = this.normalizeSeriesKey(usuario);
const franquiaLine = this.readLineNumber(line, 'franquiaLine', 'FranquiaLine');
franquiaLineTotalGb += franquiaLine > 0 ? franquiaLine : 0;
if (isReserva) {
reservas += 1;
} else if (status.includes('ATIV')) {
ativas += 1;
} else if (
status.includes('BLOQUE') ||
status.includes('PERDA') ||
status.includes('ROUBO') ||
status.includes('SUSPEN') ||
status.includes('CANCEL')
) {
bloqueadas += 1;
} else {
outrosStatus += 1;
}
if (!isReserva) {
const planoKey = planoContrato || 'Sem plano';
planMap.set(planoKey, (planMap.get(planoKey) ?? 0) + 1);
if (this.shouldIncludeTopUsuario(usuarioKey, status)) {
userMap.set(usuario, (userMap.get(usuario) ?? 0) + 1);
}
const faixa = this.resolveFranquiaLineBand(franquiaLine);
franquiaBandMap.set(faixa, (franquiaBandMap.get(faixa) ?? 0) + 1);
}
const chipType = this.normalizeChipType(this.readLineString(line, 'tipoDeChip', 'TipoDeChip'));
if (chipType === 'ESIM') {
eSim += 1;
} else if (chipType === 'SIMCARD') {
simCard += 1;
} else {
outrosChip += 1;
}
}
const topPlanos = Array.from(planMap.entries())
.map(([plano, linhas]) => ({ plano, linhas }))
.sort((a, b) => b.linhas - a.linhas || a.plano.localeCompare(b.plano, 'pt-BR'))
.slice(0, this.resumoTopN);
const topUsuarios = Array.from(userMap.entries())
.map(([cliente, linhas]) => ({ cliente, linhas }))
.sort((a, b) => b.linhas - a.linhas || a.cliente.localeCompare(b.cliente, 'pt-BR'))
.slice(0, this.resumoTopN);
const franquiaOrder = ['Sem franquia', 'Até 10 GB', '10 a 20 GB', '20 a 50 GB', 'Acima de 50 GB'];
const franquiaLabels = franquiaOrder.filter((label) => (franquiaBandMap.get(label) ?? 0) > 0);
this.franquiaLabels = franquiaLabels.length ? franquiaLabels : franquiaOrder;
this.franquiaValues = this.franquiaLabels.map((label) => franquiaBandMap.get(label) ?? 0);
this.tipoChipLabels = ['e-SIM', 'SIMCARD', 'Outros'];
this.tipoChipValues = [eSim, simCard, outrosChip];
this.travelLabels = [];
this.travelValues = [];
this.adicionaisLabels = [];
this.adicionaisValues = [];
this.adicionaisTotals = [];
this.insights = null;
this.rebuildAdicionaisComparativo(null);
this.statusResumo = {
total: totalLinhas,
ativos: ativas,
bloqueadas,
perdaRoubo: 0,
bloq120: 0,
reservas,
outras: outrosStatus,
};
this.clientOverview = {
hasData: totalLinhas > 0,
totalLinhas,
ativas,
bloqueadas,
reservas,
franquiaLineTotalGb,
planosContratados: planMap.size,
usuariosComLinha: userMap.size,
outrosStatus,
};
this.resumoTopPlanos = topPlanos;
this.resumoPlanosLabels = topPlanos.map((x) => x.plano);
this.resumoPlanosValues = topPlanos.map((x) => x.linhas);
this.resumoTopClientes = topUsuarios;
this.resumoClientesLabels = topUsuarios.map((x) => x.cliente);
this.resumoClientesValues = topUsuarios.map((x) => x.linhas);
this.resumoTopReserva = [];
this.resumoReservaLabels = [];
this.resumoReservaValues = [];
this.resumoPfPjLabels = [];
this.resumoPfPjValues = [];
this.resumoDiferencaPjPf = {
pfLinhas: null,
pjLinhas: null,
totalLinhas: null,
};
this.resumo = null;
this.rebuildPrimaryKpis();
}
private clearClientDashboardState() {
this.clientOverview = {
hasData: false,
totalLinhas: 0,
ativas: 0,
bloqueadas: 0,
reservas: 0,
franquiaLineTotalGb: 0,
planosContratados: 0,
usuariosComLinha: 0,
outrosStatus: 0,
};
this.statusResumo = {
total: 0,
ativos: 0,
bloqueadas: 0,
perdaRoubo: 0,
bloq120: 0,
reservas: 0,
outras: 0,
};
this.franquiaLabels = [];
this.franquiaValues = [];
this.tipoChipLabels = [];
this.tipoChipValues = [];
this.resumoTopClientes = [];
this.resumoTopPlanos = [];
this.resumoTopReserva = [];
this.resumoPlanosLabels = [];
this.resumoPlanosValues = [];
this.resumoClientesLabels = [];
this.resumoClientesValues = [];
this.resumoReservaLabels = [];
this.resumoReservaValues = [];
this.rebuildPrimaryKpis();
this.destroyCharts();
this.destroyResumoCharts();
}
private isNetworkError(error: unknown): boolean {
if (error instanceof HttpErrorResponse) {
return error.status === 0;
@ -448,6 +714,10 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
}
onResumoTopNChange() {
if (this.isCliente) {
void this.loadClientDashboardData();
return;
}
this.buildResumoDerived();
this.tryBuildResumoCharts();
}
@ -536,6 +806,7 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
vivo: {
qtdLinhas: this.toNumberOrNull(this.readNode(vivoRaw, 'qtdLinhas', 'QtdLinhas')),
totalFranquiaGb: this.toNumberOrNull(this.readNode(vivoRaw, 'totalFranquiaGb', 'TotalFranquiaGb')),
totalFranquiaLine: this.toNumberOrNull(this.readNode(vivoRaw, 'totalFranquiaLine', 'TotalFranquiaLine')),
totalBaseMensal: this.toNumberOrNull(this.readNode(vivoRaw, 'totalBaseMensal', 'TotalBaseMensal')),
totalAdicionaisMensal: this.toNumberOrNull(this.readNode(vivoRaw, 'totalAdicionaisMensal', 'TotalAdicionaisMensal')),
totalGeralMensal: this.toNumberOrNull(this.readNode(vivoRaw, 'totalGeralMensal', 'TotalGeralMensal')),
@ -783,6 +1054,7 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
}
private async loadFallbackFromLinesIfNeeded(force = false): Promise<void> {
if (this.isCliente) return;
if (!isPlatformBrowser(this.platformId) || this.fallbackInsightsLoading) return;
const syncIndex = this.adicionaisLabels.findIndex(
@ -901,6 +1173,58 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
return '';
}
private isReservaLine(line: DashboardLineListItemDto): boolean {
const cliente = this.normalizeSeriesKey(this.readLineString(line, 'cliente', 'Cliente'));
const usuario = this.normalizeSeriesKey(this.readLineString(line, 'usuario', 'Usuario'));
const skil = this.normalizeSeriesKey(this.readLineString(line, 'skil', 'Skil'));
return cliente === 'RESERVA' || usuario === 'RESERVA' || skil === 'RESERVA';
}
private shouldIncludeTopUsuario(usuarioKey: string, statusKey: string): boolean {
if (!usuarioKey) return false;
const invalidUserTokens = [
'SEMUSUARIO',
'AGUARDANDOUSUARIO',
'AGUARDANDO',
'BLOQUEAR',
'BLOQUEAD',
'BLOQUEADO',
'RESERVA',
'NAOATRIBUIDO',
'PENDENTE',
];
if (invalidUserTokens.some((token) => usuarioKey.includes(token))) {
return false;
}
const blockedStatusTokens = ['BLOQUE', 'PERDA', 'ROUBO', 'SUSPEN', 'CANCEL', 'AGUARD'];
return !blockedStatusTokens.some((token) => statusKey.includes(token));
}
private resolveFranquiaLineBand(value: number): string {
if (!Number.isFinite(value) || value <= 0) return 'Sem franquia';
if (value < 10) return 'Até 10 GB';
if (value < 20) return '10 a 20 GB';
if (value < 50) return '20 a 50 GB';
return 'Acima de 50 GB';
}
private extractDddFromLine(value: string | null | undefined): string | null {
const digits = (value ?? '').replace(/\D/g, '');
if (!digits) return null;
if (digits.startsWith('55') && digits.length >= 12) {
return digits.slice(2, 4);
}
if (digits.length >= 10) {
return digits.slice(0, 2);
}
return null;
}
private destroyInsightsCharts() {
try { this.chartFranquia?.destroy(); } catch {}
try { this.chartAdicionais?.destroy(); } catch {}
@ -924,36 +1248,46 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
private rebuildPrimaryKpis() {
if (this.isCliente) {
this.kpis = [
const overview = this.clientOverview;
const cards: KpiCard[] = [
{
key: 'linhas_total',
title: 'Total de Linhas',
value: this.formatInt(this.dashboardRaw?.totalLinhas ?? this.statusResumo.total),
value: this.formatInt(overview.totalLinhas),
icon: 'bi bi-sim-fill',
hint: 'Base geral',
hint: 'Base do cliente',
},
{
key: 'linhas_ativas',
title: 'Linhas Ativas',
value: this.formatInt(this.dashboardRaw?.ativos ?? this.statusResumo.ativos),
value: this.formatInt(overview.ativas),
icon: 'bi bi-check2-circle',
hint: 'Status ativo',
},
{
key: 'linhas_bloqueadas',
title: 'Linhas Bloqueadas',
value: this.formatInt(this.dashboardRaw?.bloqueados ?? this.statusResumo.bloqueadas),
icon: 'bi bi-slash-circle',
hint: 'Todos os bloqueios',
key: 'franquia_line_total',
title: 'Franquia Line Total',
value: this.formatDataAllowance(overview.franquiaLineTotalGb),
icon: 'bi bi-wifi',
hint: 'Franquia contratada',
},
{
key: 'linhas_reserva',
title: 'Linhas em Reserva',
value: this.formatInt(this.dashboardRaw?.reservas ?? this.statusResumo.reservas),
icon: 'bi bi-inboxes-fill',
hint: 'Base de reserva',
key: 'planos_contratados',
title: 'Planos Contratados',
value: this.formatInt(overview.planosContratados),
icon: 'bi bi-diagram-3-fill',
hint: 'Planos ativos na base',
},
{
key: 'usuarios_com_linha',
title: 'Usuários com Linha',
value: this.formatInt(overview.usuariosComLinha),
icon: 'bi bi-people-fill',
hint: 'Usuários vinculados',
},
];
this.kpis = cards;
return;
}
@ -972,15 +1306,33 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
add('linhas_ativas', 'Linhas Ativas', this.formatInt(dashboard.ativos), 'bi bi-check2-circle', 'Status ativo');
add('linhas_bloqueadas', 'Linhas Bloqueadas', this.formatInt(dashboard.bloqueados), 'bi bi-slash-circle', 'Todos os bloqueios');
add('linhas_reserva', 'Linhas em Reserva', this.formatInt(dashboard.reservas), 'bi bi-inboxes-fill', 'Base de reserva');
if (insights) {
add(
'franquia_vivo_total',
'Total Franquia Vivo',
this.formatGb(this.toNumberOrNull(insights.vivo?.totalFranquiaGb) ?? 0),
'bi bi-diagram-3-fill',
'Soma das franquias (Geral)'
const franquiaVivoTotal = this.toNumberOrNull(insights?.vivo?.totalFranquiaGb)
?? this.toNumberOrNull(this.resumo?.vivoLineTotals?.franquiaTotal)
?? (this.resumo?.vivoLineResumos ?? []).reduce(
(acc, row) => acc + (this.toNumberOrNull(row?.franquiaTotal) ?? 0),
0
);
}
add(
'franquia_vivo_total',
'Total Franquia Vivo',
this.formatDataAllowance(franquiaVivoTotal),
'bi bi-diagram-3-fill',
'Soma das franquias (Geral)'
);
const franquiaLineTotal = this.toNumberOrNull(insights?.vivo?.totalFranquiaLine)
?? this.toNumberOrNull(this.resumo?.vivoLineTotals?.franquiaLine)
?? (this.resumo?.vivoLineResumos ?? []).reduce(
(acc, row) => acc + (this.toNumberOrNull(row?.franquiaLine) ?? 0),
0
);
add(
'franquia_line_total',
'Total Franquia Line',
this.formatDataAllowance(franquiaLineTotal),
'bi bi-hdd-network-fill',
'Soma da franquia line'
);
add('vig_vencidos', 'Vigencia Vencida', this.formatInt(dashboard.vigenciaVencidos), 'bi bi-exclamation-triangle-fill', 'Prioridade alta');
add('vig_30', 'Vence em 30 dias', this.formatInt(dashboard.vigenciaAVencer30), 'bi bi-calendar2-week-fill', 'Prioridade');
add('mureg_30', 'MUREG 30 dias', this.formatInt(dashboard.muregsUltimos30Dias), 'bi bi-arrow-repeat', 'Movimentacao');
@ -1014,22 +1366,18 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
if (!this.viewReady || !this.dataReady) return;
requestAnimationFrame(() => {
const canvases = (
this.isCliente
? [this.chartStatusPie?.nativeElement]
: [
this.chartStatusPie?.nativeElement,
this.chartAdicionaisComparativo?.nativeElement,
this.chartVigenciaMesAno?.nativeElement,
this.chartVigenciaSupervisao?.nativeElement,
this.chartMureg12?.nativeElement,
this.chartTroca12?.nativeElement,
this.chartLinhasPorFranquia?.nativeElement,
this.chartAdicionaisPagos?.nativeElement,
this.chartTipoChip?.nativeElement,
this.chartTravelMundo?.nativeElement,
]
).filter(Boolean) as HTMLCanvasElement[];
const canvases = [
this.chartStatusPie?.nativeElement,
this.chartAdicionaisComparativo?.nativeElement,
this.chartVigenciaMesAno?.nativeElement,
this.chartVigenciaSupervisao?.nativeElement,
this.chartMureg12?.nativeElement,
this.chartTroca12?.nativeElement,
this.chartLinhasPorFranquia?.nativeElement,
this.chartAdicionaisPagos?.nativeElement,
this.chartTipoChip?.nativeElement,
this.chartTravelMundo?.nativeElement,
].filter(Boolean) as HTMLCanvasElement[];
if (!canvases.length) return;
if (canvases.some((c) => c.clientWidth === 0 || c.clientHeight === 0)) {
@ -1054,7 +1402,8 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
this.chartResumoReservaDdd?.nativeElement,
].filter(Boolean) as HTMLCanvasElement[];
if (!canvases.length || canvases.some((c) => c.clientWidth === 0 || c.clientHeight === 0)) {
if (!canvases.length) return;
if (canvases.some((c) => c.clientWidth === 0 || c.clientHeight === 0)) {
this.scheduleResumoChartRetry();
return;
}
@ -1083,10 +1432,10 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
// 1. Status Pie
if (this.chartStatusPie?.nativeElement) {
const chartLabels = this.isCliente
? ['Ativas', 'Bloqueadas', 'Reservas']
? ['Ativas', 'Demais linhas']
: ['Ativos', 'Perda/Roubo', 'Bloq 120d', 'Reservas', 'Outros'];
const chartData = this.isCliente
? [this.statusResumo.ativos, this.statusResumo.bloqueadas, this.statusResumo.reservas]
? [this.statusResumo.ativos, this.clientDemaisLinhas]
: [
this.statusResumo.ativos,
this.statusResumo.perdaRoubo,
@ -1095,7 +1444,7 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
this.statusResumo.outras,
];
const chartColors = this.isCliente
? [palette.status.ativos, palette.status.blocked, palette.status.reserve]
? [palette.status.ativos, '#cbd5e1']
: [
palette.status.ativos,
palette.status.blocked,
@ -1124,10 +1473,6 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
});
}
if (this.isCliente) {
return;
}
if (this.chartAdicionaisComparativo?.nativeElement) {
this.chartAdicionaisComparativoDoughnut = new Chart(this.chartAdicionaisComparativo.nativeElement, {
type: 'doughnut',
@ -1221,7 +1566,7 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
labels: this.tipoChipLabels,
datasets: [{
data: this.tipoChipValues,
backgroundColor: [palette.blue, palette.brand],
backgroundColor: [palette.blue, palette.brand, '#94a3b8'],
borderWidth: 0,
hoverOffset: 4
}]
@ -1490,6 +1835,18 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
return `${value} GB`;
}
formatDataAllowance(v: any) {
const n = this.toNumberOrNull(v);
if (n === null) return '0 GB';
if (n >= 1024) {
const tb = n / 1024;
const valueTb = tb.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
return `${valueTb} TB`;
}
const valueGb = n.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 2 });
return `${valueGb} GB`;
}
private toNumberOrNull(v: any) {
if (v === null || v === undefined || v === '') return null;
if (typeof v === 'number') return Number.isFinite(v) ? v : null;
@ -1513,6 +1870,10 @@ export class Dashboard implements OnInit, AfterViewInit, OnDestroy {
return Number.isNaN(n) ? null : n;
}
get clientDemaisLinhas(): number {
return Math.max(0, (this.statusResumo.total ?? 0) - (this.statusResumo.ativos ?? 0));
}
trackByKpiKey = (_: number, item: KpiCard) => item.key;
private getPalette() {

View File

@ -214,7 +214,7 @@
</div>
<!-- KPIs -->
<div class="geral-kpis mt-4 animate-fade-in" *ngIf="isGroupMode">
<div class="geral-kpis mt-4 animate-fade-in" [class.geral-kpis-client]="isClientRestricted" *ngIf="isGroupMode">
<div class="kpi" *ngIf="!isClientRestricted">
<span class="lbl">Total Clientes</span>
<span class="val val-loading" *ngIf="isKpiLoading">
@ -313,7 +313,7 @@
{{ reservaSelectedCount > 0 && reservaSelectedCount === groupLines.length ? 'Limpar seleção' : 'Selecionar todas' }}
</button>
</ng-container>
<ng-container *ngIf="isReservaExpandedGroup">
<ng-container *ngIf="isReservaExpandedGroup && hasGroupLineSelectionTools">
<button
class="btn btn-sm btn-brand"
type="button"
@ -697,16 +697,20 @@
</div>
<div class="form-field">
<label>
{{ isCreateBatchMode ? 'Linha (Preencher no Lote)' : 'Linha' }}
<span class="text-danger" *ngIf="!isCreateBatchMode">*</span>
</label>
<input
class="form-control form-control-sm"
[(ngModel)]="createModel.linha"
[disabled]="isCreateBatchMode"
[placeholder]="isCreateBatchMode ? 'Use a tabela de lote abaixo' : '119...'"
/>
<label>Linha <span class="text-danger">*</span></label>
<app-select
class="form-select"
size="sm"
[options]="createReservaLineOptions"
labelKey="label"
valueKey="value"
[searchable]="true"
searchPlaceholder="Pesquisar linha da reserva..."
[placeholder]="loadingCreateReservaLines ? 'Carregando linhas da Reserva...' : 'Selecione uma linha da Reserva'"
[disabled]="loadingCreateReservaLines"
[(ngModel)]="createModel.reservaLineId"
(ngModelChange)="onCreateReservaLineChange()"
></app-select>
</div>
<div class="form-field">
@ -1676,6 +1680,7 @@
*ngIf="detailOpen"
#detailModal
class="modal-card modal-xl-custom"
[class.modal-client-detail]="isClientRestricted"
(click)="$event.stopPropagation()"
>
<div class="modal-header">

View File

@ -251,6 +251,19 @@
/* KPIs */
.geral-kpis { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-top: 20px; margin-bottom: 16px; width: 100%; @media (max-width: 992px) { grid-template-columns: repeat(2, 1fr); } @media (max-width: 576px) { grid-template-columns: 1fr; } }
.geral-kpis.geral-kpis-client {
grid-template-columns: repeat(3, minmax(180px, 240px));
justify-content: center;
@media (max-width: 992px) {
grid-template-columns: repeat(2, minmax(170px, 1fr));
justify-content: stretch;
}
@media (max-width: 576px) {
grid-template-columns: 1fr;
}
}
.kpi { background: rgba(255,255,255,0.7); border: 1px solid rgba(17,18,20,0.08); border-radius: 16px; padding: 12px 16px; display: flex; justify-content: space-between; align-items: center; backdrop-filter: blur(8px); transition: transform 0.2s, box-shadow 0.2s; box-shadow: 0 2px 5px rgba(0,0,0,0.02); &:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(227, 61, 207, 0.1); background: #fff; border-color: var(--brand); } .lbl { font-size: 0.72rem; font-weight: 900; letter-spacing: 0.05em; text-transform: uppercase; color: var(--muted); &.text-success { color: var(--success-text) !important; } &.text-danger { color: var(--danger-text) !important; } } .val { font-size: 1.25rem; font-weight: 950; color: var(--text); } }
.kpi .val-loading { font-size: 0.86rem; font-weight: 900; color: var(--muted); display: inline-flex; align-items: center; }
@ -504,6 +517,14 @@
.modal-body { padding: 24px; overflow-y: auto; &.bg-light-gray { background-color: #f8f9fa; } }
.modal-body .box-body { overflow: visible; }
.modal-xl-custom { width: min(1100px, 95vw); max-height: 85vh; }
.modal-card.modal-client-detail {
width: min(560px, 95vw);
}
.modal-card.modal-client-detail .details-dashboard {
grid-template-columns: 1fr;
max-width: 520px;
margin: 0 auto;
}
.modal-card.modal-create { width: min(1280px, 96vw); max-height: 92vh; }
.modal-card.modal-create.batch-mode { width: min(1560px, 99vw); }
.modal-card.modal-move-reserva {

View File

@ -135,6 +135,14 @@ interface AccountCompanyOption {
contas: string[];
}
interface ReservaLineOption {
value: string;
label: string;
linha: string;
chip?: string;
usuario?: string;
}
interface CreateBatchLineDraft extends Partial<CreateMobileLineRequest> {
uid: number;
linha: string;
@ -398,6 +406,9 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
accountCompanies: AccountCompanyOption[] = [...this.fallbackAccountCompanies];
loadingAccountCompanies = false;
createReservaLineOptions: ReservaLineOption[] = [];
loadingCreateReservaLines = false;
private createReservaLineLookup = new Map<string, ReservaLineOption>();
get contaEmpresaOptions(): string[] {
return this.accountCompanies.map((x) => x.empresa);
@ -437,6 +448,7 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
docType: 'PF',
docNumber: '',
contaEmpresa: '',
reservaLineId: '',
linha: '',
chip: '',
tipoDeChip: '',
@ -567,7 +579,7 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
}
get hasGroupLineSelectionTools(): boolean {
return !!(this.expandedGroup ?? '').trim();
return !this.isClientRestricted && !!(this.expandedGroup ?? '').trim();
}
get canMoveSelectedLinesToReserva(): boolean {
@ -2002,6 +2014,7 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
this.createMode = 'NEW_CLIENT';
this.resetCreateModel();
this.createOpen = true;
void this.loadCreateReservaLines();
this.cdr.detectChanges();
}
@ -2022,6 +2035,7 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
this.syncContaEmpresaSelection(this.createModel);
this.createOpen = true;
void this.loadCreateReservaLines();
this.cdr.detectChanges();
}
@ -2031,6 +2045,7 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
docType: 'PF',
docNumber: '',
contaEmpresa: '',
reservaLineId: '',
linha: '',
chip: '',
tipoDeChip: '',
@ -2701,7 +2716,7 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
private buildCreatePayload(model: any): CreateMobileLineRequest {
this.calculateFinancials(model);
const { contaEmpresa: _contaEmpresa, uid: _uid, ...createModelPayload } = model;
const { contaEmpresa: _contaEmpresa, uid: _uid, reservaLineId: _reservaLineId, ...createModelPayload } = model;
return {
...createModelPayload,
@ -2816,6 +2831,99 @@ export class Geral implements OnInit, AfterViewInit, OnDestroy {
this.createModel.docNumber = value;
}
private async loadCreateReservaLines(): Promise<void> {
if (this.loadingCreateReservaLines) return;
this.loadingCreateReservaLines = true;
try {
const pageSize = 500;
let page = 1;
const collected: ReservaLineOption[] = [];
while (true) {
const params = new HttpParams()
.set('page', String(page))
.set('pageSize', String(pageSize))
.set('skil', 'RESERVA');
const response = await firstValueFrom(this.http.get<ApiPagedResult<ApiLineList>>(this.apiBase, { params }));
const items = Array.isArray(response?.items) ? response.items : [];
for (const row of items) {
const id = (row?.id ?? '').toString().trim();
const linha = (row?.linha ?? '').toString().trim();
if (!id || !linha) continue;
collected.push({
value: id,
label: `${row?.item ?? ''}${linha}${(row?.usuario ?? 'SEM USUÁRIO').toString()}`,
linha,
chip: (row?.chip ?? '').toString(),
usuario: (row?.usuario ?? '').toString()
});
}
const total = Number(response?.total ?? 0);
if (!items.length || (total > 0 && collected.length >= total) || items.length < pageSize) break;
page += 1;
}
const seen = new Set<string>();
const unique = collected.filter((opt) => {
if (seen.has(opt.value)) return false;
seen.add(opt.value);
return true;
});
unique.sort((a, b) => a.linha.localeCompare(b.linha, 'pt-BR', { numeric: true, sensitivity: 'base' }));
this.createReservaLineOptions = unique;
this.createReservaLineLookup = new Map(unique.map((opt) => [opt.value, opt]));
} catch {
this.createReservaLineOptions = [];
this.createReservaLineLookup.clear();
await this.showToast('Erro ao carregar linhas da Reserva.');
} finally {
this.loadingCreateReservaLines = false;
}
}
onCreateReservaLineChange() {
const lineId = (this.createModel?.reservaLineId ?? '').toString().trim();
if (!lineId) {
this.createModel.linha = '';
return;
}
const selected = this.createReservaLineLookup.get(lineId);
if (selected) {
this.createModel.linha = selected.linha ?? '';
if (!String(this.createModel.chip ?? '').trim() && selected.chip) {
this.createModel.chip = selected.chip;
}
if (!String(this.createModel.usuario ?? '').trim() && selected.usuario) {
this.createModel.usuario = selected.usuario;
}
}
this.http.get<ApiLineDetail>(`${this.apiBase}/${lineId}`).subscribe({
next: (detail) => {
this.createModel.linha = (detail?.linha ?? this.createModel.linha ?? '').toString();
if (!String(this.createModel.chip ?? '').trim() && detail?.chip) {
this.createModel.chip = detail.chip;
}
if (!String(this.createModel.tipoDeChip ?? '').trim() && detail?.tipoDeChip) {
this.createModel.tipoDeChip = detail.tipoDeChip;
}
if (!String(this.createModel.usuario ?? '').trim() && detail?.usuario) {
this.createModel.usuario = detail.usuario;
}
},
error: () => {
// Mantém dados já carregados da lista.
}
});
}
async saveCreate() {
if (this.isCreateBatchMode) {
await this.saveCreateBatch();

View File

@ -9,8 +9,8 @@
<div class="title-badge">
<i class="bi bi-shield-lock-fill"></i> SYSADMIN
</div>
<h1>Fornecer Usuário para Cliente</h1>
<p>Selecione um tenant-cliente e crie credenciais de acesso sem misturar tenants.</p>
<h1>Criar Credenciais do Cliente</h1>
<p>Selecione o cliente e gere o acesso para acompanhamento das linhas no sistema.</p>
</header>
<div class="card-body">
@ -20,16 +20,10 @@
<div class="alert-box success" *ngIf="successMessage">
{{ successMessage }}
<div class="mt-1" *ngIf="createdUser">
<small>
UserId: <strong>{{ createdUser.userId }}</strong> | TenantId:
<strong>{{ createdUser.tenantId }}</strong>
</small>
</div>
</div>
<div class="alert-box error" *ngIf="submitErrors.length">
<strong>Falha ao criar usuário:</strong>
<strong>Falha ao criar credencial:</strong>
<ul>
<li *ngFor="let err of submitErrors">{{ err }}</li>
</ul>
@ -38,35 +32,32 @@
<form [formGroup]="provisionForm" (ngSubmit)="onSubmit()" class="provision-form" novalidate>
<div class="form-grid">
<div class="form-field span-2">
<label for="tenantId">Cliente (Tenant)</label>
<label for="tenantId">Cliente</label>
<div class="select-row">
<select
<app-select
id="tenantId"
formControlName="tenantId"
class="form-control"
[disabled]="tenantsLoading || !tenants.length"
>
<option value="">Selecione um cliente...</option>
<option
*ngFor="let tenant of tenants; trackBy: trackByTenantId"
[value]="tenant.tenantId"
>
{{ tenant.nomeOficial }}
</option>
</select>
[options]="tenantOptions"
labelKey="label"
valueKey="value"
formControlName="tenantId"
[disabled]="tenantsLoading || tenantOptions.length === 0"
[searchable]="true"
searchPlaceholder="Pesquisar cliente..."
[placeholder]="tenantsLoading ? 'Carregando clientes...' : 'Selecione um cliente...'"
></app-select>
<button type="button" class="btn btn-ghost" (click)="loadTenants()" [disabled]="tenantsLoading">
{{ tenantsLoading ? 'Atualizando...' : 'Atualizar lista' }}
</button>
</div>
<small class="field-help">Origem: {{ sourceType }} (apenas tenants ativos).</small>
<small class="field-error" *ngIf="hasFieldError('tenantId', 'required')">
Selecione um tenant-cliente.
Selecione um cliente.
</small>
</div>
<div class="form-field">
<label for="name">Nome (opcional)</label>
<input id="name" type="text" class="form-control" formControlName="name" placeholder="Nome do usuário" />
<label for="name">Nome</label>
<input id="name" type="text" class="form-control" formControlName="name" placeholder="Nome do responsável" />
</div>
<div class="form-field">
@ -111,31 +102,11 @@
</small>
<small class="field-error" *ngIf="passwordMismatch">As senhas não conferem.</small>
</div>
<div class="form-field span-2">
<label>Roles do usuário</label>
<div class="roles-grid">
<label class="role-item" *ngFor="let role of roleOptions; trackBy: trackByRoleValue">
<input
type="checkbox"
[checked]="isRoleSelected(role.value)"
(change)="toggleRole(role.value, $any($event.target).checked)"
/>
<div class="role-content">
<strong>{{ role.label }}</strong>
<span>{{ role.description }}</span>
</div>
</label>
</div>
<small class="field-error" *ngIf="selectedRoles.length === 0">
Selecione ao menos uma role.
</small>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary" [disabled]="submitting || provisionForm.invalid">
<span *ngIf="!submitting">Criar usuário para cliente</span>
<span *ngIf="!submitting">Criar credencial de acesso</span>
<span *ngIf="submitting">Criando...</span>
</button>
</div>

View File

@ -9,6 +9,7 @@ import {
ValidationErrors,
Validators,
} from '@angular/forms';
import { CustomSelectComponent } from '../../components/custom-select/custom-select';
import {
SysadminService,
@ -16,30 +17,19 @@ import {
CreateSystemTenantUserResponse,
} from '../../services/sysadmin.service';
type RoleOption = {
value: string;
label: string;
description: string;
};
@Component({
selector: 'app-system-provision-user',
standalone: true,
imports: [CommonModule, ReactiveFormsModule],
imports: [CommonModule, ReactiveFormsModule, CustomSelectComponent],
templateUrl: './system-provision-user.html',
styleUrls: ['./system-provision-user.scss'],
})
export class SystemProvisionUserPage implements OnInit {
readonly roleOptions: RoleOption[] = [
{ value: 'sysadmin', label: 'SysAdmin', description: 'Acesso administrativo global do sistema (apenas SystemTenant).' },
{ value: 'gestor', label: 'Gestor', description: 'Acesso global de gestão, sem permissões administrativas.' },
{ value: 'cliente', label: 'Cliente', description: 'Acesso restrito ao tenant do cliente.' },
];
readonly sourceType = 'MobileLines.Cliente';
provisionForm: FormGroup;
tenants: SystemTenantDto[] = [];
tenantOptions: Array<{ label: string; value: string }> = [];
tenantsLoading = false;
tenantsError = '';
@ -74,6 +64,7 @@ export class SystemProvisionUserPage implements OnInit {
this.tenantsLoading = true;
this.tenantsError = '';
this.syncTenantControlAvailability();
this.sysadminService
.listTenants({ source: this.sourceType, active: true })
@ -82,34 +73,26 @@ export class SystemProvisionUserPage implements OnInit {
this.tenants = (tenants || []).slice().sort((a, b) =>
(a.nomeOficial || '').localeCompare(b.nomeOficial || '', 'pt-BR', { sensitivity: 'base' })
);
this.tenantOptions = this.tenants.map((tenant) => ({
label: tenant.nomeOficial || tenant.tenantId,
value: tenant.tenantId,
}));
this.tenantsLoading = false;
this.syncTenantControlAvailability();
},
error: (err: HttpErrorResponse) => {
this.tenantsLoading = false;
this.tenants = [];
this.tenantOptions = [];
this.tenantsError = this.extractErrorMessage(
err,
'Não foi possível carregar os clientes. Verifique se a conta possui role sysadmin.'
);
this.syncTenantControlAvailability();
},
});
}
isRoleSelected(role: string): boolean {
const selected = this.selectedRoles;
return selected.includes(role);
}
toggleRole(role: string, checked: boolean): void {
const current = this.selectedRoles;
const next = checked
? Array.from(new Set([...current, role]))
: current.filter((value) => value !== role);
this.rolesControl.setValue(next);
this.rolesControl.markAsDirty();
this.rolesControl.markAsTouched();
}
onSubmit(): void {
if (this.submitting) return;
@ -117,11 +100,8 @@ export class SystemProvisionUserPage implements OnInit {
this.submitErrors = [];
this.createdUser = null;
if (this.provisionForm.invalid || this.selectedRoles.length === 0) {
if (this.provisionForm.invalid) {
this.provisionForm.markAllAsTouched();
if (this.selectedRoles.length === 0) {
this.submitErrors = ['Selecione ao menos uma role para o usuário.'];
}
return;
}
@ -138,7 +118,8 @@ export class SystemProvisionUserPage implements OnInit {
name: nameRaw,
email,
password,
roles: this.selectedRoles,
roles: ['cliente'],
clientCredentialsOnly: true,
})
.subscribe({
next: (created) => {
@ -148,7 +129,7 @@ export class SystemProvisionUserPage implements OnInit {
this.createdUser = created;
const tenant = this.findTenantById(created.tenantId) ?? this.findTenantById(tenantId);
const tenantName = tenant?.nomeOficial || 'cliente selecionado';
this.successMessage = `Usuário ${created.email} criado com sucesso para ${tenantName}.`;
this.successMessage = `Credencial de acesso criada com sucesso para ${tenantName}.`;
this.provisionForm.patchValue({
name: '',
@ -172,10 +153,6 @@ export class SystemProvisionUserPage implements OnInit {
return tenant.tenantId;
}
trackByRoleValue(_: number, role: RoleOption): string {
return role.value;
}
hasFieldError(field: string, error?: string): boolean {
const control = this.provisionForm.get(field);
if (!control) return false;
@ -188,15 +165,6 @@ export class SystemProvisionUserPage implements OnInit {
return !!(confirmTouched && this.provisionForm.errors?.['passwordMismatch']);
}
get selectedRoles(): string[] {
const roles = this.rolesControl.value;
return Array.isArray(roles) ? roles : [];
}
get rolesControl(): AbstractControl<string[] | null, string[] | null> {
return this.provisionForm.get('roles') as AbstractControl<string[] | null, string[] | null>;
}
private findTenantById(tenantId: string): SystemTenantDto | undefined {
return this.tenants.find((tenant) => tenant.tenantId === tenantId);
}
@ -208,6 +176,21 @@ export class SystemProvisionUserPage implements OnInit {
}
this.provisionForm.enable({ emitEvent: false });
this.syncTenantControlAvailability();
}
private syncTenantControlAvailability(): void {
const tenantControl = this.provisionForm.get('tenantId');
if (!tenantControl) return;
if (this.submitting) return;
const shouldDisable = this.tenantsLoading || this.tenants.length === 0;
if (shouldDisable) {
tenantControl.disable({ emitEvent: false });
return;
}
tenantControl.enable({ emitEvent: false });
}
private extractErrors(err: HttpErrorResponse): string[] {
@ -237,7 +220,7 @@ export class SystemProvisionUserPage implements OnInit {
return ['Acesso negado. Este recurso é exclusivo para sysadmin.'];
}
return ['Não foi possível criar o usuário para o cliente selecionado.'];
return ['Não foi possível criar a credencial para o cliente selecionado.'];
}
private extractErrorMessage(err: HttpErrorResponse, fallback: string): string {

View File

@ -19,6 +19,7 @@ export type CreateSystemTenantUserPayload = {
email: string;
password: string;
roles: string[];
clientCredentialsOnly?: boolean;
};
export type CreateSystemTenantUserResponse = {