All files / app/authentication/account account.ts

89.04% Statements 65/73
78% Branches 39/50
87.5% Functions 7/8
88.4% Lines 61/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175                                96x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x   1x           28x       6x 2x     6x       9x 2x 2x     7x 7x         7x 7x   7x 7x 7x         4x 4x 4x     3x     3x   7x         10x 1x     9x 9x   10x             28x 28x   28x 28x   27x 1x 1x     26x   26x   26x 1x 1x     25x 25x     1x         1x         1x         1x 1x 1x         28x                                         31x   31x              
import { CommonModule } from '@angular/common';
import { Component, OnInit, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { TranslocoModule, TranslocoService } from '@jsverse/transloco';
import { User } from '@supabase/supabase-js';
import { SupabaseConnector } from '../../services/supabase-connector';
import { ConfirmModalService } from '../../services/confirm-modal.service';
import { Profile, Timestamp } from '../../types';
 
@Component({
  selector: 'app-account',
  imports: [CommonModule, ReactiveFormsModule, RouterLink, TranslocoModule],
  templateUrl: './account.html',
  styleUrl: './account.scss',
})
export class Account implements OnInit {
  private readonly fb = inject(FormBuilder);
  private readonly supabaseService = inject(SupabaseConnector);
  private readonly confirmModal = inject(ConfirmModalService);
  private readonly router = inject(Router);
  private readonly transloco = inject(TranslocoService);
 
  readonly isLoading = signal(true);
  readonly isSaving = signal(false);
  readonly isEditMode = signal(false);
  readonly errorMessage = signal<string | null>(null);
  readonly profile = signal<Profile | null>(null);
  readonly user = signal<User | null>(null);
 
  readonly editForm = this.fb.nonNullable.group({
    username: ['', [Validators.required, Validators.minLength(3)]],
    sync_interval: [15, [Validators.required, Validators.min(1), Validators.max(60)]],
  });
 
  ngOnInit(): void {
    void this.loadAccountData();
  }
 
  toggleEditMode(): void {
    if (this.isEditMode()) {
      this.resetFormFromProfile();
    }
 
    this.isEditMode.set(!this.isEditMode());
  }
 
  async saveChanges(): Promise<void> {
    if (this.editForm.invalid) {
      this.editForm.markAllAsTouched();
      return;
    }
 
    const profile = this.profile();
    Iif (!profile?.id) {
      this.errorMessage.set(this.transloco.translate('auth.account.invalidUserId'));
      return;
    }
 
    this.errorMessage.set(null);
    this.isSaving.set(true);
 
    try {
      const { username, sync_interval } = this.editForm.getRawValue();
      const updatedProfile = await this.supabaseService.updateProfile(profile.id, {
        username,
        sync_interval,
      });
 
      this.profile.set(updatedProfile);
      this.resetFormFromProfile();
      this.isEditMode.set(false);
    } catch (error) {
      const message =
        error instanceof Error
          ? error.message
          : this.transloco.translate('auth.account.profileUpdateFailed');
      this.errorMessage.set(message);
    } finally {
      this.isSaving.set(false);
    }
  }
 
  formatUpdatedAt(updatedAt?: Timestamp): string {
    if (!updatedAt) {
      return '-';
    }
 
    const activeLang = this.transloco.getActiveLang();
    const locale = activeLang === 'de' ? 'de-DE' : 'en-US';
 
    return new Intl.DateTimeFormat(locale, {
      dateStyle: 'medium',
      timeStyle: 'short',
    }).format(new Date(updatedAt));
  }
 
  private async loadAccountData(): Promise<void> {
    this.isLoading.set(true);
    this.errorMessage.set(null);
 
    try {
      const currentUser = await this.supabaseService.getCurrentUser();
 
      if (!currentUser) {
        void this.router.navigateByUrl('/login');
        return;
      }
 
      this.user.set(currentUser);
 
      const profile = await this.supabaseService.getProfile(currentUser.id);
 
      if (!profile) {
        this.errorMessage.set(this.transloco.translate('auth.account.accountLoadFailed'));
        return;
      }
 
      this.profile.set(profile);
      this.resetFormFromProfile();
    } catch (error) {
      const errorMsg =
        error instanceof Error
          ? error.message
          : this.transloco.translate('auth.account.accountLoadFailed');
 
      const errorCode =
        typeof error === 'object' && error !== null && 'code' in error
          ? String((error as { code: unknown }).code)
          : '';
 
      const isAuthError =
        errorMsg.includes('Auth session missing') ||
        /jwt|token|session/i.test(errorMsg) ||
        errorCode.startsWith('PGRST3');
 
      // Redirect to login if auth session is missing
      Eif (isAuthError) {
        void this.router.navigateByUrl('/login');
        return;
      }
 
      this.errorMessage.set(errorMsg);
    } finally {
      this.isLoading.set(false);
    }
  }
 
  protected async logout(): Promise<void> {
    const confirmed = await this.confirmModal.confirm({
      title: this.transloco.translate('auth.account.logoutTitle'),
      message: this.transloco.translate('auth.account.logoutMessage'),
      confirmText: this.transloco.translate('auth.account.logoutConfirm'),
      cancelText: this.transloco.translate('common.cancel'),
    });
 
    if (!confirmed) {
      return;
    }
 
    await this.supabaseService.logout();
    window.location.href = '/login';
  }
 
  private resetFormFromProfile(): void {
    const profile = this.profile();
 
    this.editForm.setValue({
      username: profile?.username ?? '',
      sync_interval: profile?.settings?.sync_interval ?? 15,
    });
  }
}