All files / src/services regulatory-declarations.service.ts

2.61% Statements 20/765
0% Branches 0/997
0% Functions 0/110
2.44% Lines 18/737

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 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 19521x 1x   1x       1x 1x 1x             1x               1x 1x 1x 1x   1x 1x                                                             1x 1x 1x   1x                                                                                                 1x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
import { cloneDeep, isEmpty, isNil, isObject, pick } from 'lodash';
import moment from 'moment';
 
import {
  declarationCargoSchema, declarationCPCSchema, declarationItemsSchema, declarationPartySchema, declarationTransportSchema,
  finalDeclarationsSchema, getSchemaByKey
} from '@logchain/apidefs';
import { Constants, LogChainConfigs } from '@logchain/configs';
import { toPartyObject, toTransportObject } from '@logchain/dtos';
import {
  BaseResponses, CarType, Flow, FlowPersona, PartyType, RegulatoryCargos, RegulatoryCascProducts, RegulatoryContainers, RegulatoryCustomsProcedureCodes, RegulatoryDeclarations,
  RegulatoryDeclarationsWithRelations, RegulatoryDocuments, RegulatoryInvoices, RegulatoryItems, RegulatoryItemsWithRelations,
  RegulatoryParties,
  RegulatorySubmissionHistories,
  RegulatoryTransports, Status, TransportMode, TransportType
} from '@logchain/models';
import {
  CalistaDropdownRepository, CompanyRegulatoryRepository, FlowPersonaRepository, FlowRepository, RegulatoryCargosRepository, RegulatoryCascProductsRepository,
  RegulatoryContainersRepository, RegulatoryCustomsProcedureCodesRepository, RegulatoryDeclarationsRepository,
  RegulatoryDeclarationsViewRepository,
  RegulatoryDocumentsRepository, RegulatoryInvoicesRepository, RegulatoryItemsRepository, RegulatoryPartiesRepository,
  RegulatorySubmissionHistoriesRepository, RegulatoryTransportsRepository
} from '@logchain/repositories';
import { AnyObject, RegulatoryDeclarationUpdateTransactionParam } from '@logchain/types';
import { DateUtils, ObjectUtils, StringUtils, ValidationError } from '@logchain/utils';
import { BindingScope, injectable, service } from '@loopback/core';
import { EntityNotFoundError, FilterBuilder, IsolationLevel, Options, repository, Where } from '@loopback/repository';
import { HttpErrors, SchemaObject, validateValueAgainstSchema } from '@loopback/rest';
 
import { BaseService, FlowJourneyService } from './';
import { CalistaResponseCode, CalistaStatusCode, MailTemplateMapping, SubmitResponse } from './calista.service';
import { RegulatoryDeclarationsView } from '@logchain/models/views';
 
function extractJobNo(str?: string): [number, number] {
  if (!str) return [0, 0];
  const date = +str.slice(0, 8);
  const seqNo = +str.slice(8).replace(/0/g, '');
  return [date, seqNo];
}
 
function numberFormat(number: string, width: number) {
  return new Array(+width + 1 - (number + '').length).join('0') + number;
}
 
function cleanObject(obj: AnyObject) {
  Object.entries(obj)
    .forEach(([k, v]) => {
      if (isObject(v)) {
        cleanObject(v);
      }
      if (isObject(v) && !Object.keys(v).length || isNil(v)) {
        if (Array.isArray(obj)) {
          obj.splice(+k, 1);
        } else {
          delete obj[k];
        }
      }
    });
  return obj;
}
 
const MAXIMUM_CASC_PRODUCTS_ALLOWED = 5;
const MAXIMUM_ITEMS_ALLOWED = 50;
const MAXIMUM_INVOICE_ALLOWED = 20;
 
const MIME_TYPES_ALLOWED = [
  'application/msword',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  'application/vnd.ms-excel',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  'application/pdf',
  'image/jpeg',
  'image/png',
  'image/bmp',
  'image/gif',
  'image/tiff'
];
 
function getEnumKeyByEnumValue<
  TEnumKey extends string,
  TEnumVal extends string | number
>(myEnum: { [key in TEnumKey]: TEnumVal }, enumValue: TEnumVal): string {
  const keys = (Object.keys(myEnum) as TEnumKey[]).filter((x) => myEnum[x] === enumValue);
  return keys.length > 0 ? keys[0] : '';
};
 
function bytesToKilobyte(bytes?: number, precision = 2) {
  return Number(((bytes ?? 0) / Constants.KILOBYTE).toFixed(precision));
}
 
function convertName(data: AnyObject, field?: string) {
  const finalNameField = field ?? 'name';
  const nameObject = <AnyObject>{};
  if (!data) { return };
  const { name1, name2 } = data;
  const name = [];
  nameObject[finalNameField] = cloneDeep(name1);
  name.push(cloneDeep(nameObject));
  if (name2) {
    nameObject[finalNameField] = cloneDeep(name2);
    name.push(cloneDeep(nameObject));
  }
  return name;
}
 
function convertAddress(data: AnyObject) {
  if (!data) { return };
  const { address1, address2 } = data;
  const address = [{ address: address1 }]
  if (address2) { address.push({ address: address2 }) }
  return address;
}
 
@injectable({ scope: BindingScope.TRANSIENT })
export class RegulatoryDeclarationsService extends BaseService<RegulatoryDeclarations>{
  constructor(
    @repository(RegulatoryDeclarationsRepository)
    public regulatoryDeclarationsRepo: RegulatoryDeclarationsRepository,
    @repository(RegulatoryDeclarationsViewRepository)
    public regulatoryDeclarationsViewRepo: RegulatoryDeclarationsViewRepository,
    @repository(RegulatoryPartiesRepository)
    public regulatoryPartiesRepo: RegulatoryPartiesRepository,
    @repository(RegulatoryCargosRepository)
    public regulatoryCargosRepo: RegulatoryCargosRepository,
    @repository(RegulatoryContainersRepository)
    public regulatoryContainersRepo: RegulatoryContainersRepository,
    @repository(RegulatoryTransportsRepository)
    public regulatoryTransportsRepo: RegulatoryTransportsRepository,
    @repository(RegulatoryDocumentsRepository)
    public regulatoryDocumentsRepo: RegulatoryDocumentsRepository,
    @repository(RegulatoryCustomsProcedureCodesRepository)
    public regulatoryCustomsProcedureCodesRepo: RegulatoryCustomsProcedureCodesRepository,
    @repository(RegulatoryInvoicesRepository)
    public regulatoryInvoicesRepo: RegulatoryInvoicesRepository,
    @repository(RegulatoryItemsRepository)
    public regulatoryItemsRepo: RegulatoryItemsRepository,
    @repository(RegulatoryCascProductsRepository)
    public regulatoryCascProductsRepo: RegulatoryCascProductsRepository,
    @repository(RegulatorySubmissionHistoriesRepository)
    public regulatorySubmissionHistoriesRepo: RegulatorySubmissionHistoriesRepository,
    @repository(CompanyRegulatoryRepository)
    public companyRegulatoryRepo: CompanyRegulatoryRepository,
    @repository(CalistaDropdownRepository)
    public calistaDropdownRepo: CalistaDropdownRepository,
    @repository(FlowRepository)
    public flowRepo: FlowRepository,
    @repository(FlowPersonaRepository)
    public flowPersonaRepo: FlowPersonaRepository,
    @service(FlowJourneyService)
    public flowJourneyService: FlowJourneyService,
  ) {
    super();
  }
 
  async validateRegulatoryDeclarations(model: Partial<RegulatoryDeclarations>) {
    if (model.flow_id) {
      const flow = await this.flowRepo.count({
        id: model.flow_id,
        live_status: {
          inq: [Status.LiveStatus.New, Status.LiveStatus.InTransit]
        }
      });
      if (!flow.count) {
        throw new HttpErrors.NotFound(`Not found or invalid status of the flow: ${model.flow_id}!`);
      }
    }
 
    if (model.car_type === CarType.IPTDEC) {
      delete model.out_tpt_mode;
      if (model.dec_type === 'BKT') {
        delete model.in_tpt_mode;
      }
    }
 
    if ((model.car_type === CarType.INPDEC)) {
      if (model.dec_type === 'BKT') {
        delete model.in_tpt_mode;
      }
 
      if (model.dec_type && ['APS', 'BKT', 'GTR', 'SHO', 'DES', 'TCS', 'TCR', 'TCE', 'TCO', 'TCI'].includes(model.dec_type)) {
        delete model.out_tpt_mode;
      }
    }
 
    if (model.car_type === CarType.OUTDEC &&
      model.dec_type && ['APS', 'BKT', 'TCE', 'TCI', 'TCO', 'TCR', 'TCS'].includes(model.dec_type)) {
      delete model.in_tpt_mode;
    }
 
    return model;
  }
 
  async create(model: Partial<RegulatoryDeclarations>, options: Options = {}): Promise<RegulatoryDeclarationsWithRelations> {
    const latestRegulatory = await this.companyRegulatoryRepo.findOne({
      where: {
        company_id: this.current_user.company_id,
      },
      order: ['created_date DESC']
    });
 
    if (latestRegulatory?.status !== Status.CompanyRegulatory.Accepted) {
      throw new HttpErrors.BadRequest("Creation of new declarations is not allowed. Please make sure your company has an active regulatory rights.");
    }
 
    model = await this.validateRegulatoryDeclarations(model);
    return this.regulatoryDeclarationsRepo.create({
      ...model,
      company_regulatory_id: latestRegulatory.id,
      company_id: this.current_user.company_id,
      status: Status.RegulatoryDeclaration.Draft,
      seq_no: 1, // Can be any number provided by LogChain
    }, options);
  }
 
  /**
   * Duplicate one declaration
   * @param  {number} declarationId
   * @param  {AnyObject} setting
   * @returns Promise
   */
  async clone(declarationId: number, setting: AnyObject ): Promise<RegulatoryDeclarationsWithRelations> {
    let idx = 1;
    // Create tab header
    const oldDeclaration = await this.getByIdOrIdentifier(declarationId) as AnyObject;
    const newDeclarationProperties = Object.keys(RegulatoryDeclarations.definition.properties);
    const newDeclaration = {};
    ObjectUtils.assignByProperties(oldDeclaration, newDeclaration, newDeclarationProperties, setting?.all ? undefined : setting.header);
    const clonedDeclaration = await this.create(newDeclaration);
    // ---------------------------------
    
    // Create tab party
    if (setting?.all || setting.party) {
      try {
        const newParties = [] as RegulatoryParties[];
        const oldParties = oldDeclaration.parties || [];
        oldParties.map((oldParty: RegulatoryParties) => {
          if (!setting?.all && (!setting?.party || !setting?.party[oldParty.type.replace(/-/g, '_')])) {
            return true;
          }
          const newPartyProperties = Object.keys(RegulatoryParties.definition.properties);
          const newParty = {} as RegulatoryParties;
          ObjectUtils.assignByProperties(
            oldParty as unknown as Record<string, AnyObject>, 
            newParty as unknown as Record<string, AnyObject>, 
            newPartyProperties
          );
          newParty.declaration_id = clonedDeclaration.id;
          newParties.push(newParty);
        })
        clonedDeclaration.parties = newParties.length ? await this.regulatoryPartiesRepo.createAll(newParties) : [];
      } catch (error) {
        console.error('party: ', error);
      }
    }
    // ---------------------------------
    
    // Create tab cargo
    if (setting?.all || (oldDeclaration.cargo && setting?.cargo)) {
      try {
        idx = 1;
        const newCargo = {} as RegulatoryCargos;
        const newCargoProperties = Object.keys(RegulatoryCargos.definition.properties);
        const { containers: settingCargoContainers, ...settingCargo } = setting.cargo || { containers: {} };
        ObjectUtils.assignByProperties(oldDeclaration.cargo, newCargo as unknown as Record<string, AnyObject>, newCargoProperties, setting?.all ? undefined : settingCargo);
        newCargo.declaration_id = clonedDeclaration.id;
        clonedDeclaration.cargo = await this.regulatoryCargosRepo.create(newCargo);
        if (oldDeclaration.cargo?.containers) {
          const containers = oldDeclaration.cargo.containers as RegulatoryContainers[];
          // Containers
          const pContainerTasks: Promise<RegulatoryContainers>[] = [];
          containers.map(async ({ id, ...payloadContainer }) => {
            if (!setting?.all && (!settingCargoContainers[id] || Object.keys(settingCargoContainers[id]).length === 0)) {
              return false;
            }
            const settingCargoContainer = setting?.all ? undefined : settingCargoContainers[id];
            const newPayloadContainer = {} as RegulatoryContainers;
            const newPayloadContainerProperties = Object.keys(RegulatoryContainers.definition.properties);
            ObjectUtils.assignByProperties(
              payloadContainer as unknown as Record<string, AnyObject>, 
              newPayloadContainer as unknown as Record<string, AnyObject>, 
              newPayloadContainerProperties,
              settingCargoContainer,
            );
            newPayloadContainer.seq_no = idx++;
            newPayloadContainer.declaration_cargo_id = clonedDeclaration.cargo?.id as number;
            pContainerTasks.push(this.regulatoryContainersRepo.create(newPayloadContainer));
          });
          clonedDeclaration.cargo.containers = pContainerTasks.length ? await Promise.all(pContainerTasks) : [];
        }
      } catch (error) {
        console.error('cargo: ', error);
      }
    }
    // ---------------------------------
 
    // Create tab in_trans or out_trans
    if (setting?.all || (oldDeclaration.transports && (setting?.in_trans || setting?.out_trans))) {
      try {
        idx = 1;
        const newTransports = [] as RegulatoryTransports[];
        const oldTransports = oldDeclaration.transports || [];
        oldTransports.map((oldTransport: RegulatoryTransports) => {
          const type = oldTransport.type === TransportType.IN_TRANS ? 'in_trans' : 'out_trans';
          if (!setting?.all && (!setting[type] || Object.keys(setting[type]).length === 0)) {
            return false;
          }
          const settingTransport = setting?.all ? undefined : (setting[type] ?? {});
          const newTransport = {} as RegulatoryTransports;
          const newTransportProperties = Object.keys(RegulatoryTransports.definition.properties);
          ObjectUtils.assignByProperties(
            oldTransport as unknown as Record<string, AnyObject>, 
            newTransport as unknown as Record<string, AnyObject>, 
            newTransportProperties, 
            settingTransport
          );
          newTransport.declaration_id = clonedDeclaration.id;
          newTransport.type = oldTransport.type;
          newTransports.push(newTransport);
        });
        clonedDeclaration.transports = newTransports.length ? await this.regulatoryTransportsRepo.createAll(newTransports) : [];
      } catch (error) {
        console.error('transports: ', error);
      }
    }
    // ---------------------------------
 
    // Create tab ref_document
    if (setting?.all || setting?.ref_document) {
      try {
        idx = 1;
        const documents = oldDeclaration.documents as RegulatoryDocuments[] || [];
        const pDocumentTasks: Promise<RegulatoryDocuments>[] = [];
        documents.map(async ({ id, ...payloadDocument }) => {
          if (!setting?.all && !setting?.ref_document[id]) {
            return false;
          }
          payloadDocument.s3_uri = (await this.duplicateS3Object(payloadDocument.s3_uri)).s3_uri;
          payloadDocument.declaration_id = clonedDeclaration.id as number;
          payloadDocument.seq_no = idx++;
          pDocumentTasks.push(this.regulatoryDocumentsRepo.create(payloadDocument));
        });
        clonedDeclaration.documents = pDocumentTasks.length ? await Promise.all(pDocumentTasks) : [];
      } catch (error) {
        console.error('ref_document: ', error);
      }
    }
    // ---------------------------------
 
    // Create tab invoice
    if (setting?.all || setting?.invoice) {
      try {
        idx = 1;
        const newInvoices = [] as RegulatoryInvoices[];
        const invoiceFilter = new FilterBuilder<RegulatoryInvoices>();
        invoiceFilter.offset(0);
        invoiceFilter.limit(1000);
        const oldInvoices = (await this.findInvoices(oldDeclaration.id, invoiceFilter)).data;
        oldInvoices.map((oldInvoice: RegulatoryInvoices) => {
          if (!setting?.all && (!setting?.invoice || !setting?.invoice[oldInvoice.id] || Object.keys(setting?.invoice[oldInvoice.id]).length === 0)) {
            return false;
          }
          const invoiceSetting = setting?.all ? undefined : setting?.invoice[oldInvoice.id];
          const newInvoice = {} as RegulatoryInvoices;
          const newInvoiceProperties = Object.keys(RegulatoryInvoices.definition.properties);
          ObjectUtils.assignByProperties(
            oldInvoice as AnyObject, 
            newInvoice as AnyObject, 
            newInvoiceProperties,
            invoiceSetting,
          );
          newInvoice.declaration_id = clonedDeclaration.id;
          newInvoice.seq_no = idx++;
          newInvoices.push(newInvoice);
        });
        clonedDeclaration.invoices = newInvoices.length ? await this.regulatoryInvoicesRepo.createAll(newInvoices) : [];
      } catch (error) {
        console.error('invoice: ', error);
      }
    }
    // ---------------------------------
 
    // Create tab items
    if (setting?.all || setting?.items) {
      try {
        idx = 1;
        const oldItems = oldDeclaration.items || [];
        const pItemTasks = oldItems.map(async (oldItem: RegulatoryItems) => {
          if (!setting?.all && (!setting?.items || !setting?.items[oldItem.id] || Object.keys(setting?.items[oldItem.id]).length === 0)) {
            return false;
          }
          const itemsSetting = setting?.all ? undefined : setting?.items[oldItem.id];
          let newItem = {} as RegulatoryItems;
          const newItemProperties = Object.keys(RegulatoryItems.definition.properties);
          ObjectUtils.assignByProperties(
            oldItem as AnyObject, 
            newItem as AnyObject, 
            newItemProperties, 
            itemsSetting
          );
          newItem.declaration_id = clonedDeclaration.id;
          newItem.seq_no = idx++;
          newItem = await this.regulatoryItemsRepo.create(newItem);
          newItem.cascProducts = await this.upsertCascProducts(newItem.id, oldItem.cascProducts, {}) as RegulatoryCascProducts[];
          return newItem;
        });
        clonedDeclaration.items = idx > 1 ? await Promise.all(pItemTasks) : [];
      } catch (error) {
        console.error('items: ', error);
      }
    }
    // ---------------------------------
 
    // Create tab cpc
    if (setting?.all || setting?.cpc) {
      try {
        idx = 1;
        const newCustomsProcedureCodes = [] as RegulatoryCustomsProcedureCodes[];
        const oldCustomsProcedureCodes = oldDeclaration.customsProcedureCodes || [];
        oldCustomsProcedureCodes.map((oldCustomsProcedureCode: RegulatoryCustomsProcedureCodes) => {          
          if (!setting?.all && (!setting?.cpc || !setting?.cpc[oldCustomsProcedureCode.id])) {
            return false;
          }
          const newCustomsProcedureCode = {} as RegulatoryCustomsProcedureCodes;
          const newCustomsProcedureCodeProperties = Object.keys(RegulatoryCustomsProcedureCodes.definition.properties);
          ObjectUtils.assignByProperties(
            oldCustomsProcedureCode as AnyObject, 
            newCustomsProcedureCode as AnyObject, 
            newCustomsProcedureCodeProperties,
          );
          newCustomsProcedureCode.seq_no = idx++;
          newCustomsProcedureCode.declaration_id = clonedDeclaration.id;
          newCustomsProcedureCodes.push(newCustomsProcedureCode);
        });
        clonedDeclaration.customsProcedureCodes = idx > 1 ? await this.regulatoryCustomsProcedureCodesRepo.createAll(newCustomsProcedureCodes) : [];
      } catch (error) {
        console.error('cpc: ', error);
      }
    }
    // ---------------------------------
 
    return clonedDeclaration;
  }
 
  async updateByIdOrIdentifier(id: number, model: Partial<RegulatoryDeclarations>, options?: Options) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(id);
    model = await this.validateRegulatoryDeclarations({
      dec_type: dbRegulatoryDeclarations.dec_type,
      car_type: dbRegulatoryDeclarations.car_type,
      in_tpt_mode: dbRegulatoryDeclarations.in_tpt_mode,
      out_tpt_mode: dbRegulatoryDeclarations.out_tpt_mode,
      ...model,
    });
 
    if (model.dec_stmt_ind) {
      model.confirmed_by = this.current_user.id;
      model.confirmed_date = new Date();
    } else {
      model.confirmed_by = undefined;
      model.confirmed_date = undefined;
    }
 
    const tx = await this.regulatoryCargosRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
 
      /**
       * Improvement: https://dirox.easyredmine.com/issues/10355
       * when a transport mode is updated the related record on transport table should be deleted
       *    IF in_tpt_mode value is updated: DELETE related regulatory_transports record (same declaration_id) with type=INTRANS
       *    IF out_tpt_mode value is updated: DELETE related regulatory_transports record (same declaration_id) with type=OUTTRANS
       */
      const dbDeclaration = await this.regulatoryDeclarationsRepo.findById(id);
      if (dbDeclaration?.id) {
        if (dbDeclaration.in_tpt_mode !== model.in_tpt_mode) {
          await this.regulatoryTransportsRepo.deleteAll({ declaration_id: id, type: TransportType.IN_TRANS });
        }
 
        if (dbDeclaration.out_tpt_mode !== model.out_tpt_mode) {
          await this.regulatoryTransportsRepo.deleteAll({ declaration_id: id, type: TransportType.OUT_TRANS });
        }
      }
      await this.regulatoryDeclarationsRepo.updateById(id, model);
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when update regulatory declaration!');
    }
    return dbRegulatoryDeclarations;
  }
 
  private async ensureDeclarationCanBeUpdated(id: number, options: Options = {}): Promise<RegulatoryDeclarationsWithRelations> {
    const dbRegulatoryDeclarations = await this.regulatoryDeclarationsRepo.findOne({
      where: { company_id: this.current_user.company_id, id }
    }, options);
    if (!dbRegulatoryDeclarations) {
      throw new EntityNotFoundError(this.regulatoryDeclarationsRepo.entityClass, id);
    }
 
    if (dbRegulatoryDeclarations.status === Status.RegulatoryDeclaration.ForValidation) {
      throw new HttpErrors.BadRequest("This declaration is submitted. You can not submit it again!");
    }
 
    if (dbRegulatoryDeclarations.status === Status.RegulatoryDeclaration.Accepted) {
      throw new HttpErrors.BadRequest("This declaration is accepted. You can not submit it again!");
    }
 
    if (dbRegulatoryDeclarations.status === Status.RegulatoryDeclaration.Rejected) {
      throw new HttpErrors.BadRequest("This declaration is rejected. You can not submit it again!");
    }
 
    return dbRegulatoryDeclarations;
  }
 
  public ensureRightAccessRecord(): void {
    this.filter_builder.impose({
      company_id: this.current_user.company_id,
    });
  }
 
  async buildSearchQuery(q?: string) {
    if (!q) { return; }
 
    const ilikeValue = this.buildILikeValue(q);
    const flowIds = await this.getFlowIdsByQuery(ilikeValue);
    const companyIds = await this.getCompaniesIdByQuery(ilikeValue);
    this.filter_builder.impose({
      or: [
        {
          flow_id: { inq: flowIds },
        },
        {
          company_id: { inq: companyIds }
        }
      ],
    });
  }
 
  async find(options?: Options): Promise<BaseResponses<RegulatoryDeclarationsView>> {
    if (options?.is_private) {
      this.filter_builder.fields({ company_id: true, company_regulatory_id: true });
      this.filter_builder.include({
        relation: 'company',
        scope: { fields: { id: true, identifier: true, name: true }, },
      });
      this.filter_builder.include({
        relation: 'regulatory',
        scope: { fields: { id: true, uen: true }, },
      });
    }
 
    const filter_builder = new FilterBuilder<RegulatoryDeclarationsView>();
    filter_builder.filter = this.filter_builder.filter;
    filter_builder.fields({
      id: true,
      car_type: true,
      dec_type: true,
      flow_id: true,
      flow_name: true,
      company_name: true,
      company_regulatory_uen: true,
      transaction_id: true,
      transaction_date: true,
      submitted_date: true,
      status: true,
      status_name: true
    });
 
    return this.regulatoryDeclarationsViewRepo.fillRelation(filter_builder);
  }
 
  async upsertParties(declarationId: number, model: AnyObject) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const schema = getSchemaByKey(declarationPartySchema, `addParty${dbRegulatoryDeclarations.car_type}Schema` as never);
    await validateValueAgainstSchema(model, schema);
    const tx = await this.regulatoryCargosRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const pTasks = Object.entries(model).map(([key, value]) => {
        const type = PartyType[StringUtils.pascalCase(key) as never];
        return this.regulatoryPartiesRepo.upsertWithWhere({
          type,
          declaration_id: declarationId,
        }, {
          ...value,
          type,
          declaration_id: declarationId,
        });
      });
      await Promise.all(pTasks);
      await this.regulatoryPartiesRepo.deleteAll({
        declaration_id: dbRegulatoryDeclarations.id,
        type: { nin: Object.keys(model).map(key => PartyType[StringUtils.pascalCase(key) as never]) }
      })
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create party!');
    }
  }
 
  async upsertCargo(declarationId: number, model: Partial<RegulatoryCargos>) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const schema = getSchemaByKey(declarationCargoSchema, `addCargo${dbRegulatoryDeclarations.car_type}Schema` as never);
    await validateValueAgainstSchema(model, schema);
 
    const tx = await this.regulatoryCargosRepo.beginTransaction(
      IsolationLevel.SERIALIZABLE,
    );
    try {
      const { containers = [], ...restValue } = model;
      const dbRegulatoryCargos = await this.regulatoryCargosRepo.upsertWithWhere({
        declaration_id: dbRegulatoryDeclarations.id,
      }, {
        declaration_id: dbRegulatoryDeclarations.id,
        ...restValue,
      }, { transaction: tx, returnInstanceAfterUpdate: true });
 
      if (dbRegulatoryCargos) {
        const pTasks: Promise<AnyObject>[] = containers.map(({ id, ...restValueContainer }, idx) => {
          if (id) {
            // update container already exists
            return (async () => {
              const { count } = await this.regulatoryContainersRepo.updateAll({
                ...restValueContainer,
                seq_no: idx + 1,
                declaration_cargo_id: dbRegulatoryCargos.id,
              }, {
                declaration_cargo_id: dbRegulatoryCargos.id,
                id,
              }, { transaction: tx });
 
              return { id, isNotUpdated: !count };
            })();
          } else {
            // create new container records
            return this.regulatoryContainersRepo.create({
              ...restValueContainer,
              seq_no: idx + 1,
              declaration_cargo_id: dbRegulatoryCargos.id,
            }, { transaction: tx });
          }
        });
        const resl = await Promise.all(pTasks);
        const notFoundIds = resl.filter(({ isNotUpdated }) => isNotUpdated);
        if (notFoundIds?.length) {
          throw new EntityNotFoundError(this.regulatoryContainersRepo.entityClass, notFoundIds.map(({ id }) => id));
        }
        await this.regulatoryContainersRepo.deleteAll({
          declaration_cargo_id: dbRegulatoryCargos.id,
          id: { nin: resl.map((c) => c?.id) as number[] }
        }, { transaction: tx });
      }
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      console.error(error);
      throw new HttpErrors.InternalServerError('An error occurred when create cargo!');
    }
  }
 
  async deleteByIdOrIdentifier(id: number | string) {
    this.addWhereIdOrIdentifier(id);
    const dbRegulatoryDeclarations = await this.regulatoryDeclarationsRepo.findOne(this.filter_builder.build());
 
    if (!dbRegulatoryDeclarations) {
      throw new EntityNotFoundError(this.regulatoryDeclarationsRepo.entityClass, id);
    }
 
    if (dbRegulatoryDeclarations.status !== Status.RegulatoryDeclaration.Draft) {
      throw new HttpErrors.BadRequest(`Only record of status "Draft" can be deleted.`);
    }
 
    await this.regulatoryDeclarationsRepo.deleteById(dbRegulatoryDeclarations.id);
    // return to write logs
    return dbRegulatoryDeclarations;
  }
 
  async getByIdOrIdentifier(id: string | number, options?: Options): Promise<RegulatoryDeclarationsWithRelations> {
    this.addWhereIdOrIdentifier(id);
    this.filter_builder.include({
      relation: 'company',
      scope: { fields: { id: true, name: true }, },
    });
    this.filter_builder.include({
      relation: 'regulatory',
      scope: { fields: { id: true, uen: true, tradeweb_id: true }, },
    });
    this.filter_builder.include({
      relation: 'creator',
      scope: { fields: { id: true, name: true, contact_number: true }, },
    });
    this.filter_builder.include({
      relation: 'parties',
    });
    this.filter_builder.include({
      relation: 'cargo',
      scope: {
        fields: {
          id: true, declaration_id: true, release_loc: true, receipt_loc: true, storage_loc: true, blanket_start_date: true
        },
        include: [
          {
            relation: 'containers',
            scope: { order: ['seq_no ASC'], },
          }
        ]
      },
    });
    this.filter_builder.include({
      relation: 'documents',
    });
    this.filter_builder.include({
      relation: 'items',
    });
    this.filter_builder.include({
      relation: 'transports',
    });
    this.filter_builder.include({
      relation: 'customsProcedureCodes',
    });
 
    const dbRegulatoryDeclarations = await this.regulatoryDeclarationsRepo.findOne(this.filter_builder.build());
    if (!dbRegulatoryDeclarations) {
      throw new EntityNotFoundError(this.regulatoryDeclarationsRepo.entityClass, id);
    }
 
    return dbRegulatoryDeclarations;
  }
 
  async upsertTransport(declarationId: number, model: Partial<RegulatoryTransports>) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    let transportModeName = '';
    let transportType;
    let carType: string = dbRegulatoryDeclarations.car_type;
    let tptMode;
    if ('discharge_port' in model) {
      transportType = TransportType.OUT_TRANS;
      tptMode = dbRegulatoryDeclarations.out_tpt_mode;
    } else {
      transportType = TransportType.IN_TRANS;
      tptMode = dbRegulatoryDeclarations.in_tpt_mode;
    }
    carType = <string>transportType;
    transportModeName = getEnumKeyByEnumValue(TransportMode, String(tptMode));
 
    try {
      const schema = getSchemaByKey(
        declarationTransportSchema,
        `addTransport${carType}${transportModeName}Schema` as never
      );
      await validateValueAgainstSchema(model, schema, {}, { removeAdditional: true });
    } catch (error) {
      if (error instanceof ValidationError && error.code === 'SchemaNotFound') {
        const finalError = new HttpErrors.BadRequest('The current transport status is out of date.');
        finalError.code = 'SCHEMA_NOT_FOUND';
        throw finalError;
      }
      throw error;
    }
 
    await this.regulatoryTransportsRepo.upsertWithWhere({
      declaration_id: dbRegulatoryDeclarations.id,
      type: transportType
    }, {
      ...model,
      declaration_id: dbRegulatoryDeclarations.id,
      type: transportType,
    });
  }
 
  async upsertDocument(declarationId: number, documents: RegulatoryDocuments[]) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    if (!dbRegulatoryDeclarations.has_ref_docs) {
      throw new HttpErrors.BadRequest("Do not allow uploading documents!");
    }
 
    const tx = await this.regulatoryDocumentsRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const pTasks: Promise<AnyObject>[] = documents.map(async ({ id, file_name, ...restValue }, idx) => {
        const headResult = await this.ensureS3ObjectExists(restValue.s3_uri);
        if (!headResult.ContentType || !MIME_TYPES_ALLOWED.includes(headResult.ContentType)) {
          const error = new HttpErrors.BadRequest('The content-type is not allowed');
          error.details = {
            contentTypeAllowed: MIME_TYPES_ALLOWED
          };
          throw error;
        }
 
        if (id) {
          // update document already exists
          const { count } = await this.regulatoryDocumentsRepo.updateAll({
            ...restValue,
            file_name: file_name.toUpperCase(),
            seq_no: idx + 1,
            size_in_kilobyte: bytesToKilobyte(headResult?.ContentLength),
            declaration_id: dbRegulatoryDeclarations.id,
          }, {
            declaration_id: dbRegulatoryDeclarations.id,
            id,
          });
 
          return { id, isNotUpdated: !count };
        } else {
          // create new container records
          return this.regulatoryDocumentsRepo.create({
            ...restValue,
            seq_no: idx + 1,
            file_name: file_name.toUpperCase(),
            size_in_kilobyte: bytesToKilobyte(headResult?.ContentLength),
            declaration_id: dbRegulatoryDeclarations.id,
          });
        }
      });
      const resl = await Promise.all(pTasks);
      const notFoundIds = resl.filter(({ isNotUpdated }) => isNotUpdated);
      if (notFoundIds?.length) {
        throw new EntityNotFoundError(this.regulatoryDocumentsRepo.entityClass, notFoundIds.map(({ id }) => id));
      }
 
      const deleteWhere: Where<RegulatoryDocuments> = {
        declaration_id: dbRegulatoryDeclarations.id,
        id: { nin: resl.map((c) => c?.id) as number[] }
      };
      // delete all documents
      if (!documents?.length) {
        delete deleteWhere.id;
      }
      await this.regulatoryDocumentsRepo.deleteAll(deleteWhere);
 
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create documents!');
    }
  }
 
  async upsertCodes(declarationId: number, seq_no: number, { id, ...restValue }: Partial<RegulatoryCustomsProcedureCodes>, options: Options) {
    if (id) {
      const { count } = await this.regulatoryCustomsProcedureCodesRepo.updateAll({
        ...restValue,
        seq_no,
        declaration_id: declarationId,
      }, {
        declaration_id: declarationId,
        id,
      }, options);
      return { id, isNotUpdated: !count };
    } else {
      return this.regulatoryCustomsProcedureCodesRepo.create({
        ...restValue,
        seq_no,
        declaration_id: declarationId,
      }, options);
    }
  }
 
  async upsertCustomsProcedureCodes(declarationId: number, customsProcedureCodes: declarationCPCSchema.AddRegulatoryDeclarationsCPC[]) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const tx = await this.regulatoryCustomsProcedureCodesRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const pTasks: Promise<AnyObject>[] = []
      customsProcedureCodes.forEach(({ group_no, custom_proc_code, codes }) => {
        codes.map((code, idx) => {
          pTasks.push(this.upsertCodes(dbRegulatoryDeclarations.id, idx + 1, { ...code, group_no, custom_proc_code }, {
            transaction: tx
          }));
        });
      });
 
      const resl = await Promise.all(pTasks);
      const notFoundIds = resl.filter(({ isNotUpdated }) => isNotUpdated);
      if (notFoundIds?.length) {
        throw new EntityNotFoundError(this.regulatoryCustomsProcedureCodesRepo.entityClass, notFoundIds.map(({ id }) => id));
      }
      await this.regulatoryCustomsProcedureCodesRepo.deleteAll({
        declaration_id: dbRegulatoryDeclarations.id,
        id: { nin: resl.map((c) => c?.id) as number[] }
      });
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create customs procedure codes!');
    }
  }
 
  async createInvoices(declarationId: number, invoice: RegulatoryInvoices) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    if (![CarType.INPDEC, CarType.IPTDEC].includes(dbRegulatoryDeclarations.car_type)) {
      throw new HttpErrors.BadRequest(`The declaration with car_type(${dbRegulatoryDeclarations.car_type}) not supported invoices`);
    }
 
    const tx = await this.regulatoryInvoicesRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const { count: totalInvoices } = await this.regulatoryInvoicesRepo.count(
        { declaration_id: dbRegulatoryDeclarations.id },
        { transaction: tx }
      );
      if (totalInvoices >= MAXIMUM_INVOICE_ALLOWED) {
        throw new HttpErrors.BadRequest(`Maximum invoice allowed: ${MAXIMUM_INVOICE_ALLOWED}`);
      }
      const lastInvoice = await this.regulatoryInvoicesRepo.findOne(
        {
          where: { declaration_id: dbRegulatoryDeclarations.id },
          order: ['seq_no DESC']
        },
        { transaction: tx }
      );
      const newInvoice = await this.regulatoryInvoicesRepo.create({
        ...invoice,
        seq_no: (lastInvoice?.seq_no ?? 0) + 1,
        declaration_id: dbRegulatoryDeclarations.id,
      });
      await tx.commit();
      return newInvoice;
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create invoices!');
    }
  }
 
  async updateInvoices(declarationId: number, invoiceId: number, invoice: RegulatoryInvoices) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    if (![CarType.INPDEC, CarType.IPTDEC].includes(dbRegulatoryDeclarations.car_type)) {
      throw new HttpErrors.BadRequest(`The declaration with car_type(${dbRegulatoryDeclarations.car_type}) not supported invoices`);
    }
    const tx = await this.regulatoryInvoicesRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      // Set value to undefined to remove it in the database when client remove the invoice data.
      const INVOICE_KEYS = ["sup_mfr", "tot_inv_amt", "frc_charge", "ins_charge", "oth_charge"];
      INVOICE_KEYS.forEach((key) => {
        if (!(key in invoice)) {
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (invoice as any)[key] = undefined;
        }
      });
      const { count } = await this.regulatoryInvoicesRepo.updateAll({
        ...invoice,
      }, {
        declaration_id: dbRegulatoryDeclarations.id,
        id: invoiceId,
      });
 
      if (!count) {
        throw new EntityNotFoundError(this.regulatoryInvoicesRepo.entityClass, invoiceId);
      }
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create invoices!');
    }
  }
 
  async deleteInvoices(declarationId: number, invoiceId: number) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const tx = await this.regulatoryInvoicesRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const { count } = await this.regulatoryInvoicesRepo.deleteAll({
        declaration_id: dbRegulatoryDeclarations.id,
        id: invoiceId,
      });
 
      if (!count) {
        throw new EntityNotFoundError(this.regulatoryInvoicesRepo.entityClass, invoiceId);
      }
      await tx.commit();
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create invoices!');
    }
  }
 
  async findInvoices(declarationId: number, invoiceFilter: FilterBuilder<RegulatoryInvoices>) {
    this.filter_builder.where({ id: declarationId });
    const dbRegulatoryDeclarations = await this.regulatoryDeclarationsRepo.findOne(this.filter_builder.build());
    if (!dbRegulatoryDeclarations) {
      throw new EntityNotFoundError(this.regulatoryDeclarationsRepo.entityClass, declarationId);
    }
 
    invoiceFilter.impose({
      declaration_id: dbRegulatoryDeclarations.id,
    });
 
    invoiceFilter.order(['seq_no ASC']);
    return this.regulatoryInvoicesRepo.findWithPaging(invoiceFilter.build());
  }
 
  async createItems(declarationId: number, item: RegulatoryItemsWithRelations) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const schema = getSchemaByKey(declarationItemsSchema, `addItem${dbRegulatoryDeclarations.car_type}Schema` as never);
    await validateValueAgainstSchema(item, schema);
    const tx = await this.regulatoryItemsRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const { casc_products, ...restValue } = item;
      const lastItem = await this.regulatoryItemsRepo.findOne(
        {
          where: { declaration_id: dbRegulatoryDeclarations.id },
          order: ['seq_no DESC']
        },
        { transaction: tx }
      );
      const newItems = await this.regulatoryItemsRepo.create({
        ...restValue,
        seq_no: (lastItem?.seq_no ?? 0) + 1,
        declaration_id: dbRegulatoryDeclarations.id,
      });
 
      if (casc_products?.length) {
        const newCascProducts = casc_products.map(({ add_casc_code, ...cascProduct }, index) => (
          {
            ...cascProduct,
            seq_no: index + 1,
            declaration_id: dbRegulatoryDeclarations.id,
            item_id: newItems.id,
            add_casc_code: { value: add_casc_code },
          }
        ));
        await this.regulatoryCascProductsRepo.createAll(newCascProducts);
      }
      await tx.commit();
      return newItems;
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create items!');
    }
  }
 
  async updateItems(declarationId: number, itemId: number, item: RegulatoryItemsWithRelations) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const schema = getSchemaByKey(declarationItemsSchema, `addItem${dbRegulatoryDeclarations.car_type}Schema` as never);
    await validateValueAgainstSchema(item, schema);
    const { count } = await this.regulatoryItemsRepo.updateAll({
      ...item,
      declaration_id: dbRegulatoryDeclarations.id,
    }, {
      declaration_id: dbRegulatoryDeclarations.id,
      id: itemId,
    });
    if (!count) {
      throw new EntityNotFoundError(this.regulatoryItemsRepo.entityClass, itemId);
    }
  }
 
  async deleteItems(declarationId: number, itemId: number) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const { count } = await this.regulatoryItemsRepo.deleteAll({
      declaration_id: dbRegulatoryDeclarations.id,
      id: itemId,
    });
 
    if (!count) {
      throw new EntityNotFoundError(this.regulatoryItemsRepo.entityClass, itemId);
    }
  }
 
  async createCascProducts(declarationId: number, cascProducts: RegulatoryCascProducts) {
    const tx = await this.regulatoryItemsRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      const [dbRegulatoryDeclarations, dbItems, dbCascProducts] = await Promise.all([
        this.ensureDeclarationCanBeUpdated(declarationId),
        this.regulatoryItemsRepo.findOne({ where: { declaration_id: declarationId, id: cascProducts.item_id } }),
        this.regulatoryCascProductsRepo.find(
          {
            where: { declaration_id: declarationId, item_id: cascProducts.item_id },
            order: ['seq_no DESC']
          },
          { transaction: tx }
        )
      ]);
 
      if (!dbItems) {
        throw new EntityNotFoundError(this.regulatoryItemsRepo.entityClass, cascProducts.item_id);
      }
 
      if (dbCascProducts?.length >= MAXIMUM_CASC_PRODUCTS_ALLOWED) {
        throw new HttpErrors.BadRequest(`Maximum items of casc products are reached: ${MAXIMUM_CASC_PRODUCTS_ALLOWED}`);
      }
      const lastCascProduct = dbCascProducts.shift();
      const newCascProduct = await this.regulatoryCascProductsRepo.create({
        ...cascProducts,
        declaration_id: dbRegulatoryDeclarations.id,
        add_casc_code: { value: cascProducts.add_casc_code },
        seq_no: (lastCascProduct?.seq_no ?? 0) + 1,
      });
      await tx.commit();
      return newCascProduct;
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create invoices!');
    }
  }
 
  async updateCascProducts(declarationId: number, cascProductId: number, cascProducts: RegulatoryCascProducts) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const { count } = await this.regulatoryCascProductsRepo.updateAll({
      ...cascProducts,
      add_casc_code: { value: cascProducts.add_casc_code },
      declaration_id: dbRegulatoryDeclarations.id,
    }, {
      declaration_id: dbRegulatoryDeclarations.id,
      id: cascProductId,
    });
 
    if (!count) {
      throw new EntityNotFoundError(this.regulatoryCascProductsRepo.entityClass, cascProductId);
    }
  }
 
  async deleteCascProducts(declarationId: number, cascProductId: number) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const { count } = await this.regulatoryCascProductsRepo.deleteAll({
      declaration_id: dbRegulatoryDeclarations.id,
      id: cascProductId,
    });
 
    if (!count) {
      throw new EntityNotFoundError(this.regulatoryCascProductsRepo.entityClass, cascProductId);
    }
  }
 
  async upsertCascProducts(itemId: number, cascProducts: RegulatoryCascProducts[], options: Options = {}) {
    if (!cascProducts || cascProducts.length === 0) {
      return [];
    }
    const pTasks: Promise<AnyObject>[] = cascProducts.map(async ({ id, ...restValue }, idx) => {
      if (id) {
        const { count } = await this.regulatoryCascProductsRepo.updateAll({
          ...restValue,
          add_casc_code: { value: restValue.add_casc_code },
          seq_no: idx + 1,
          item_id: itemId,
        }, {
          item_id: itemId,
          id,
        }, options);
        return { id, isNotUpdated: !count };
      } else {
        return this.regulatoryCascProductsRepo.create({
          ...restValue,
          add_casc_code: { value: restValue.add_casc_code },
          seq_no: idx + 1,
          item_id: itemId,
        }, options);
      }
    });
    const resl = await Promise.all(pTasks);
    const notFoundIds = resl.filter(({ isNotUpdated }) => isNotUpdated);
    if (notFoundIds?.length) {
      throw new EntityNotFoundError(this.regulatoryCascProductsRepo.entityClass, notFoundIds.map(({ id }) => id));
    }
    await this.regulatoryCascProductsRepo.deleteAll({ item_id: itemId, id: { nin: resl.map((c) => c?.id) as number[] } }, options);
 
    return resl;
  }
 
  async upsertItems(declarationId: number, items: RegulatoryItemsWithRelations) {
    const dbRegulatoryDeclarations = await this.ensureDeclarationCanBeUpdated(declarationId);
    const schema = getSchemaByKey(declarationItemsSchema, `addItem${dbRegulatoryDeclarations.car_type}Schema` as never);
    await validateValueAgainstSchema(items, schema);
    const { id, casc_products, ...restValue } = items;
    const tx = await this.regulatoryItemsRepo.beginTransaction(IsolationLevel.SERIALIZABLE);
    try {
      let itemId = id;
      if (id) {
        const { count } = await this.regulatoryItemsRepo.updateAll({
          ...restValue,
          declaration_id: dbRegulatoryDeclarations.id,
        }, {
          declaration_id: dbRegulatoryDeclarations.id,
          id,
        });
        if (!count) {
          throw new EntityNotFoundError(this.regulatoryItemsRepo.entityClass, id);
        }
        await this.upsertCascProducts(id, casc_products);
      } else {
 
        const { count: totalItems } = await this.regulatoryItemsRepo.count(
          { declaration_id: dbRegulatoryDeclarations.id },
          { transaction: tx }
        );
        if (totalItems >= MAXIMUM_ITEMS_ALLOWED) {
          throw new HttpErrors.BadRequest(`Maximum items allowed: ${MAXIMUM_ITEMS_ALLOWED}`);
        }
        const lastItem = await this.regulatoryItemsRepo.findOne(
          {
            where: { declaration_id: dbRegulatoryDeclarations.id },
            order: ['seq_no DESC']
          },
          { transaction: tx }
        );
        const newItems = await this.regulatoryItemsRepo.create({
          ...restValue,
          seq_no: (lastItem?.seq_no ?? 0) + 1,
          declaration_id: dbRegulatoryDeclarations.id,
        });
        await this.upsertCascProducts(newItems.id, casc_products);
        itemId = newItems.id;
      }
      await tx.commit();
      return { id: itemId }
    } catch (error) {
      await tx.rollback();
      if (error instanceof EntityNotFoundError || error instanceof HttpErrors.BadRequest || error instanceof HttpErrors.NotFound) {
        throw error;
      }
      throw new HttpErrors.InternalServerError('An error occurred when create items!');
    }
  }
 
  async findItems(declarationId: number, itemFilter: FilterBuilder<RegulatoryItems>) {
    this.filter_builder.where({ id: declarationId });
    const dbRegulatoryDeclarations = await this.regulatoryDeclarationsRepo.findOne(this.filter_builder.build());
    if (!dbRegulatoryDeclarations) {
      throw new EntityNotFoundError(this.regulatoryDeclarationsRepo.entityClass, declarationId);
    }
 
    itemFilter.impose({
      declaration_id: dbRegulatoryDeclarations.id,
    });
    itemFilter.include({
      relation: 'cascProducts',
    });
    itemFilter.order(['seq_no ASC']);
    return this.regulatoryItemsRepo.findWithPaging(itemFilter.build());
  }
 
  private prepareHeader(declaration: RegulatoryDeclarationsWithRelations) {
    const { id, regulatory, remarks, customsProcedureCodes, calista_job_no } = declaration;
    const [date, seq_no] = extractJobNo(calista_job_no);
    return {
      msg_ref_no: id.toString(),
      unique_ref_no: {
        cr_uei_no: regulatory?.uen,
        date,
        seq_no,
      },
      declarant_id: regulatory?.tradeweb_id,
      car_type: declaration.car_type,
      dec_type: declaration.dec_type,
      dec_stmt_ind: declaration.dec_stmt_ind,
      remarks: remarks.map((remark) => ({ line: [{ line: remark }] })),
      bg_ind: declaration.bg_ind,
      custom_proc_code_info: customsProcedureCodes?.map(({ custom_proc_code, process_code1, process_code2, process_code3 }) => ({
        custom_proc_code,
        cpc_process_code: {
          process_code1,
          process_code2,
          process_code3,
        }
      })),
    }
  }
 
  private prepareCargo(declaration: RegulatoryDeclarationsWithRelations) {
    const { cargo } = declaration;
    return {
      pack_type: declaration.pack_type,
      release_loc: cargo?.release_loc,
      receipt_loc: cargo?.receipt_loc,
      storage_loc: cargo?.storage_loc,
      container: cargo?.containers?.map(({ ctn_no, ctn_type_size, ctn_wt_value, ctn_seal_no }, idx) => ({
        seq_no: idx + 1,
        ctn_no,
        ctn_type_size,
        ctn_wt_value,
        ctn_seal_no
      })),
      supply_ind: declaration.supply_ind,
      blanket_start_date: DateUtils.format(cargo?.blanket_start_date),
    }
  }
 
  private prepareTransport(declaration: RegulatoryDeclarationsWithRelations) {
    const transport: AnyObject = toTransportObject(declaration.transports);
    const sendingFields = ['cvy_ref_no', 'tpt_id', 'master_ship_doc', 'loading_port', 'add_vess_info'];
    return !isEmpty(transport) ? {
      in_tpt: {
        tpt_mode: declaration.in_tpt_mode,
        arrival_date: DateUtils.format(transport['in_tpt']?.arrival_date),
        ...pick(transport['in_tpt'], sendingFields)
      },
      out_tpt: {
        tpt_mode: declaration.out_tpt_mode,
        dept_date: DateUtils.format(transport['out_tpt']?.dept_date),
        discharge_port: transport['out_tpt']?.discharge_port,
        cty_destn: transport['out_tpt']?.cty_destn,
        ...pick(transport['out_tpt'], sendingFields)
      },
    } : {};
  }
 
  private prepareParty(declaration: RegulatoryDeclarationsWithRelations) {
    const { regulatory, creator } = declaration
    const {
      declaring_agent, freight_forwarder, in_carrier_agent, importer, out_carrier_agent,
      exporter, consignee, claimant, end_user, manufacturer
    }: AnyObject = toPartyObject(declaration.parties);
    const sendingFields = ['city', 'sbt_code', 'sbt_name', 'pst_code', 'cty_code'];
    return {
      declarant: {
        person_code: regulatory?.tradeweb_id,
        person_name: creator?.name,
        person_phone: creator?.contact_number?.replace('+', '') // https://dirox.easyredmine.com/issues/7559
      },
      declaring_agent: declaring_agent && {
        cr_uei_no: declaring_agent.cr_uei_no,
        name: convertName(declaring_agent)
      },
      freight_forwarder: freight_forwarder && {
        cr_uei_no: freight_forwarder.cr_uei_no,
        name: convertName(freight_forwarder),
      },
      in_carrier_agent: in_carrier_agent && {
        cr_uei_no: in_carrier_agent.cr_uei_no,
        name: convertName(in_carrier_agent),
      },
      importer: importer && {
        cr_uei_no: importer.cr_uei_no,
        name: convertName(importer),
      },
      out_carrier_agent: out_carrier_agent && {
        cr_uei_no: out_carrier_agent.cr_uei_no,
        name: convertName(out_carrier_agent),
      },
      exporter: exporter && {
        ...pick(exporter, sendingFields),
        cr_uei_no: exporter.cr_uei_no,
        name: convertName(exporter),
        address: convertAddress(exporter)
      },
      consignee: consignee && {
        name: convertName(consignee),
        address: convertAddress(consignee),
        ...pick(consignee, sendingFields)
      },
      claimant: claimant && {
        cr_uei_no: claimant.cr_uei_no,
        name: convertName(claimant),
        claimant_detail: claimant?.extra_info,
      },
      end_user: end_user && {
        name: convertName(end_user),
        address: convertAddress(end_user),
        ...pick(end_user, sendingFields)
      },
      manufacturer: manufacturer && {
        cr_uei_no: manufacturer.cr_uei_no,
        name: convertName(manufacturer),
        address: convertAddress(consignee),
        ...pick(manufacturer, sendingFields)
      },
    }
  }
 
  private prepareLicence(declaration: RegulatoryDeclarationsWithRelations) {
    const { licences } = declaration;
    return {
      lic_no: licences?.map((licence) => ({ lic_no: licence }))
    };
  }
 
  private prepareSupportDoc(declaration: RegulatoryDeclarationsWithRelations) {
    const { documents } = declaration;
    return {
      document: documents?.map(({ type, file_name }) => ({ doc_id: type, file_name: file_name.toUpperCase() }))
    }
  }
 
  private async prepareInvoice(declaration: RegulatoryDeclarationsWithRelations) {
    const sendingFields = ['inv_no', 'inv_term_type', 'tot_inv_amt', 'frc_charge', 'ins_charge', 'oth_charge'];
    const invoices = await this.regulatoryInvoicesRepo.find({
      where: {
        declaration_id: declaration.id,
      },
      order: ['seq_no ASC']
    });
    return invoices.map((invoice) => ({
      ...pick(invoice, sendingFields),
      inv_date: DateUtils.format(invoice.inv_date),
      sup_mfr: {
        person_code: invoice.sup_mfr?.cr_uei_no,
        person_name: convertName(invoice.sup_mfr, 'person_name'),
      },
    }));
  }
 
  private async prepareItem(declaration: RegulatoryDeclarationsWithRelations) {
    const sendingFields = [
      'hs_code', 'item_desc', 'cty_origin', 'brand', 'model', 'dangerous_goods_ind', 'curr_lot_no', 'prev_lot_no',
      'marking', 'in_house_ship_doc', 'out_house_ship_doc', 'item_inv_no', 'out_pack_qty', 'in_pack_qty', 'inner_pack_qty',
      'inmost_pack_qty'
    ];
    const items = await this.regulatoryItemsRepo.find({
      where: {
        declaration_id: declaration.id,
      },
      include: [{
        relation: 'cascProducts',
      }],
      order: ['seq_no ASC']
    });
 
    return items.map((item, idx) => ({
      seq_no: idx + 1,
      ...pick(item, sendingFields),
      item_qty: pick(item, ['hs_qty', 'tot_dut_qty', 'dut_qty', 'alcohol_percent']),
      transaction_value: pick(item, ['cif_fob_amt', 'cif_fob_fc', 'last_selling_price', 'unit_price', 'optional_item_charge']),
      item_cert: {
        ...pick(item.item_cert, ['cert_qty', 'item_value', 'text_code', 'text_qty', 'inv_no', 'hs_code', 'content_percent']),
        cert_desc: item.item_cert?.cert_desc?.map((desc: string) => ({ line: [{ line: desc }] })),
        origin_criterion: item.item_cert?.origin_criterion?.map((origin_criterion: string) => ({ origin_criterion })),
      },
      casc_product: item.cascProducts?.map((cascProduct, idx1) => ({
        prod_qty: cascProduct.prod_qty,
        prod_qty_uom: cascProduct.prod_qty_uom,
        prod_code: cascProduct.prod_code,
        add_casc_code: cascProduct.add_casc_code.value,
        end_use_desc: cascProduct.end_use_desc,
      })),
      shipping_marks: item.shipping_marks?.map((marks) => ({ marks: [{ marks }] })),
      duty_tax: {
        pref_code: item.pref_code,
        gst_rate: item.gst_rate,
        gst_amt: item.gst_amt,
        excise_duty: item.excise_duty,
        customs_duty: item.customs_duty,
        other_tax: item.other_tax,
      }
    }));
  }
 
  private prepareSummary(declaration: RegulatoryDeclarationsWithRelations) {
    return {
      tot_item: declaration.tot_item,
      tot_cif_fob_amt: declaration.tot_cif_fob_amt,
      tot_out_pack: declaration.tot_out_pack,
      tot_gross_wt: declaration.tot_gross_wt,
      tot_duty_tax: declaration.tot_duty_tax
    }
  }
 
  async prepareDeclaration(declarationId: number) {
    const dbRegulatoryDeclarations = await this.getByIdOrIdentifier(declarationId);
    if (dbRegulatoryDeclarations.status === Status.RegulatoryDeclaration.ForValidation) {
      throw new HttpErrors.BadRequest("This declaration is submitted. You can not submit it again!");
    }
 
    if (dbRegulatoryDeclarations.status === Status.RegulatoryDeclaration.Accepted) {
      throw new HttpErrors.BadRequest("This declaration is accepted. You can not submit it again!");
    }
 
    if (dbRegulatoryDeclarations.status === Status.RegulatoryDeclaration.Rejected) {
      throw new HttpErrors.BadRequest("This declaration is rejected. You can not submit it again!");
    }
 
    if (dbRegulatoryDeclarations.status === Status.RegulatoryDeclaration.ForValidationMissingInfo && !dbRegulatoryDeclarations.calista_job_no) {
      throw new HttpErrors.BadRequest('Missing calista_job_no');
    }
 
    /**
     * As described in issue https://easy.dirox.net/issues/10846
     * We only allow a flow to be attached multiplte time before its accepted / for validation (mssing info)
     */
    if (dbRegulatoryDeclarations.flow_id) await this.validateFlow(dbRegulatoryDeclarations.flow_id);
 
    dbRegulatoryDeclarations.submitted_date = new Date();
    const declaration = {
      message_version: '',
      sender_id: dbRegulatoryDeclarations.regulatory?.tradeweb_id,
      recipient_id: '',
      message: {
        header: this.prepareHeader(dbRegulatoryDeclarations),
        cargo: this.prepareCargo(dbRegulatoryDeclarations),
        transport: this.prepareTransport(dbRegulatoryDeclarations),
        party: this.prepareParty(dbRegulatoryDeclarations),
        licence: this.prepareLicence(dbRegulatoryDeclarations),
        support_doc: this.prepareSupportDoc(dbRegulatoryDeclarations),
        invoice: await this.prepareInvoice(dbRegulatoryDeclarations),
        item: await this.prepareItem(dbRegulatoryDeclarations),
        summary: this.prepareSummary(dbRegulatoryDeclarations),
      }
    };
    const finalSchema = this.buildFinalSchema(dbRegulatoryDeclarations);
    await validateValueAgainstSchema(cleanObject(declaration), finalSchema as SchemaObject);
    const updatedData: Partial<RegulatoryDeclarations> = {
      submitted_date: dbRegulatoryDeclarations.submitted_date,
    };
 
    if (!dbRegulatoryDeclarations.dec_stmt_ind) {
      updatedData.confirmed_by = this.current_user.id;
      updatedData.confirmed_date = new Date();
      updatedData.dec_stmt_ind = true;
    }
    await this.regulatoryDeclarationsRepo.updateById(declarationId, updatedData);
    return declaration;
  }
 
  async validateFlow(flowId: number): Promise<void> {
    const existedDbFlow = await this.flowJourneyService.getJourneyDetailsByFlowId(flowId);
    const unAllowedRegulatoryDecStatusList = [Status.RegulatoryDeclaration.ForValidation, Status.RegulatoryDeclaration.ForValidationMissingInfo, Status.RegulatoryDeclaration.Accepted];
    if (!existedDbFlow?.id)  throw new HttpErrors.BadRequest(`Flow ${flowId} not found`);
    const existedRegulatoryUsingThisFlow = await this.regulatoryDeclarationsRepo.findOne({where: {
      flow_id: flowId,
      status: {
        inq: unAllowedRegulatoryDecStatusList
      }
    }});
    if (existedRegulatoryUsingThisFlow?.id) throw new HttpErrors.BadRequest(`Flow "${existedDbFlow.name}" is already in used by another regulatory declartion`);
  }
 
  async downloadBase64DocumentsByDeclarationId(declarationId: number): Promise<{ fileName: string, base64?: string }[]> {
    const documents = await this.regulatoryDocumentsRepo.find({
      where: {
        declaration_id: declarationId,
      },
      order: ['seq_no ASC']
    });
 
    const documentsBase64 = await Promise.all(documents.map(({ s3_uri }) => this.s3_service.getObject(s3_uri)));
    return documentsBase64.map(({ Body }, idx) => {
      if (!Body) {
        throw new HttpErrors.BadRequest(`Cannot download documents ${documents[idx].file_name} form S3`);
      }
      return {
        fileName: documents[idx].file_name.toUpperCase(),
        base64: Body.toString('base64'),
      }
    });
  }
 
  async updateDeclarationAfterSummit(declarationId: number, { data, status, message }: SubmitResponse, rawData?: AnyObject) {
    const updatedData: Partial<RegulatoryDeclarations> = {
      transaction_id: data?.transactionId.toString(),
      calista_status: status,
    }
    if (status === CalistaStatusCode.S001) {
      updatedData.status = Status.RegulatoryDeclaration.ForValidation;
    }
    await this.regulatorySubmissionHistoriesRepo.create({
      declaration_id: declarationId,
      transaction_id: data?.transactionId.toString(),
      status: updatedData.status,
      calista_status: status,
      req_data: rawData,
      res_data: data,
      created_by: this.current_user.id,
    });
    const declaration = await this.regulatoryDeclarationsRepo.findOne({where: {id: declarationId}});
    const declarationTransactionId = declaration?.transaction_id?.toString();
    const submitResponseTransactionId = data?.transactionId?.toString();
    if (declarationTransactionId !== submitResponseTransactionId) {
      await this.regulatoryDeclarationsRepo.updateById(declarationId, updatedData);
    }
    if (status !== CalistaStatusCode.S001) {
      throw new HttpErrors.BadRequest(message ?? `Unknown error (${status})`);
    }
  }
 
  async createHistory(uen: string, id: number, data: AnyObject) {
    const { Response: response } = data;
    const { count } = await this.regulatorySubmissionHistoriesRepo.count({
      transaction_id: response?.GeTSRefNo.toString(),
      calista_status: response.CustomerRefNo2,
    });
    if (count === 0) {
      await this.regulatorySubmissionHistoriesRepo.create({
        declaration_id: id,
        transaction_id: data?.Response?.GeTSRefNo.toString(),
        calista_status: response.CustomerRefNo2,
        remarks: data?.Response?.Remarks,
        res_data: data,
      });
    }
  }
 
  async updateTransaction(uen: string, id: number, data: RegulatoryDeclarationUpdateTransactionParam) {
    const dbCompanyRegulatory = await this.companyRegulatoryRepo.findOne({ 
      where: { 
        uen, 
        status: Status.CompanyRegulatory.Accepted,
        duration_end: { gte: new Date() }
      } 
    });
    if (!dbCompanyRegulatory) {
      const error = new EntityNotFoundError(this.companyRegulatoryRepo.entityClass, uen);
      error.code = 'ERR_UEN_NOT_FOUND';
      throw new HttpErrors.NotFound(error.message);
    }
 
    const dbRegulatoryDeclarations = await this.regulatoryDeclarationsRepo.findOne({
      where: { id, company_id: dbCompanyRegulatory.company_id },
      include: [{
        relation: 'verifier',
        scope: { fields: { id: true, contact_email: true, status: true, name: true }, where: { status: Status.User.Active } },
      }, {
        relation: 'company',
        scope: {
          fields: { id: true, identifier: true },
        }
      }]
    });
    if (!dbRegulatoryDeclarations) {
      const error = new EntityNotFoundError(this.regulatoryDeclarationsRepo.entityClass, id);
      error.code = 'ERR_DEC_NOT_FOUND';
      throw new HttpErrors.NotFound(error.message);
    }
 
    const { Response: response } = data;
    // if (dbRegulatoryDeclarations.status !== Status.RegulatoryDeclaration.ForValidation) {
    //   const error = new HttpErrors.BadRequest('Invalid status!');
    //   error.code = 'ERR_STATUS_INVALID';
    //   throw error;
    // }
 
    const updatedData: Partial<RegulatoryDeclarations> = {
      calista_status: response.CustomerRefNo2
    };
 
    if (response.CustomerRefNo2 === CalistaResponseCode.DraftCreated
      || response.CustomerRefNo2 === CalistaResponseCode.DraftCreatedDI
      || response.CustomerRefNo2 === CalistaResponseCode.DraftSubmittedToCustoms) {
      const { Remarks: remarks } = response;
      if (remarks?.length) {
        const uniqueRefNo = remarks[0]['unique_ref_no'];
        if (uniqueRefNo) {
          updatedData.calista_job_no = uniqueRefNo.date + numberFormat(uniqueRefNo.seq, 4);
        }
      }
    }
 
    if (response.CustomerRefNo2 === CalistaResponseCode.ProcessingError
      || response.CustomerRefNo2 === CalistaResponseCode.DraftCreatedDI
      || response.CustomerRefNo2 === CalistaResponseCode.CancellationApproved
    ) {
      updatedData.status = Status.RegulatoryDeclaration.ForValidationMissingInfo;
      const logChainAdminUsers = await this.user_repo.find({
        where: {
          company_id: LogChainConfigs.LogChainCompanyId,
          status: Status.User.Active,
        }
      });
      if (logChainAdminUsers.length) {
        const mail = MailTemplateMapping[response.CustomerRefNo2];
        const attachments = [
          {
            filename: 'response.json',
            content: Buffer.from(JSON.stringify(data, null, 2)),
            contentType: 'application/json'
          }
        ];
        await Promise.allSettled(logChainAdminUsers.map(({ contact_email, name }) => this.ses_service.sendEmailWithAttachment(
          mail.subject,
          mail.htmlPath,
          contact_email,
          [],
          {
            link: this._buildHref(dbRegulatoryDeclarations.id),
            adminUserName: name,
            declarationId: dbRegulatoryDeclarations.id,
          },
          attachments
        )));
      }
    } else {
      if (response.CustomerRefNo2 === CalistaResponseCode.DraftCreated
        || response.CustomerRefNo2 === CalistaResponseCode.ErrorMessageFromCustoms) {
        updatedData.status = Status.RegulatoryDeclaration.ForValidationMissingInfo;
      }
 
      if (response.CustomerRefNo2 === CalistaResponseCode.DraftSubmittedToCustoms) {
        updatedData.status = Status.RegulatoryDeclaration.ForValidation;
      }
 
      if (response.CustomerRefNo2 === CalistaResponseCode.RejectedMessageFromCustoms) {
        updatedData.status = Status.RegulatoryDeclaration.Rejected;
      }
 
      let ccRecipients: string[] = [];
      if (response.CustomerRefNo2 === CalistaResponseCode.ApprovedPermit) {
        const { add_recipients } = dbRegulatoryDeclarations;
        ccRecipients = [...add_recipients.map((email) => email)].filter((email) => email);
        const { company } = dbRegulatoryDeclarations
        if (response.DeclarationData && company) {
          const buf = Buffer.from(response.DeclarationData, 'base64')
          updatedData.declaration_file = `documents/regulatory/${company.identifier}/${dbRegulatoryDeclarations.transaction_id}-declaration.pdf`;
          const param = {
            Key: updatedData.declaration_file,
            Body: buf,
            ContentEncoding: 'base64',
            ContentType: 'application/pdf',
            ServerSideEncryption: 'AES256',
          };
          const putResult = await this.s3_service.putObject(param);
          if (dbRegulatoryDeclarations.flow_id) {
            // invoke chaincode AttachRegulatory
            const blockchainTx = await this.cc_service.invoke('AttachRegulatory', {
              flowId: dbRegulatoryDeclarations.flow_id,
              regId: dbRegulatoryDeclarations.id,
              hash: putResult.ETag?.replace(/"/g, ''),
              uri: updatedData.declaration_file,
              version: putResult.VersionId,
            });
            updatedData.blockchain_tx = blockchainTx;
          }
 
          updatedData.hash = putResult.ETag?.replace(/"/g, '');
          updatedData.version = putResult.VersionId;
        }
        updatedData.status = Status.RegulatoryDeclaration.Accepted;
      }
      const { Remarks: remarks } = response;
      const { verifier } = dbRegulatoryDeclarations;
      if (verifier) {
        const mail = MailTemplateMapping[response.CustomerRefNo2];
        await this.ses_service.sendEmailWithAttachment(
          mail.subject,
          mail.htmlPath,
          verifier.contact_email,
          ccRecipients,
          {
            link: this._buildHref(dbRegulatoryDeclarations.id),
            verifierName: verifier.name,
            declarationId: dbRegulatoryDeclarations.id,
            ...remarks[0],
          }
        );
      }
    }
 
    await this.regulatoryDeclarationsRepo.updateById(id, { ...updatedData, transaction_id: data?.Response?.GeTSRefNo.toString() });
  }
 
  private _buildHref(id: number): string {
    return `${LogChainConfigs.portalUrl}/regulatory/transaction/${id}/submission`;
  }
 
  async calcStatisticDeclarationByCarType(companyId?: number) {
    const params = [];
    let sql = `
      SELECT
        COUNT ( rd.ID ) FILTER ( WHERE rd.car_type = 'OUTDEC' ) AS total_outdec,
        COUNT ( rd.ID ) FILTER ( WHERE rd.car_type = 'INPDEC' ) AS total_inpdec,
        COUNT ( rd.ID ) FILTER ( WHERE rd.car_type = 'IPTDEC' ) AS total_iptdec
      FROM
        regulatory_declarations rd`;
    if (companyId) {
      params.push(companyId);
      sql += ' WHERE rd.company_id = $1';
    }
    return this.regulatoryDeclarationsRepo.execute(sql, params);
  }
 
  async calcStatisticDeclarationByDate(fromDate: Date, toDate: Date, companyId?: number) {
    const params: (Date | number)[] = [fromDate, toDate];
    let sql = `
      SELECT
        TO_CHAR( modified_date, 'Mon YYYY' ) AS month,
        COUNT ( rd.ID ) FILTER ( WHERE rd.car_type = 'OUTDEC' ) AS total_outdec,
        COUNT ( rd.ID ) FILTER ( WHERE rd.car_type = 'INPDEC' ) AS total_inpdec,
        COUNT ( rd.ID ) FILTER ( WHERE rd.car_type = 'IPTDEC' ) AS total_iptdec,
        COUNT ( rd.ID ) FILTER ( WHERE rd.status = 1 ) AS total_draft,
        COUNT ( rd.ID ) FILTER ( WHERE rd.status = 2 ) AS total_for_validation,
        COUNT ( rd.ID ) FILTER ( WHERE rd.status = 3 ) AS total_for_validation_missing_info,
        COUNT ( rd.ID ) FILTER ( WHERE rd.status = 4 ) AS total_accepted,
        COUNT ( rd.ID ) FILTER ( WHERE rd.status = 5 ) AS total_rejected
      FROM
        regulatory_declarations rd
      WHERE rd.modified_date BETWEEN $1 AND $2`;
    if (companyId) {
      params.push(companyId);
      sql += ' AND rd.company_id = $3';
    }
    sql += ' GROUP BY month';
    return this.regulatoryDeclarationsRepo.execute(sql, params);
  }
 
  async calcStatisticDeclaration(companyId?: number) {
    const now = moment();
    const currentMonth = now.format("MMM YYYY");
    const startOfYear = now.startOf('year').toDate();
    const endOfYear = now.endOf('year').toDate();
    const stats = await this.calcStatisticDeclarationByDate(startOfYear, endOfYear, companyId);
    const statsByCarTypeAllTime = await this.calcStatisticDeclarationByCarType(companyId);
    const statsOfCurrentMonth = stats.find(({ month }: { month: string }) => month === currentMonth);
    return {
      stats_by_car_type: statsByCarTypeAllTime?.length ? statsByCarTypeAllTime[0] : {},
      stats_of_month: statsOfCurrentMonth,
      stats_of_years: stats
    };
  }
 
  async findHistorySubmissions(declarationId: number, historyFilter: FilterBuilder<RegulatorySubmissionHistories>) {
    this.filter_builder.where({ id: declarationId });
    const dbRegulatoryDeclarations = await this.regulatoryDeclarationsRepo.findOne(this.filter_builder.build());
    if (!dbRegulatoryDeclarations) {
      throw new EntityNotFoundError(this.regulatoryDeclarationsRepo.entityClass, declarationId);
    }
 
    historyFilter.impose({
      declaration_id: dbRegulatoryDeclarations.id,
    });
    historyFilter.order(['created_date DESC']);
    historyFilter.fields({
      'id': true,
      'declaration_id': true,
      'transaction_id': true,
      'status': true,
      'calista_status': true,
      'remarks': true,
      'created_date': true,
      'created_by': true,
      'res_data': true
    });
    return this.regulatorySubmissionHistoriesRepo.findWithPaging(historyFilter.build());
  }
 
  async getRegulatoryDeclarationsByFlowId(flowId: number) {
    return this.regulatoryDeclarationsRepo.findOne({
      fields: ['id', 'flow_id', 'calista_status', 'company_id', 'declaration_file', 'version', 'hash', 'blockchain_tx'],
      where: {
        flow_id: flowId,
        company_id: this.current_user.company_id,
        calista_status: CalistaResponseCode.ApprovedPermit
      }
    });
  }
 
  buildFinalSchema(regulatoryDeclarations: RegulatoryDeclarations) {
    const { in_tpt_mode, out_tpt_mode } = regulatoryDeclarations;
    const finalSchema = cloneDeep(finalDeclarationsSchema);
    const { properties: { message } } = finalSchema
    const hasInTptMode = in_tpt_mode && in_tpt_mode.toString() !== TransportMode.MULTIMODAL;
    const hasOutTptMode = out_tpt_mode && out_tpt_mode.toString() !== TransportMode.MULTIMODAL;
 
    if (hasInTptMode || hasOutTptMode) {
      message?.required.push('transport');
    }
 
    // ++ Because in_tpt_mode and out_tpt_mode are both additional
    // so we have to by pass them if not required or vice versa
    if (hasInTptMode) {
      message?.properties?.transport?.required.push('in_tpt');
    } else {
      if (message?.properties?.transport?.properties?.in_tpt?.required) // ts left-hand operand syntax
        message.properties.transport.properties.in_tpt.required = [];
    }
 
    if (hasOutTptMode) {
      message?.properties?.transport?.required.push('out_tpt');
    } else {
      if (message?.properties?.transport?.properties?.out_tpt?.required) // ts left-hand operand syntax
        message.properties.transport.properties.out_tpt.required = [];
    }
 
    if (message?.properties?.transport?.additionalProperties === false) // ts left-hand operand syntax
        message.properties.transport.additionalProperties = true;
    // --
 
 
    return { ...finalSchema }
  }
 
  async findParties(filter: AnyObject) {
    const query = `SELECT * FROM (
      SELECT DISTINCT ON (cr_uei_no) cr_uei_no AS cr_uei_no_alias, parties_view_1.*
      FROM (
        SELECT 
          CASE WHEN rp."type" = $1 THEN rp.name1
          ELSE rp.cr_uei_no END AS cr_uei_no,
          rp.id,
          rp.type,
          rp.name1,
          rp.name2,
          rp.address1,
          rp.address2,
          rp.city,
          rp.sbt_code,
          rp.sbt_name,
          rp.pst_code,
          rp.cty_code,
          rp.extra_info
        FROM regulatory_parties rp
        JOIN regulatory_declarations rd ON rd.id = rp.declaration_id
        AND rd.company_id = $2
        ${filter?.where?.type ? `WHERE rp."type" = '${filter.where.type}'` : ''}
      ) AS parties_view_1
      ORDER BY cr_uei_no ASC, id DESC
    ) parties_view_2
    WHERE name1 ILIKE $3 ORDER BY name1 ASC`;
 
    const data = await this.regulatoryPartiesRepo.execute(query, [
      PartyType.Consignee, 
      this.current_user.company_id,
      filter?.where?.name1?.like || '%%'
    ]);
 
    return {
      data: data as RegulatoryParties
    }
  }
 
  async findFiltersFlows(itemFilter: FilterBuilder<Flow>) {
    // Get list of flows by flow_persona
    const filter_persona = new FilterBuilder<FlowPersona>({
      fields: ['id', 'flow_id', 'company_id'],
      where: {
        company_id: this.current_user.company_id,
      },
    });
    const flow_personas = await this.flowPersonaRepo.find(filter_persona.build());
    const flowIds = flow_personas.map(persona => persona.flow_id);
    itemFilter.impose({
      id: {inq: flowIds},
      status: {
        inq: [Status.Flow.Validated, Status.Flow.Live],
      },
      live_status: {inq: [Status.LiveStatus.New, Status.LiveStatus.InTransit]},
    });
    // ------------------------------------
 
    return this.flowRepo.findWithPaging(itemFilter.build());
  }
}