All files / src app.utils.ts

74.33% Statements 197/265
75.64% Branches 59/78
82.5% Functions 33/40
73.51% Lines 186/253

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 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 8951x         1x             1x 31x 31x         1x               1x 1x 1x 1x 1x   1x                     3x                             1x                     5x 2x       5x 1x 1x 256x 256x 2048x   256x         5x 5x 16x     5x                         4x 2x     2x         2x 2x 3x 3x       2x                         1x     2x 2x 8x 8x   2x     1x                               2x 2x 2x 1x 1x   1x 1x 1x   1x   2x 1x     2x 2x                   1x   1x 1x 4x   1x                 1x 1x 1x 1x 4x   1x                 2x 2x   2x 2x 8x   2x                 2x 2x 2x 2x 8x   2x                 1x 1x 1x                     1x 1x 1x                                   2x                     1x 1x   1x 1x 1x 1x 1x 1x   1x                           2x                       2x             1x               16x       16x 16x 16x   16x                         24x 24x 24x   24x 7x     17x             6x 6x 6x 6x 6x       6x 1x     5x 35x   35x       35x 20x 20x 11x     20x     15x       5x 5x 5x           5x 3x   2x 1x     1x             3x   3x 3x 9x     3x 3x 12x 12x 6x   6x       3x   3x 3x   3x       3x             12x 1x     11x 11x 5x   5x 1x     5x 2x     5x 2x     5x     6x                 18x 18x 2x     16x 16x 16x 16x     16x                                                                                     1x 2x           9x 2x   9x               5x 5x 5x 3x 3x     2x                   4x 4x 2x 2x 2x             2x                                                                                                                                                                             1x                                                                                                                                                                                                                                                                                                                                                                                                                                
import { AppConstants } from "./app.constants";
 
/**
 * Utility class for generic helper functions.
 */
export class GenericUtils {
    
    /**
     * Generates a random UUID (v4).
     * @returns A string representation of a UUID.
     */
    public static uuidv4(): string {    // https://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }
 
    /** @internal  */
    private static _normalize_map: Map<string, string> = new Map();
 
    /**
     * Normalizes a string to be used as a variable.
     * @param str - The string to be normalized.
     * @returns The normalized string or null if no string is provided.
    */
    public static Normalize(str: string | null) : string | null {
        if (str){
            let _str = this._normalize_map.get(str);
            if (!_str){
                _str = str.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/\s/g, "_");
                this._normalize_map.set(str, _str);
            }
            return _str;
        }
 
        return null;    // no string provided
    }
 
    /**
     * Enables advanced logging on the console.
     * @returns Returns the hardcoded value for verbose logging.
     */
    public static VerboseLogging(level: number): boolean {
        return level < 4;
    }
 
    /**
     * Delays refresh to be perfomed every clock tick
     * @returns Returns the hardcoded value for delay refresh (true for production / expected behaviour).
     */
    public static DelayedRefresh(): boolean {
        return true;    // production value should be true
    }
 
    /********************************/
    /* CRC32 CALCULATION            */
    /********************************/
 
    private static _global_crcTable: Array <number> | null = null;
 
    /**
     * Calculates the CRC32 checksum of a given string.
     * This checksum is commonly used for error-checking in data transmission.
     * @param str - The input string to calculate the CRC32 checksum for. If null, it defaults to an empty string.
     * @returns The calculated CRC32 checksum as an unsigned integer.
     */
    public static CRC32(str: string | null): number{
 
        // https://stackoverflow.com/questions/18638900/javascript-crc32
        if (!str){
            str = '';
        }
 
        // build the CRC lookup table
        if (!this._global_crcTable){
            this._global_crcTable = [];
            for(let n=0; n < 256; n++) {
                let c = n;
                for(let k=0; k < 8; k++) {
                    c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
                }
                this._global_crcTable[n] = c;
            }
        }
 
        // calculate the CRC value
        let crc = 0 ^ (-1);
        for (let i=0; i < str.length; i++ ) {
            crc = (crc >>> 8) ^ this._global_crcTable[(crc ^ str.charCodeAt(i)) & 0xFF];
        }
 
        return (crc ^ (-1)) >>> 0;        
    }
    
    /********************************/
    /* DEEP OBJECT COPY             */
    /********************************/
 
    /**
     * Creates a deep copy of the given object.
     * @param obj - The object to be copied.
     * @returns A deep copy of the object.
     */   
    public static CopyObject(obj: any){
        if (obj === null || typeof obj !== 'object') {
            return obj;
        }
 
        Iif (obj instanceof Date) {  // create new instance for Date entries
            return new Date(obj.getTime());
        }
 
        // assings each property cloned object to the new object
        const _cloned: any = Array.isArray(obj) ? [] : {};
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {                
                _cloned[key] = this.CopyObject(obj[key]);
            }
        }
    
        return _cloned;
    }
 
    /********************************/
    /* SIMPLE (QUICK) HASH          */
    /********************************/
 
    /**
     * Generates a simple hash of a given string.
     * @param str - The string to hash.
     * @returns The hashed string.
    */   
    public static simpleHash(str: string){
        const rev = str.split('').reverse().join('');
 
        function _hash(str: string) {
            let hash = 0;
            for (let i = 0; i < str.length; i++) {
                const char = str.charCodeAt(i);
                hash = (hash << 5) - hash + char;
            }
            return (hash >>> 0).toString(36).padStart(7, '0');        
        }
 
        return _hash(str) + _hash(rev);
    }
 
    /********************************/
    /* ARRAY BUFFER SERIALIZATION   */
    /********************************/
   
    /**
     * Converts an image URL to a base64 string.
     * @param url - The image URL.
     * @param format - The format of the image (default is 'image/png').
     * @param resize - The resize factor (default is 1.0).
     * @param quality - The quality factor (default is 0.8).
     * @returns A promise that resolves to the base64 string of the image.
     */   
    public static imageTobase64(url: string, format='image/png', resize=1.0, quality=0.8) {
        return new Promise <string> ((resolve, reject) =>{
            const _img = new Image();
            _img.onload = () => {
                const _cnv: any = document.createElement("canvas");
                const _ctx: any = _cnv.getContext("2d");
 
                _cnv.width = _img.naturalWidth * resize;
                _cnv.height = _img.naturalHeight * resize;
                _ctx.drawImage(_img, 0, 0, _cnv.width, _cnv.height);
 
                resolve(_cnv.toDataURL(format, quality));
            }
            _img.onerror = () => {
                reject(new Error(`Failed to load image from URL: ${url}`));
            };
 
            _img.crossOrigin = "Anonymous";
            _img.src = url;
        });
    }
 
    /**
     * Converts a Uint8Array to a base64 string.
     * @param bytes - The Uint8Array to convert.
     * @returns The base64 encoded string.
     */   
    public static uint8ArrayToBase64(bytes: Uint8Array): string {
        const length = bytes.byteLength;
 
        let binary = '';
        for (let i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }
   
    /**
     * Converts a base64 string to a Uint8Array.
     * @param base64 - The base64 encoded string.
     * @returns The resulting Uint8Array.
     */   
    public static base64ToUint8Array(base64: string): Uint8Array {
        const binary_string = window.atob(base64);
        const len = binary_string.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes;
    }
 
    /**
     * Converts an ArrayBuffer to a base64 string.
     * @param buffer - The ArrayBuffer to convert.
     * @returns The base64 encoded string.
     */   
    public static arrayBufferToBase64(buffer: ArrayBuffer): string {
        const bytes = new Uint8Array(buffer);
        const len = bytes.byteLength;
 
        let binary = '';
        for (let i = 0; i < len; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }
 
    /**
     * Converts a base64 string to an ArrayBuffer.
     * @param base64 - The base64 encoded string.
     * @returns The resulting ArrayBuffer.
     */   
    public static base64ToArrayBuffer(base64: string): ArrayBuffer {
        const binary_string = window.atob(base64);
        const len = binary_string.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }
 
    /**
     * Converts a string to a base64 encoded string.
     * @param str - The string to convert.
     * @returns The base64 encoded string or null if conversion fails.
     */   
    public static stringToBase64(str: string): string | null {
        const _arraybuffer = new TextEncoder().encode(str).buffer;
        if (_arraybuffer){
            return GenericUtils.arrayBufferToBase64(_arraybuffer);
        }
        return null;
    }
 
    /**
     * Converts a base64 string back to a regular string.
     * @param base64 - The base64 encoded string.
     * @returns The decoded string or null if conversion fails.
     */   
    public static base64ToString(base64: string): string | null {
        const _arraybuffer = GenericUtils.base64ToArrayBuffer(base64);
        if (_arraybuffer){
            return new TextDecoder().decode(_arraybuffer);
        }
        return null;
    }
 
    /********************************/
    /* MYSQL DATA CONVERSION        */
    /********************************/    
 
    /**
     * Converts a MySQL datetime string to an ISO 8601 date string.
     * This method replaces the space in a MySQL datetime string with a `T` 
     * and appends `.000Z` to convert it to UTC format.
     * 
     * @param date - The MySQL datetime string to convert. Example: `"2024-12-19 12:34:56"`.
     * @returns The ISO 8601 date string in UTC format, or `null` if the input is `null` or empty.
     */    
    public static mysqlToDateStr(date: string | null): string | null {
        return date ? date.replace(' ', 'T') + '.000Z' : null;
    }    
 
    /**
     * Converts a `Date` object to a MySQL datetime string.
     * This method formats the date in the MySQL `YYYY-MM-DD HH:MM:SS` format in UTC.
     * 
     * @param date - The `Date` object to convert.
     * @returns The formatted MySQL datetime string in UTC.
     */    
    public static dateStrToMysql(date: Date | null | undefined) : string | null{
        if (date){
            let _mysqldate = '';
 
            _mysqldate += date.getUTCFullYear() + '-';
            _mysqldate += ('00' + (date.getUTCMonth()+1)).slice(-2) + '-';
            _mysqldate += ('00' + date.getUTCDate()).slice(-2) + ' ';
            _mysqldate += ('00' + date.getUTCHours()).slice(-2) + ':'; 
            _mysqldate += ('00' + date.getUTCMinutes()).slice(-2) + ':'; 
            _mysqldate += ('00' + date.getUTCSeconds()).slice(-2);        
    
            return _mysqldate;    
        }
 
        return null;
    }
 
    /**
     * Extracts the file name from a file path for MySQL storage.
     * This method removes the directory path, leaving only the file name.
     * 
     * @param file - The file path to process. Example: `"/path/to/file.jpg"`.
     * @returns The extracted file name, or `null` if the input is `null` or empty.
     */    
    public static uploadToMysql(file: string | null){
        return file ? file.substring(file.lastIndexOf('/') + 1) : null;
    }
 
    /**
     * Converts a MySQL file reference to a full upload URL.
     * This method constructs a URL using a base URL, upload path, and the provided file name.
     * 
     * @param file - The file name stored in MySQL. Example: `"file.jpg"`.
     * @returns The full upload URL, or `null` if the input is `null` or empty.
     *          Example: `"https://example.com/uploads/file.jpg"`.
     */    
    public static mysqlToUpload(file: string | null){
        return file ? (AppConstants.baseURL + AppConstants.uploadPath + file) : null;
    }    
}
 
/**
 * Utility class for validating Spanish Tax Identifiers such as DNI and CIF.
 */
export class TaxIdValidators {
 
    /**
     * Formats a tax ID string.
     * @param taxid - The tax ID to format.
     * @returns A formatted tax ID string.
     */    
    public static ToTaxId(taxid: string) : string | null {
        Iif (!taxid) {
            return null;
        }
 
        let _taxid = taxid;
        if (taxid){
            _taxid = _taxid.toUpperCase().replace(/[^A-Z0-9]/g, '');
        }
        return _taxid;    
    }
 
    /*************************/
    /* DNI/CIF VALIDATORS    */
    /*************************/
    
    // https://www.lawebdelprogramador.com/codigo/JavaScript/1992-Validar-un-CIF-NIF-y-DNI.html
 
    /**
     * @internal
     */
    private static _ValidateDNI(dni: string): boolean {
        const lockup = 'TRWAGMYFPDXBNJZSQVHLCKE';
        const valueDni: string = dni.substring(0, dni.length - 1);
        const letra: string = dni.substring(dni.length - 1).toUpperCase();
 
        if (lockup.charAt(Number(valueDni) % 23) === letra) {
            return true;
        }
 
        return false;
    }
 
    /**
     * @internal
     */    
    private static _ValidateCIF_type1(cif: string): boolean {
        const letters: string[] = ['J', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
        const digits: string = cif.substring(1, cif.length - 1);
        const letter: string = cif.substring(0, 1);
        const control: string = cif.substring(cif.length - 1);
        let sum = 0;
        let i: number;
        let digit: number;
   
        if (!letter.match(/[A-Z]/)) {
            return false;
        }
   
        for (i = 0; i < digits.length; ++i) {
            digit = parseInt(digits[i]);
   
            Iif (isNaN(digit)) {
                return false;
            }
   
            if (i % 2 === 0) {
                digit *= 2;
                if (digit > 9) {
                    digit = Math.floor(digit / 10) + (digit % 10);
                }
   
                sum += digit;
            } 
            else {
                sum += digit;
            }
        }
   
        sum %= 10;
        if (sum !== 0) {
            digit = 10 - sum;
        } 
        else E{
            digit = sum;
        }
   
        if (letter.match(/[ABEH]/)) {
            return String(digit) === control;
        }
        if (letter.match(/[NPQRSW]/)) {
            return letters[digit] === control;
        }
   
        return String(digit) === control || letters[digit] === control;
    }
 
    /**
     * @internal
     */
    private static _ValidateCIF_type2(cif: string): boolean {
        const valueCif = cif.substring(1, cif.length - 1);
    
        let suma = 0;
        for (let i = 1; i < valueCif.length; i += 2) {
            suma += parseInt(valueCif.substring(i, i + 1));
        }
    
        let suma2 = 0;
        for (let i = 0; i < valueCif.length; i += 2) {
            const result = parseInt(valueCif.substring(i, i + 1)) * 2;
            if (String(result).length === 1) {
                suma2 += result;
            } else {
                suma2 += parseInt(String(result).substring(0, 1)) + parseInt(String(result).substring(1, 2));
            }
        }
    
        suma += suma2;
    
        let unidad = parseInt(String(suma).substring(1, 2));
        unidad = 10 - unidad;
    
        Iif (unidad === 10) {
            unidad = 0;
        }
    
        return (cif.substring(cif.length - 1) === String(unidad));
    }    
 
    /**
     * @internal
     */
    private static _ValidateCIF(cif: string): boolean {
        if (!cif || cif.length !== 9) {
            return false;
        }
    
        const primerCaracter = cif.substring(0, 1);
        if (primerCaracter.match(/^[XYZ]$/)) {
            let newcif = "";
    
            if (primerCaracter === "X") {
                newcif = cif.substring(1);
            }
    
            if (primerCaracter === "Y") {
                newcif = "1" + cif.substring(1);
            }
    
            if (primerCaracter === "Z") {
                newcif = "2" + cif.substring(1);
            }
    
            return this._ValidateDNI(newcif);
        }
    
        return this._ValidateCIF_type1(cif) || this._ValidateCIF_type2(cif) || this._ValidateDNI(cif);
    }
    
    /**
     * Validates a generic Spanish tax ID (DNI or CIF).
     * @param value - The tax ID to validate.
     * @returns True if the tax ID is valid, otherwise false.
     */    
    public static ValidateTaxId(value: string | null): boolean{
        let _valid = false;
        if (!value){
            return false;
        }
 
        const _taxid = this.ToTaxId(value);
        if (_taxid){
            _valid = _valid || this._ValidateDNI(_taxid);
            _valid = _valid || this._ValidateCIF(_taxid);
        }
 
        return _valid;
    }    
}
 
/**
 * Class for managing global mutex locks.
 * 
 * ### Example
 * ```typescript
 * async function exampleUsage() {
 *     // Create an instance of GlobalMutex
 *     const mutex = new GlobalMutex();
 * 
 *     // Define a function that requires exclusive access
 *     async function criticalSection(key: string) {
 *         console.log(`Attempting to lock the key: ${key}`);
 *         
 *         // Lock the key
 *         await mutex.lock(key);
 *         console.log(`Key locked: ${key}`);
 *         
 *         // Critical section
 *         console.log(`Executing critical section for key: ${key}`);
 *         await new Promise((resolve) => setTimeout(resolve, 1000)); // Simulates async task
 * 
 *         // Unlock the key
 *         mutex.unlock(key);
 *         console.log(`Key unlocked: ${key}`);
 *     }
 * 
 *     // Run multiple calls with the same key
 *     criticalSection("resource1");
 *     criticalSection("resource1");
 *     criticalSection("resource1");
 * 
 *     // Managing different keys simultaneously
 *     criticalSection("resource2");
 * }
 * 
 * // Call the example function
 * exampleUsage();
 * ```
 */
export class GlobalMutex {
    private _mutex: Map<string, { locked: boolean; queue: (() => void)[] }> = new Map();
 
    /**
     * @internal
     */    
    private _getMutex(key: string): { locked: boolean; queue: (() => void)[] } {
        if (!this._mutex.has(key)) {
            this._mutex.set(key, { locked: false, queue: [] });
        }
        return this._mutex.get(key) as { locked: boolean; queue: (() => void)[] };
    }
 
    /**
     * Locks the specified key, blocking further calls until the lock is released.
     * @param key - The key to lock.
     */    
    async lock(key: string) {
        const mutex = this._getMutex(key);
        await new Promise<void>((resolve) => {
            if (!mutex.locked) {
                mutex.locked = true;
                resolve();
            } 
            else {
                mutex.queue.push(resolve);
            }
        });
    }
 
    /**
     * Releases the lock on the specified key, allowing queued calls to proceed.
     * @param key - The key to unlock.
     */    
    unlock(key: string) {
        const mutex = this._getMutex(key);
        if (mutex.queue.length > 0) {
            const resolve = mutex.queue.shift();
            if (resolve) {
                resolve();
            } 
            else E{
                mutex.locked = false;
            }
        } 
        else {
            mutex.locked = false;
        }
    }
}
 
/**
 * Represents a split of a price amount with its tax information
 */
type TaxesSplit = {
    /** The total amount including taxes */
    total: number, 
    /** The tax rate as a percentage (e.g., 21 for 21%) */
    rate: number, 
    /** The base amount without taxes */
    base: number, 
    /** The tax amount */
    taxes: number 
}
 
/**
 * Aggregated tax information for a price
 */
type TaxesInfo = {
    /** The total amount including all taxes */
    total: number,
    /** The sum of all base amounts without taxes */
    base: number,
    /** The sum of all tax amounts */
    taxes: number,
    /** Detailed breakdown of taxes by rate */
    split: Array<TaxesSplit>
}
 
/**
 * Comprehensive price information with tax details and formatting
 * 
 */
export type PriceType = {
    /** The total price value including taxes */
    val: number, 
    /** Indicates whether the price is negative */
    neg: boolean,
    /** The absolute value of the price (always positive) */
    abs: number,
    /** The integer part of the absolute price value */
    int: string,
    /** The decimal part of the absolute price value */
    dec: string,
    /** Formatted price string with comma as decimal separator (e.g., "123,45") */
    str: string,
    /** Detailed tax information including base amounts, tax amounts, and breakdown by tax rates */
    tax: TaxesInfo,
    /** Detailed discount information including base amounts, tax amounts, and breakdown by tax rates */
    dsc: TaxesInfo
}
 
/**
 * A class for handling price calculations with different tax rates
 * 
 * This class manages price components with their respective tax rates,
 * calculates tax amounts, and provides formatted price information.
 * It supports multiple discounts that are applied proportionally across
 * all tax groups based on their relative weight in the total.
 * 
 * @example
 * ```typescript
 * const price = new PriceInfo();
 * price.Add(100, 21); // Add 100€ with 21% tax rate
 * price.Add(50, 10);  // Add 50€ with 10% tax rate
 * price.Del(30);      // Add a 30€ discount
 * const priceInfo = price.price; // Get complete price information
 * console.log(`Total: ${priceInfo.val}€, Taxes: ${priceInfo.tax.taxes}€`);
 * // Output: Total: 120€, Taxes: ~19.83€
 * ```
 * 
 * @example Multiple discounts
 * ```typescript
 * const price = new PriceInfo();
 * price.Add(100, 21); // Add 100€ with 21% tax rate
 * price.Add(50, 10);  // Add 50€ with 10% tax rate
 * price.Del(30);      // First discount: 30€
 * price.Del(20);      // Second discount: 20€ (applied to remaining amount)
 * const priceInfo = price.price;
 * console.log(`Final total: ${priceInfo.val}€`);
 * // Discounts are applied proportionally to each tax group
 * ```
 */
export class PriceInfo {
    private _val = 0;       // total price value
    private _dsc = 0;       // total discount value
 
    private _taxmap = new Map <number, TaxesSplit> ();  // increments map
    private _dscmap = new Map <number, TaxesSplit> ();  // decrements map
 
    /**
     * Creates a new PriceInfo instance
     * 
     * @param total - Optional initial amount to add (including tax)
     * @param rate - Optional tax rate for the initial amount as a percentage (e.g., 21 for 21%)
     */    
    constructor(total = 0, rate = AppConstants.defaultTaxRate){
        this.Add(total, rate);
    }
 
    /**
     * Adds a price amount with a specific tax rate to the price
     * 
     * If multiple amounts are added with the same tax rate, they will be 
     * aggregated into a single tax group.
     * 
     * @param amount - The amount to add (including tax). Must be positive.
     * @param taxrate - The tax rate as a percentage (e.g., 21 for 21%). Must be non-negative.
     * 
     * @example
     * ```typescript
     * price.Add(100, 21);    // Add 100€ with 21% tax
     * price.Add(50, 21);     // Add another 50€ with same tax rate (will aggregate)
     * // Result: 150€ total with 21% tax rate
     * ```
     */     
    Add(amount: number, taxrate: number): void {
        this._val += amount;
        
        let _split: TaxesSplit | null = this._taxmap.get(taxrate) || null;
        Iif (!_split){
            _split = { total: 0, rate: taxrate, base: 0, taxes: 0 };
        }
 
        _split.total += amount;
        this._taxmap.set(taxrate, _split);
    }
 
    /**
     * Removes a gross amount from the total, distributed proportionally across all existing tax rates.
     * 
     * The removal amount is allocated to each tax group based on its relative weight in the total.
     * Both base and tax amounts are adjusted accordingly. The discount is applied when the 
     * price getter is called, ensuring all prices are set before calculating proportions.
     * 
     * @param taxmap - Array of tax splits (cloned from _taxmap) to apply discounts to
     * @param amount - The total amount to remove (including tax). Must be positive.
     * 
     * @remarks
     * This method modifies the provided taxmap array in-place and updates the internal
     * _dscmap with the discount amounts for each tax rate. Discounts are limited by
     * the available amount in each tax group (cannot exceed the group's total).
     * 
     * @internal This is a private method used internally by the price getter.
     */ 
    private discount(taxmap: TaxesSplit[], amount: number): void {
        Iif (amount === 0 || this._val === 0) {
            return;
        }
 
        let total = 0;
        for (const split of taxmap){
            total += split.total;
        }
 
        let _applied = 0;
        for (const split of taxmap){
            let disct: TaxesSplit | null = this._dscmap.get(split.rate) || null;
            Iif (!disct){
                disct = { total: 0, rate: split.rate, base: 0, taxes: 0 };
            }            
 
            const _toapply = Math.min(amount * (split.total / total), split.total);
 
            disct.total += _toapply;
            _applied += _toapply;            
            split.total -= _toapply;    // adjust the remaining price (in the copy)
 
            this._dscmap.set(split.rate, disct);
        }
 
        this._dsc += _applied;
    }   
 
    private _discounts: Array <number> = [];
 
    /**
     * Pushes a discount value to be applied on final price calculation
     * 
     * Discounts are not applied immediately but stored for calculation when
     * the price getter is accessed. This allows for proper proportional
     * distribution based on the final price composition.
     * 
     * Multiple discounts are applied sequentially, with each subsequent
     * discount applied to the remaining amount after previous discounts.
     * 
     * @param amount - The total amount to remove (including tax). Must be positive.
     * 
     * @example
     * ```typescript
     * price.Del(30);  // Queue first discount
     * price.Del(20);  // Queue second discount
     * const info = price.price; // Both discounts applied proportionally
     * ```
     */    
    Del(amount: number){
        this._discounts.push(amount);
    }
 
    /**
     * Gets comprehensive price information including tax calculations and formatting
     * 
     * This property calculates the final price by applying all queued discounts
     * proportionally across tax groups, then computes base amounts, tax amounts,
     * and formats the result.
     * 
     * Discounts are applied in the order they were added, with each discount
     * applied to the remaining amount after previous discounts.
     * 
     * @returns An object containing:
     *  - val: Total price value after discounts
     *  - neg: Flag indicating if the price is negative
     *  - abs: Absolute price value
     *  - int: Integer part of the absolute price
     *  - dec: Decimal part of the absolute price  
     *  - str: Formatted price as string with comma as decimal separator
     *  - tax: Detailed tax information for the final amount
     *  - dsc: Detailed discount information broken down by tax rate
     * 
     * @example
     * ```typescript
     * const price = new PriceInfo();
     * price.Add(121, 21);  // 100€ base + 21€ tax
     * const info = price.price;
     * console.log(info.val);           // 121
     * console.log(info.tax.base);      // ~100
     * console.log(info.tax.taxes);     // ~21
     * console.log(info.str);           // "121,00"
     * ```
     */   
    get price(): PriceType {
        const _taxes: TaxesInfo = { total: 0, base: 0, taxes: 0, split: [] };
        const _dscnt: TaxesInfo = { total: 0, base: 0, taxes: 0, split: [] };
 
        // clone the source taxmap so its not affected by discounts aplication
        const _taxmap: TaxesSplit[] = Array.from(this._taxmap.values()).map(split => ({
            total: split.total,
            rate: split.rate,
            base: split.base,
            taxes: split.taxes
        }));
 
        // calculate the discounts once all the prices are set
        this._dscmap.clear();
        for(const _disc of this._discounts){
            this.discount(_taxmap, _disc);
        }
 
        // calculate the final price information
        for(const split of this._taxmap.values()){
            split.base = split.total / (1 + (split.rate / 100));
            split.taxes = split.total - split.base;
 
            _taxes.split.push(split);
 
            _taxes.total += split.total;
            _taxes.base += split.base;
            _taxes.taxes += split.taxes;
        }
 
        // adjust the totals with the discounts
        for(const split of this._dscmap.values()){
            split.base = split.total / (1 + (split.rate / 100));
            split.taxes = split.total - split.base;
 
            _dscnt.split.push(split);
            
            _taxes.total -= split.total;
            _taxes.base -= split.base;
            _taxes.taxes -= split.taxes;
        }
 
        _taxes.total = Math.round(_taxes.total * 100) / 100;
        _taxes.base = Math.round(_taxes.base * 100) / 100;
        _taxes.taxes = Math.round(_taxes.taxes * 100) / 100;
 
        const _val = this._val - this._dsc;
        const _abs = Math.abs(_val);
        const [_int, _dec] = _abs.toFixed(2).split(".");
 
        return {
            val: _val,
            neg: (_val < 0),
            abs: _abs,
            str: _int + "," + _dec,
            int: _int,
            dec: _dec,
            tax: _taxes,
            dsc: _dscnt
        }
    }
}