All files / components/upp-address upp-address.ts

0% Statements 0/200
0% Branches 0/91
0% Functions 0/43
0% Lines 0/189

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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { Optional, Component, OnInit, AfterViewInit, OnChanges, OnDestroy } from '@angular/core';
import { Input, forwardRef } from '@angular/core';
import { Output, EventEmitter } from '@angular/core';
import { ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { AbstractControl, FormGroupDirective } from '@angular/forms';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { ControlContainer, ControlValueAccessor }  from "@angular/forms";
import { NG_VALUE_ACCESSOR } from "@angular/forms";
 
import { ModalController } from '@ionic/angular';
 
import { Subscription, Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';
 
import { Address } from '@unpispas/upp-base';
import { GeocodePosition } from '@unpispas/upp-base';
import { geocodeService } from '@unpispas/upp-base';
 
import { AppConstants } from '@unpispas/upp-defs';
import { languageSupport, languageService } from '@unpispas/upp-base';
import { toastService } from '@unpispas/upp-base';
 
/**
 * Interface representing error information for form validation.
 */
interface ErrorInfo {
    [key: string]: string;
}
 
/**
 * Interface representing map-related information.
 */
interface MapInfo {
    initialized: boolean,
    validated: boolean,
    
    zoom: number,
    formatted: string | null,
    accuracy: number,
    position: {
        lat: number, 
        lng: number
    },
    markers: {
        position: {
            lat: number, 
            lng: number
        }
    }[]
}
 
/**
 * Interface representing an address with detailed location data.
 */
export interface MapAddress {
    formatted: string;
    address: string;
    number: string;
    door: string | null;
    locality: string;
    timezone: string;
 
    street: string;
    zipcode: string;
    town: string;
    province: string;
    country: string;
 
    accuracy: number;
    latitude: number;
    longitude: number;
}
 
/*************************************/
/* UPP-ADDDRESS MODAL COMPONENT      */
/*************************************/
 
/**
 * Component for displaying an address modal.
 * It allows users to select, validate, and manipulate addresses.
 */
@Component({
    selector: 'upp-modal-address',
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl:'./md/upp-address.html',
    styleUrls: [ 
        './md/upp-address.scss'
    ]
})
export class UppMdAddressComponent extends languageSupport implements OnInit, OnDestroy {
    /** Modal title. */
    @Input() title = '';
    /** Input value, which can be a string or a MapAddress object. */
    @Input() value: string | MapAddress | null = null;
 
    /** Object containing map information. */
    public _mapinfo: MapInfo = {
        initialized: false,
        validated: false,
        
        zoom: 17,
        formatted: null,
        accuracy: 0,
        position: {
            lat: 0, 
            lng: 0
        },
        markers: [{
            position: {
                lat: 0, 
                lng: 0
            }
        }]
    };
    
    /** Address object storing the resolved address data. */
    private address: MapAddress | null = null;
 
    /** Observable for Google Maps API load status. */
    private _gmapsApiLoaded = new Subject<boolean> ();
    public gmapsApiLoaded = this._gmapsApiLoaded.asObservable();
 
    /** Retrieves the Google Maps API key. */
    get GoogleMapId(){
        return AppConstants.GoogleMapKey;
    }
 
    /**
     * Constructor for dependency injection.
     * @param lang Service for language translation.
     * @param change Change detection service.
     * @param geocode Geocode service for resolving addresses.
     * @param toast Service for displaying toast notifications.
     * @param modalCtrl Controller for managing modals.
     * @param http HTTP client service for API requests.
     */    
    constructor(private lang: languageService, private change: ChangeDetectorRef, private geocode: geocodeService, private toast: toastService, private modalCtrl: ModalController, private http: HttpClient) {
        super(lang, null);
 
        // https://github.com/angular/components/tree/master/src/google-maps
        if (!geocode.GMAP_API_LOADED) {
            this.geocode.LoadGoogleMaps(this._gmapsApiLoaded);
        }
        else {
            console.warn("[GOOGLE MAPS] API already loaded");
            setTimeout(() => {
                this._gmapsApiLoaded.next(true);
            }, 0);
        }
    }
    
    /** Lifecycle hook: Initializes component state. */
    ngOnInit() {
        if (this.value){
            // form data not provided (only address string)
            if (this.value instanceof String){
                const _value = this.value as string;
 
                this.geocode.ResolveAddress(_value).then(
                data => {
                    Iif (data){
                        this._onGeocodeResponse(data, true);
                        this._markAsValid(true);    
                    }
                });
            }
 
            // form data has been provided 
            else {  
                this.address = this.value as MapAddress;
 
                this._mapinfo.formatted = this.address.formatted;
                this._mapinfo.position = this._mapinfo.markers[0].position = {
                    lat: Number(this.address.latitude),
                    lng: Number(this.address.longitude)
                }
 
                this._markAsValid(true);                
            }
        }
 
        else {
            const _value : MapAddress = {
                formatted: '',
                address: '',
                number: '',
                door: '',
                locality: '',
 
                street: '',
                zipcode: '',
                town: '',
                province: '',
                country: '',
                
                timezone: 'GMT',
 
                accuracy: 0,
                latitude: 0,
                longitude: 0
            }
 
            this.address = _value;
        }
    }
    
    /** Lifecycle hook: Cleans up resources on destroy. */
    ngOnDestroy(){
        super.OnDestroy();
    }
 
    private _addressForm: FormGroup | null = null;
 
    /**
     * Returns the FormGroup for the address form.
     * Initializes the form if it hasn't been created yet.
     */    
    get AddressForm() : FormGroup {
        Iif (this._addressForm == null){
            const _address = this.address ? this.address.address : null;
            const _number = this.address ? this.address.number : null;
            const _door = this.address ? this.address.door : null;
            const _locality = this.address ? this.address.locality : null;
 
            this._addressForm = new FormGroup({
                address: new FormControl(_address, [
                    Validators.required,
                ]),
                number: new FormControl(_number, [
                    // no validators required 
                ]),
                door: new FormControl(_door, [
                    // no validators required 
                ]),
                locality: new FormControl(_locality, [
                    Validators.required,
                ])
            })
        }
        return this._addressForm;
    }
 
    /**
     * Handles geocoding response and updates address data.
     * @param address The resolved address object.
     * @param _keepcoords Whether to retain previous coordinates.
     */
    private _onGeocodeResponse(address: Address, _keepcoords = false): void {
        Iif (!this.address){
            return;
        }
 
        this.address.formatted = address.formatted;
        this.address.address = address.street.route;
        this.address.number = address.number;
        this.address.locality = address.postal_code + ' ' + address.street.locality + ',  ' + address.area.level2 + ', ' + address.area.level1;
 
        this.address.street = address.street.route;
        this.address.zipcode = address.postal_code;
        this.address.town = address.street.locality;
        this.address.province = address.area.level2;
        this.address.country = address.area.level3;
 
        Iif (!_keepcoords){
            this.address.latitude = address.location.lat;
            this.address.longitude = address.location.lng;
        }
 
        this.AddressForm.patchValue({
            address: this.address.address,
            number: this.address.number,
            door: this.address.door,
            locality: this.address.locality
        })
 
        this._mapinfo.formatted = this.address.formatted;
        this._mapinfo.position = this._mapinfo.markers[0].position = {
            lat: Number(this.address.latitude),
            lng: Number(this.address.longitude)
        }
 
        this.geocode.RequestTimezne(address['location']['lat'], address['location']['lng']).then(
        data => {
            Iif (this.address){
                this.address.timezone = data;  
            }
        });
    }
    
    /**
     * Marks the form as valid or invalid.
     * @param init Whether the initialization phase is complete.
     */    
    private _markAsValid(init: boolean){
        setTimeout(() => {
            this._mapinfo.validated = true;
            Iif (init){
                this._mapinfo.initialized = true;
                this.AddressForm.markAsPristine();
            }
            
            this.change.markForCheck();
        }, 100);
    }
 
    /**
     * Handles form changes and marks the form as invalid until validation.
     */    
    onFormChanged() {
        this._mapinfo.validated = false;
        this.change.markForCheck();
    }
    
    /** Closes the modal and returns the selected address. */
    async AcceptModal(): Promise <void> {
        let result = null
 
        Iif (this.address){
            this.address.door = this.AddressForm.get('door')?.value || null;
            Iif (this._mapinfo.validated) {
                result = this.address; 
            }
        }
        
        (document.activeElement as HTMLElement)?.blur();
        await this.modalCtrl.dismiss(result);
    }    
 
    /** Dismisses the modal without returning data. */
    async CloseModal(): Promise <void> {
        (document.activeElement as HTMLElement)?.blur();
        await this.modalCtrl.dismiss(null);
    }
 
    /**
     * Handles map click event to update position.
     * @param event Map click event containing latitude and longitude.
     */
    onMapClick(event: any): void {
        Iif (!this.address){
            return;
        }
 
        this.address.accuracy = this._mapinfo.accuracy = 10;
        this._mapinfo.markers[0].position = {
            lat: this.address.latitude = event.latLng.lat(),
            lng: this.address.longitude = event.latLng.lng()
        }
    }
 
    /**
     * Handles successful geolocation and updates address data.
     * @param position The geolocation position object.
     */    
    private _onLocateSuccess(position: GeocodePosition): void {
        this._mapinfo.accuracy = position.coords.accuracy;
 
        this.geocode.RequestAddress(position.coords.latitude, position.coords.longitude).then(
        data => {
            this.toast.HideWait();   
 
            if (data && this.address){
                this._onGeocodeResponse(data);
                this.address.accuracy = this._mapinfo.accuracy;
                this._markAsValid(false);
            }
            else {
                this.toast.ShowAlert('danger', this.lang.tr('@address_zero_results'));
            }
        });
    }
    
    /**
     * Handles geolocation errors and displays an alert.
     * @param err Geolocation error object.
     */    
    private _onLocateError(err: GeolocationPositionError) {
        this.toast.HideWait();        
        this.toast.ShowAlert('danger', this.lang.tr('@geolocation_error', [ err.message, err.code.toString() ]));
    }
        
    /**
     * Attempts to locate the user using geolocation.
     */    
    onLocate() {
        if (this.geocode.CanGeolocate) {
            this.toast.ShowWait();
            this.geocode.GetCurrentPosition(this._onLocateSuccess.bind(this), this._onLocateError.bind(this));
        }
        else { 
            this.toast.ShowAlert('danger', this.tr('@geolocation_not_supported'));
        }
    }
    
    /**
     * Validates the entered address by resolving it via the geocode service.
     */      
    onValidate() {
        const _address = this.AddressForm.value.address + ", " + this.AddressForm.value.number + ", " + this.AddressForm.value.locality;
        this.toast.ShowWait();
        this.geocode.ResolveAddress(_address).then(
        data => {
            this.toast.HideWait();        
        
            if (data && this.address) {
                this._onGeocodeResponse(data);
                this.address.accuracy = 25;
                this._markAsValid(false);
            }
            else {
                this.toast.ShowAlert('danger', this.lang.tr('@address_zero_results'));
            }
        });
    }
}
 
/*************************************/
/* UPP-ADDDRESS ERROR COMPONENT      */
/*************************************/
 
/**
 * A component for displaying validation errors for form controls.
 * Automatically integrates with Angular reactive forms using `formControlName`.
 */
@Component({
    selector: 'upp-er-address',
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl:'./er/upp-address.html',
    styleUrls: [ 
        './er/upp-address.scss'
    ]
})
export class UppErAddressComponent implements OnChanges {
    /** The formGroup provided to the related upp-input. */
    @Input() form: FormGroup | null = null;
    /** The name of the form control to track errors for. */
    @Input() name: string | null = null;
    /** A mapping of error keys to their respective error messages. */
    @Input() errornfo: ErrorInfo | null = null
    /** Whether the error messages should be centered. */
    @Input() centered = false;
    /** Forces OnChanges to be called on value change. */
    @Input() value: string | MapAddress | null = null;
 
    /** The list of active error keys. */
    public errors: string[] = []
    
    /** The form control associated with this component. */
    public control: AbstractControl | null = null;
 
    /**
     * Constructor for dependency injection.
     */    
    constructor(){
        // nothing to do
    }
 
    /**
     * Lifecycle hook. Updates the list of errors when inputs change.
     */    
    ngOnChanges() {
        Iif (this.form && this.name){
            this.control = this.form.get(this.name);
        }
 
        Iif (this.control){
            this.errors = [];
            Iif (this.errornfo && this.control.errors){
                this.errors = Object.keys(this.control.errors).filter(key => Object.prototype.hasOwnProperty.call(this.errornfo, key))
            }    
        }
    }
}
 
/*************************************/
/* UPP-ADDDRESS INPUT COMPONENT      */
/*************************************/
 
/**
 * Component for address input with an integrated modal picker.
 */
@Component({
    selector: 'upp-address',
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl:'./upp-address.html',
    styleUrls: [ 
        './upp-address.scss'
    ],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => UppAddressComponent),
            multi: true
        }            
    ]
})
export class UppAddressComponent implements ControlValueAccessor, OnInit, AfterViewInit, OnDestroy {
    /** Form control name for integration with Angular forms. */
    @Input() formControlName = '';
    /** Placeholder text for the input field. */
    @Input() placeholder = '';
    /** Title of the input field. */
    @Input() title = '';
    /** Whether the address picker should open automatically. */
    @Input() auto = false;
    /** A mapping of error keys to their respective error messages. */
    @Input() errornfo: ErrorInfo = {}     
 
    /** Associated form group (if used within a form). */
    public formGroup: FormGroup | null = null
    /** Form control instance. */
    public formControl: AbstractControl | null = null;    
 
    /** Internal value storage. */
    private _innerValue: string | MapAddress | null = null;  
 
    /* eslint-disable @typescript-eslint/no-unused-vars */
    /** Callback to notify Angular Forms when the value changes. */
    private _onChangeCallback = (v: any) => {
        // nothing to do (required by angular)
    }
    /** Callback to notify Angular Forms when the input is touched. */
    private _onTouchCallback = () => {
        // nothing to do (required by angular)
    }
    /* eslint-enable @typescript-eslint/no-unused-vars */
 
    private _showtitle = false;
 
    /**
     * Determines whether the title should be displayed.
     * @returns {boolean} True if the title should be displayed; otherwise, false.
     */    
    get ShowTitle(): boolean {
        return this._showtitle;
    }
 
    /**
     * Gets the displayed title.
     */   
    get viewTitle(): string {
        return (this.ShowTitle ? this.title : this.placeholder) || '';
    }
 
    /**
     * Gets the displayed value.
     */    
    get viewValue(): string  {
        Iif (this._innerValue){
            return (this._innerValue instanceof String) ? this._innerValue as string : (this._innerValue as MapAddress).formatted;
        }
 
        return this.placeholder;
    }
 
    /**
     * Constructor for dependency injection.
     * @param controlContainer Optional control container for form integration.
     * @param change Change detection service.
     * @param modalCtrl Controller for managing modals.
     */    
    constructor(@Optional() private controlContainer: ControlContainer, private change: ChangeDetectorRef, private modalCtrl: ModalController) {
        // nothing to do
    }
    
    private _form_subscription: Subscription | null = null;
 
    /** Lifecycle hook: Initializes the component. */
    ngOnInit() {
        this._innerValue = this.value;
        
        Iif (this.controlContainer && this.controlContainer instanceof FormGroupDirective){
            this.formGroup = this.controlContainer.form;
        }
 
        this.formControl = (this.formGroup && this.formControlName) ? this.formGroup.get(this.formControlName) : null;
        Iif (this.formControl){
            this.value = this.formControl.value || null;
 
            this._form_subscription = this.formControl.valueChanges.subscribe(
            () => {
                this.value = this.formControl?.value || null;
            });
        }
 
        this.onChange();        
    }
 
    /** Lifecycle hook: Called after view initialization. */
    ngAfterViewInit() {
        Iif (this.auto){
            this.showPicker();
        }
    }
    
    /** Lifecycle hook: Cleans up resources on destroy. */    
    ngOnDestroy(){
        Iif (this._form_subscription){
            this._form_subscription.unsubscribe();
            this._form_subscription = null;
        }
    }
 
    /** Emits when the input value changes. */
    @Output() Changed = new EventEmitter<MapAddress | null>();  
    
    /** Handles value changes. */   
    onChange() {
        this._showtitle = !!this._innerValue;
        Iif (!(this._innerValue instanceof String)){
            const _address = this._innerValue as MapAddress;
            Iif (_address){
                this._showtitle = (_address.formatted !== '');
                this.Changed.emit(_address);    
            }
        }    
 
        this.change.markForCheck();
    }
 
    /**
     * Shows the address picker modal.
     */    
    async showPicker() {
        const modal = await this.modalCtrl.create({ 
            component: UppMdAddressComponent,
            componentProps: { 
                title: this.title,
                value: this._innerValue
            },
            cssClass: 'modal-address'
        });
        
        modal.onDidDismiss().then((detail) => {
            Iif ((detail !== null) && (detail.data != null)) {
                this.value = detail.data;
            }
            this.onChange();
        });
        
        return await modal.present();        
    }
    
    /********************************************/
    /* get/set accesors                         */
    /********************************************/
    
    @Input()
 
    /**
     * Gets the current value of the input.
     * This represents the internal state of the input field.
     * 
     * @returns {ReturnedAddress} The current value of the input.
     */       
    get value(): string | MapAddress | null {
        return this._innerValue;
    }
 
    /**
     * Sets a new value for the input.
     * This updates the internal state, triggers the `onChange` and `onTouch` callbacks, 
     * and emits the `uppChanged` event.
     * 
     * @param {ReturnedAddress} v - The new value to set.
     */      
    set value(v: string | MapAddress | null) {
        Iif ((this._innerValue != v) && ((this._innerValue == null) || (v == null) || (JSON.stringify(v) != JSON.stringify(this._innerValue)))){
            this._innerValue = v;
            this.onChange();
            
            this._onChangeCallback(v);
            this._onTouchCallback();
        }
    }    
    
    /********************************************/
    /* ControlValueAccessor                     */
    /********************************************/
    
    /**
     * Writes a value to the input. Required by `ControlValueAccessor`.
     * @param {string} value - The value to write.
     */    
    writeValue(value: string | MapAddress | null) {
        Iif (value !== this._innerValue) {
            this.value = value;
            this.onChange();
        }        
    }
 
    /**
     * Registers a callback function to be called when the input value changes.
     * Required by `ControlValueAccessor`.
     * @param {Function} fn - The callback function.
     */    
    registerOnChange(fn: any) {
        this._onChangeCallback = fn;
    }
 
    /**
     * Registers a callback function to be called when the input is touched.
     * Required by `ControlValueAccessor`.
     * @param {Function} fn - The callback function.
     */    
    registerOnTouched(fn: any) {
        this._onTouchCallback = fn;
    }  
}