addio-admin-sdk 1.7.187 → 1.7.188

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(yarn test *)"
5
+ ]
6
+ }
7
+ }
package/.env CHANGED
@@ -2,14 +2,13 @@ NEXT_PUBLIC_FIREBASE_CONFIG_API_KEY_DEV='AIzaSyBNtwzdIe2__HJD23S87RIbWbIqKQVtFiw
2
2
  NEXT_PUBLIC_FIREBASE_CONFIG_API_KEY_PROD='AIzaSyDK6WQZkCrsMGunAPHn9KkdCGPky4hTgL4'
3
3
  NEXT_PUBLIC_MESSAGING_SENDER_ID_DEV='188490998694'
4
4
  NEXT_PUBLIC_MESSAGING_SENDER_ID_PROD='725873016982'
5
- NEXT_PUBLIC_FIREBASE_APP_ID_PROD='1:725873016982:web:9b1f6d77819909e19102b7'
6
5
  NEXT_PUBLIC_FIREBASE_APP_ID_DEV='1:188490998694:web:eecd719e7b18f38d272567'
6
+ NEXT_PUBLIC_FIREBASE_APP_ID_PROD='1:725873016982:web:9b1f6d77819909e19102b7'
7
7
  NEXT_PUBLIC_MEASUREMENT_ID_DEV='G-4BB66ZRTWZ'
8
8
  NEXT_PUBLIC_MEASUREMENT_ID_PROD='G-BB8HHZ466R'
9
-
10
9
  NEXT_PUBLIC_SERVICE_DATABASE_READ_PROVIDER=nobase
11
- NEXT_PUBLIC_SERVICE_DATABASE_WRITE_PROVIDER=nobase
10
+ NEXT_PUBLIC_SERVICE_DATABASE_WRITE_PROVIDER=nobase,firebase
12
11
  NEXT_PUBLIC_SERVICE_DATABASE_URL=https://db-test.addiocommerce.com/
13
- NEXT_PUBLIC_API_URL=https://api-test.addiocommerce.com/v1
14
- NEXT_PUBLIC_SERVICE_DATABASE_TOKEN='337043a374-6f0be-5eb26-05be550631'
15
- LOCAL_FIRESTORE=false
12
+ NEXT_PUBLIC_SERVICE_DATABASE_TOKEN=$SERVICE_DATABASE_TOKEN
13
+ # NEXT_PUBLIC_API_URL=https://api-test.addiocommerce.com/v1
14
+ NEXT_PUBLIC_API_URL=http://localhost:8080
@@ -7,11 +7,11 @@ export default interface IEmail {
7
7
  export declare const getDefaultEmail: (locale?: string) => {
8
8
  TemplateModel: {
9
9
  shopping_cart_icon: string;
10
+ check_icon: string;
11
+ mail_icon: string;
10
12
  help_label: string;
11
13
  preferences_label: string;
12
14
  unsubscribe_label: string;
13
- check_icon: string;
14
- mail_icon: string;
15
15
  socialmedias_items: never[];
16
16
  };
17
17
  };
@@ -4,32 +4,18 @@ exports.getDefaultEmailTemplateBySpace = exports.getDefaultEmail = void 0;
4
4
  const __1 = require("../..");
5
5
  const locale_1 = require("../../utils/locale");
6
6
  const getDefaultEmail = (locale = 'fr') => {
7
- switch (locale) {
8
- case 'en':
9
- return {
10
- TemplateModel: {
11
- shopping_cart_icon: `https://gng-ecr${__1.isTestEnv ? '-test' : ''}.imgix.net/1.0.0/emails_src/shopping_cart_icon.png`,
12
- help_label: 'Contact us',
13
- preferences_label: 'Settings',
14
- unsubscribe_label: 'Unsubscribe',
15
- check_icon: `https://gng-ecr${__1.isTestEnv ? '-test' : ''}.imgix.net/1.0.0/emails_src/check_icon.png`,
16
- mail_icon: `https://gng-ecr${__1.isTestEnv ? '-test' : ''}.imgix.net/1.0.0/emails_src/mail_icon.png`,
17
- socialmedias_items: []
18
- }
19
- };
20
- default:
21
- return {
22
- TemplateModel: {
23
- shopping_cart_icon: `https://gng-ecr${__1.isTestEnv ? '-test' : ''}.imgix.net/1.0.0/emails_src/shopping_cart_icon.png`,
24
- help_label: 'Nous joindre',
25
- preferences_label: 'Préférences',
26
- unsubscribe_label: 'Se désinscrire',
27
- check_icon: `https://gng-ecr${__1.isTestEnv ? '-test' : ''}.imgix.net/1.0.0/emails_src/check_icon.png`,
28
- mail_icon: `https://gng-ecr${__1.isTestEnv ? '-test' : ''}.imgix.net/1.0.0/emails_src/mail_icon.png`,
29
- socialmedias_items: []
30
- }
31
- };
32
- }
7
+ const baseImgUrl = `https://${__1.isTestEnv ? 'test' : 'beta'}.ecomm.titanestudio.ca/images/emails`;
8
+ return {
9
+ TemplateModel: {
10
+ shopping_cart_icon: `${baseImgUrl}/shopping_cart_icon.png`,
11
+ check_icon: `${baseImgUrl}/check_icon.png`,
12
+ mail_icon: `${baseImgUrl}/mail_icon.png`,
13
+ help_label: (0, locale_1.translateILang)({ fr: 'Nous joindre', en: 'Contact us' }, locale),
14
+ preferences_label: (0, locale_1.translateILang)({ fr: 'Préférences', en: 'Settings' }, locale),
15
+ unsubscribe_label: (0, locale_1.translateILang)({ fr: 'Se désinscrire', en: 'Unsubscribe' }, locale),
16
+ socialmedias_items: []
17
+ }
18
+ };
33
19
  };
34
20
  exports.getDefaultEmail = getDefaultEmail;
35
21
  const getDefaultEmailTemplateBySpace = (space, locale = 'fr') => {
@@ -1 +1 @@
1
- {"version":3,"file":"IEmail.js","sourceRoot":"","sources":["../../../src/Interfaces/Email/IEmail.ts"],"names":[],"mappings":";;;AACA,6BAAiC;AAEjC,+CAA2D;AAQpD,MAAM,eAAe,GAAG,CAAC,SAAiB,IAAI,EAAE,EAAE;IACxD,QAAQ,MAAM,EAAE;QACf,KAAK,IAAI;YACR,OAAO;gBACN,aAAa,EAAE;oBACd,kBAAkB,EAAE,kBACnB,aAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EACvB,oDAAoD;oBACpD,UAAU,EAAE,YAAY;oBACxB,iBAAiB,EAAE,UAAU;oBAC7B,iBAAiB,EAAE,aAAa;oBAChC,UAAU,EAAE,kBAAkB,aAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,4CAA4C;oBAClG,SAAS,EAAE,kBAAkB,aAAS,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,2CAA2C;oBAChG,kBAAkB,EAAE,EAAE;iBACtB;aACD,CAAA;QAEF;YACC,OAAO;gB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CAAC,CAAC,aAAa,CAAA;IAC3F,IAAI,aAAa,GAAoC,KAAK,CAAC,IAAI,EAAE,CAAC,aAAa,CAAA;IAC/E,IAAI,CAAC,CAAC,aAAa,EAAE;QACpB,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YAC1C;YACC,wBAAwB;YACxB,CAAC,CAAC,aAAa;gBACf,+CAA+C;gBAC/C,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC;gBACpB,qCAAqC;gBACrC,CAAC,CAAC,CAAC,kBAAkB,EAAE,0BAA0B,EAAE,YAAY,EAAE,WAAW,EAAE,kBAAkB,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,EAC9G;gBACD,aAAa,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;oBACrD,CAAC,CAAC,+BAA+B;wBAChC,IAAA,+BAAsB,EAAC,aAAa,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;oBACnD,CAAC,CAAC,gCAAgC;wBACjC,aAAa,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAA;aAC5B;QACF,CAAC,CAAC,CAAA;QACF,YAAY,mCACR,YAAY,GACZ,aAAa,CAChB,CAAA;KACD;IAED,OAAO;QACN,aAAa,EAAE,YAAY;KAC3B,CAAA;AACF,CAAC,CAAA;AA7BY,QAAA,8BAA8B,kCA6B1C"}
@@ -162,6 +162,7 @@ export default class Cart extends BaseServiceClass<ICart> {
162
162
  usedPromise?: ICartPromiseToPurchase;
163
163
  saveToDatabase?: boolean;
164
164
  associatedTransferRequests?: TransferRequest[];
165
+ forceApplyInactivePA?: boolean;
165
166
  }) => Promise<this | undefined>;
166
167
  private defineWhatICanBe;
167
168
  checkDiscountConditions: (discount: IDiscountRule) => boolean;
@@ -274,8 +275,10 @@ export default class Cart extends BaseServiceClass<ICart> {
274
275
  * @param escompteItems list of discount products from the dash
275
276
  * @param customPriceList list of products with their custom pric from G2
276
277
  * @param banksUsedForCart Optionnal. Array of banks_used applied to cart
278
+ * @param isCartModification Optionnal. Is it a modification process
277
279
  */
278
- updateWithPromiseToPurchasePrices: (escompteItems: IndexedProduct[], customPriceList?: string | ICustomPriceItem[] | undefined, banksUsedForCart?: IBankUsed[]) => Promise<void>;
280
+ updateWithPromiseToPurchasePrices: (escompteItems: IndexedProduct[], customPriceList?: string | ICustomPriceItem[] | undefined, banksUsedForCart?: IBankUsed[], isCartModification?: boolean) => Promise<void>;
281
+ removePromiseToPurchaseFromCart: (customPriceList?: string | ICustomPriceItem[] | undefined) => Promise<void>;
279
282
  /**
280
283
  * Function canBePaidWithMyPromiseToPurchase
281
284
  * @description Check if a cart can be paid with a promise to purchase
@@ -284,9 +287,10 @@ export default class Cart extends BaseServiceClass<ICart> {
284
287
  * @param customPriceList a list of custom price items
285
288
  * @param contingency contingency (from the space)
286
289
  * @param forceCartTypeid Optionnal. A cart type ID to use for bank to apply check, if should be forced
290
+ * @param contingencyExemptBankTypeIds Optionnal. In modification, the original PA bank types allowed to overdraw past the contingency. New banks are still checked
287
291
  * @returns true if cart can be paid, false if it cannot
288
292
  */
289
- canBePaidWithMyPromiseToPurchase: (applicableBanks: IApplicablePromiseBank[], applicableBanksHistory: IIndexedBankUsed[], customPriceList?: string | ICustomPriceItem[] | undefined, contingency?: number | undefined, forcedBankTypeId?: string) => Promise<boolean | ApplyBanksToCartErrorsEnum>;
293
+ canBePaidWithMyPromiseToPurchase: (applicableBanks: IApplicablePromiseBank[], applicableBanksHistory: IIndexedBankUsed[], customPriceList?: string | ICustomPriceItem[] | undefined, contingency?: number | undefined, forcedBankTypeId?: string, bypassBankAvailability?: boolean, contingencyExemptBankTypeIds?: string[]) => Promise<boolean | ApplyBanksToCartErrorsEnum>;
290
294
  /**
291
295
  * Function calculatePotentialRemainingAmountsAndSetBanksUsedAmounts
292
296
  * @description Calculate the amounts that would remain in the promise's banks if we paid this cart with the promise and associates the amounts to use in the banks to the cart
@@ -295,7 +299,7 @@ export default class Cart extends BaseServiceClass<ICart> {
295
299
  * @param promiseToPurchase the promise to purchase
296
300
  * @returns an array of IBankUsed
297
301
  */
298
- calculatePotentialRemainingAmountsAndSetBanksUsedAmounts: (remainingAmounts: IBankUsed[], applicableBanks: IApplicablePromiseBank[], forcedBankTypeId?: string | undefined) => IBankUsed[];
302
+ calculatePotentialRemainingAmountsAndSetBanksUsedAmounts: (remainingAmounts: IBankUsed[], applicableBanks: IApplicablePromiseBank[], forcedBankTypeId?: string | undefined, bypassBankAvailability?: boolean) => IBankUsed[];
299
303
  private _savePromiseToPurchaseInCart;
300
304
  setBankUsed: (bankAmountsUpdated: IBankUsed[]) => void;
301
305
  /**
@@ -306,9 +310,11 @@ export default class Cart extends BaseServiceClass<ICart> {
306
310
  * @param customPriceList a list of custom price items
307
311
  * @param space the space
308
312
  * @param forcedCartType Optionnal. If provided, overrides cart type found by check cart item types.
313
+ * @param isCartModification Optionnal. Pass true when called from the POS order modification flow so escompte lines are rebuilt even on a paid cart.
314
+ * @param originalPromiseToPurchase Optionnal. The PA the order was originally paid with. In modification, its banks are re-applied even if now disabled.
309
315
  * @returns the updated cart and a boolean canBePaid determining if the cart can be paid with the promise or not
310
316
  */
311
- canBePaidWithPA: (applicableBanks: IApplicablePromiseBank[], customerID: string, customPriceList: ICustomPriceItem[], space: Space, forcedBankTypeId?: string) => Promise<{
317
+ canBePaidWithPA: (applicableBanks: IApplicablePromiseBank[], customerID: string, customPriceList: ICustomPriceItem[], space: Space, forcedBankTypeId?: string, isCartModification?: boolean, originalPromiseToPurchase?: ICartPromiseToPurchase) => Promise<{
312
318
  canBePaid: boolean;
313
319
  canBePaidReason?: ApplyBanksToCartErrorsEnum | undefined;
314
320
  updatedCart: ICart;
@@ -60,7 +60,6 @@ const g2_1 = require("../../rules/GR/utils/g2");
60
60
  const cart_1 = require("../../utils/cart");
61
61
  const promiseToPurchase_1 = require("../../utils/promiseToPurchase");
62
62
  const PromiseToPurchase_2 = require("../../Interfaces/PromiseToPurchase");
63
- const products_2 = require("../../rules/GR/utils/products");
64
63
  const baseService_1 = require("../baseService");
65
64
  const DatabaseService_1 = __importDefault(require("../../services/database/DatabaseService"));
66
65
  const logs_1 = require("../../services/logs");
@@ -1899,6 +1898,7 @@ class Cart extends baseService_1.BaseServiceClass {
1899
1898
  }
1900
1899
  };
1901
1900
  this.saveCartModification = async (partial, oldItems, newItems, currentUser, options = {}) => {
1901
+ var _b, _c, _d, _e, _f, _g;
1902
1902
  // default saveToDatabase to true
1903
1903
  const shouldSaveToDB = typeof options.saveToDatabase == 'boolean' ? options.saveToDatabase : true;
1904
1904
  try {
@@ -1906,46 +1906,45 @@ class Cart extends baseService_1.BaseServiceClass {
1906
1906
  const space = await Space_2.default.getCurrentSpaceWithRef(this._collection.path, this._user);
1907
1907
  if (!!!space)
1908
1908
  throw new Error('could not init space obj');
1909
- // If the cart is associated to a promise
1910
- if (!!options.usedPromise) {
1911
- for (const bank of options.usedPromise.banks_used) {
1912
- const promiseQuery = await space.promisesToPurchase.get({
1913
- query: [{ field: 'id', operator: '==', value: bank.promise_id }]
1914
- });
1915
- // If the promise is closed or doesn't exist, we don't adjust it
1916
- if (!!!promiseQuery || !!!promiseQuery.length)
1917
- continue;
1918
- if (!!promiseQuery[0].data().ending_date)
1919
- continue;
1920
- // If the bank is inactive, we don't adjust it
1921
- const bankInDB = promiseQuery[0].data().banks.find((b) => b.bank_type_id === bank.bank_type_id);
1922
- if (!!!bankInDB || !!!bankInDB.active)
1923
- continue;
1924
- let amountTotal = 0;
1925
- const taxes = this.data().total - this.data().subtotal;
1926
- if ((0, promiseToPurchase_1.getBankTypeName)(space.bankTypes.get(), bank.bank_type_id) === 'installation') {
1927
- amountTotal = Number((0, products_2.getInstallItemPrice)('installation-gazon', itemsForInventory.filter((i) => !!i.is_service)));
1928
- }
1929
- else {
1930
- const itemsWithoutInstallation = itemsForInventory.filter((i) => !!!i.parent_slug || !!!['installation-gazon', 'frais-de-mobilisation'].includes(i.parent_slug));
1931
- itemsWithoutInstallation.map((i) => (amountTotal += (0, products_1.getLowestPrice)(i).price.amount * i.qte));
1932
- amountTotal += taxes;
1909
+ const beforeBanksUsed = (_c = (_b = options.usedPromise) === null || _b === void 0 ? void 0 : _b.banks_used) !== null && _c !== void 0 ? _c : [];
1910
+ const afterBanksUsed = (_e = (_d = this.data().promise_to_purchase) === null || _d === void 0 ? void 0 : _d.banks_used) !== null && _e !== void 0 ? _e : [];
1911
+ const adjustmentsToApply = (0, promiseToPurchase_1.getModificationBankAdjustments)(beforeBanksUsed, afterBanksUsed, (_f = this.data().ref) !== null && _f !== void 0 ? _f : '');
1912
+ if (shouldSaveToDB && !!adjustmentsToApply.length) {
1913
+ for (const promiseId of (0, uniq_1.default)(adjustmentsToApply.map((a) => a.promise_id))) {
1914
+ try {
1915
+ const promiseQuery = await space.promisesToPurchase.get({
1916
+ query: [{ field: 'id', operator: '==', value: promiseId }]
1917
+ });
1918
+ if (!!!promiseQuery || !!!promiseQuery.length)
1919
+ continue;
1920
+ const promise = promiseQuery[0];
1921
+ if (!options.forceApplyInactivePA && !!promise.data().ending_date)
1922
+ continue;
1923
+ let newBanks = promise.data().banks;
1924
+ let updated = false;
1925
+ for (const { bank_type_id, adjustment } of adjustmentsToApply.filter((a) => a.promise_id === promiseId)) {
1926
+ const bankInDB = newBanks.find((b) => b.bank_type_id === bank_type_id);
1927
+ if (!!!bankInDB || (!options.forceApplyInactivePA && !!!bankInDB.active))
1928
+ continue;
1929
+ const remaining = await space.promisesToPurchase.getSpecificAvailableBankAmount(promiseId, bank_type_id, promise);
1930
+ const bankNowEmpty = !!remaining && typeof remaining.remaining_amount === 'number'
1931
+ ? (0, round_1.default)(remaining.remaining_amount, 3) + (0, round_1.default)(adjustment.amount, 3) < 1
1932
+ : false;
1933
+ const updatedBank = Object.assign(Object.assign(Object.assign({}, bankInDB), { adjustments: [...((_g = bankInDB.adjustments) !== null && _g !== void 0 ? _g : []), Object.assign(Object.assign({}, adjustment), { issued_by: this._user })] }), (!!bankNowEmpty ? { active: false } : {}));
1934
+ newBanks = newBanks.map((b) => (b.bank_type_id === bank_type_id ? updatedBank : b));
1935
+ updated = true;
1936
+ }
1937
+ if (!!updated) {
1938
+ const allBanksInactive = newBanks.every((b) => !!!b.active);
1939
+ await promise.save(Object.assign({ banks: newBanks }, (!!allBanksInactive && !!!promise.data().ending_date ? { ending_date: (0, moment_1.default)().toDate() } : {})));
1940
+ }
1933
1941
  }
1934
- const adjustment = {
1935
- amount: amountTotal * -1,
1936
- reason: `Modification de la commande #${this.data().ref}`,
1937
- issued_at: new Date(),
1938
- issued_by: !!currentUser ? currentUser : (0, services_1.getDefaultSpaceUserEmail)(space.data().id)
1939
- };
1940
- const remainingAmount = await space.promisesToPurchase.getSpecificAvailableBankAmount(bank.promise_id, bank.bank_type_id, promiseQuery[0]);
1941
- let newRemainingAmount;
1942
- if (!!remainingAmount && !!remainingAmount.remaining_amount) {
1943
- newRemainingAmount = (0, round_1.default)(remainingAmount.remaining_amount, 3) + (0, round_1.default)(adjustment.amount);
1942
+ catch (e) {
1943
+ console.log('error on adjusting promise for cart modification: ', e.toString());
1944
1944
  }
1945
- await promiseQuery[0].adjustAmountLeftInPromise(adjustment, bank.bank_type_id, !!newRemainingAmount && newRemainingAmount < 1);
1946
1945
  }
1947
1946
  }
1948
- await this.save(partial, undefined, shouldSaveToDB, true);
1947
+ await this.save(Object.assign(Object.assign({}, partial), { id: this._data.id }), undefined, shouldSaveToDB, true);
1949
1948
  // INVENTORY MANAGEMENT
1950
1949
  const data = this.data();
1951
1950
  const storeIdToUse = !!data.current_store_id
@@ -3328,12 +3327,14 @@ class Cart extends baseService_1.BaseServiceClass {
3328
3327
  * @param escompteItems list of discount products from the dash
3329
3328
  * @param customPriceList list of products with their custom pric from G2
3330
3329
  * @param banksUsedForCart Optionnal. Array of banks_used applied to cart
3330
+ * @param isCartModification Optionnal. Is it a modification process
3331
3331
  */
3332
- this.updateWithPromiseToPurchasePrices = async (escompteItems, customPriceList = undefined, banksUsedForCart) => {
3332
+ this.updateWithPromiseToPurchasePrices = async (escompteItems, customPriceList = undefined, banksUsedForCart, isCartModification = false) => {
3333
3333
  var _b, _c, _d, _e;
3334
3334
  if (!!!customPriceList || typeof customPriceList == 'string')
3335
3335
  throw new Error('CustomPriceList is undefined!');
3336
- if (!!this.data().status &&
3336
+ if (!isCartModification &&
3337
+ !!this.data().status &&
3337
3338
  this.data().status >= Cart_1.CartStatusEnum.CHECKOUT_PAYMENT_SUCCESS &&
3338
3339
  !!this.data().paid_at) {
3339
3340
  console.log('cannot update a paid cart with a PA, returning');
@@ -3397,6 +3398,18 @@ class Cart extends baseService_1.BaseServiceClass {
3397
3398
  this._data = Object.assign(Object.assign({}, this._data), { items: [...updatedPriceProducts, ...associatedEscomptes] });
3398
3399
  await this.calculateTotals();
3399
3400
  };
3401
+ // Remove PA ESC supp, revert to the non PA prices and cancel the PA
3402
+ this.removePromiseToPurchaseFromCart = async (customPriceList = undefined) => {
3403
+ if (!!!customPriceList || typeof customPriceList == 'string' || customPriceList.length === 0)
3404
+ throw new Error('CustomPriceList is undefined!');
3405
+ if (!!!this._data.promise_to_purchase)
3406
+ return;
3407
+ const revertedItems = this._data.items
3408
+ .filter((item) => !(0, g2_1.isEscompteSuppItem)(item.sku))
3409
+ .map((item) => (0, g2_1.checkForCustomPriceEquivalent)(item, customPriceList));
3410
+ this._data = Object.assign(Object.assign({}, this._data), { items: revertedItems, promise_to_purchase: null });
3411
+ await this.calculateTotals();
3412
+ };
3400
3413
  /**
3401
3414
  * Function canBePaidWithMyPromiseToPurchase
3402
3415
  * @description Check if a cart can be paid with a promise to purchase
@@ -3405,9 +3418,10 @@ class Cart extends baseService_1.BaseServiceClass {
3405
3418
  * @param customPriceList a list of custom price items
3406
3419
  * @param contingency contingency (from the space)
3407
3420
  * @param forceCartTypeid Optionnal. A cart type ID to use for bank to apply check, if should be forced
3421
+ * @param contingencyExemptBankTypeIds Optionnal. In modification, the original PA bank types allowed to overdraw past the contingency. New banks are still checked
3408
3422
  * @returns true if cart can be paid, false if it cannot
3409
3423
  */
3410
- this.canBePaidWithMyPromiseToPurchase = async (applicableBanks, applicableBanksHistory, customPriceList = undefined, contingency = 0, forcedBankTypeId) => {
3424
+ this.canBePaidWithMyPromiseToPurchase = async (applicableBanks, applicableBanksHistory, customPriceList = undefined, contingency = 0, forcedBankTypeId, bypassBankAvailability = false, contingencyExemptBankTypeIds) => {
3411
3425
  if (!!!customPriceList || typeof customPriceList == 'string')
3412
3426
  throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.CUSTOM_PRICE_LIST_UNDEFINED);
3413
3427
  // NEW - used to have a check here if contingency was undefined, but it makes more sense to let the logic pass, even if no contingency exists (could be a volontary decision from user)
@@ -3418,13 +3432,15 @@ class Cart extends baseService_1.BaseServiceClass {
3418
3432
  const remainingAmounts = await PromiseToPurchase_1.default.calculateRemainingAmounts(this, applicableBanks, applicableBanksHistory, space);
3419
3433
  // If only one bank is used and said bank has no initial amount, returns empty array
3420
3434
  // (so there is no overlap between "bank goes over allowed amount" and "bank is disabled in promise")
3421
- const potentialRemainingAmounts = this.calculatePotentialRemainingAmountsAndSetBanksUsedAmounts(remainingAmounts, applicableBanks, forcedBankTypeId);
3422
- // if bank to use has no initial amount, return false
3423
- // if payment for any of the banks goes over the remaining amount + the contingency, return false
3424
- if (!!!potentialRemainingAmounts.length) {
3435
+ const potentialRemainingAmounts = this.calculatePotentialRemainingAmountsAndSetBanksUsedAmounts(remainingAmounts, applicableBanks, forcedBankTypeId, bypassBankAvailability);
3436
+ // if all banks to use are empty/disabled, return false (skipped in modification to re-apply the original PA)
3437
+ if (!bypassBankAvailability && !!!potentialRemainingAmounts.length) {
3425
3438
  throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.BANK_NOT_FOUND);
3426
3439
  }
3427
- if (!!potentialRemainingAmounts.find((bank) => bank.amount + contingency < 0)) {
3440
+ // contingency is still enforced for banks that aren't part of the original PA (e.g. a new bank from an item added at modification)
3441
+ const overContingencyBank = potentialRemainingAmounts.find((bank) => bank.amount + contingency < 0 &&
3442
+ !(bypassBankAvailability && (!!!contingencyExemptBankTypeIds || contingencyExemptBankTypeIds.includes(bank.bank_type_id))));
3443
+ if (!!overContingencyBank) {
3428
3444
  throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.NOT_ENOUGH_REMAINING);
3429
3445
  }
3430
3446
  return true;
@@ -3442,7 +3458,7 @@ class Cart extends baseService_1.BaseServiceClass {
3442
3458
  * @param promiseToPurchase the promise to purchase
3443
3459
  * @returns an array of IBankUsed
3444
3460
  */
3445
- this.calculatePotentialRemainingAmountsAndSetBanksUsedAmounts = (remainingAmounts, applicableBanks, forcedBankTypeId) => {
3461
+ this.calculatePotentialRemainingAmountsAndSetBanksUsedAmounts = (remainingAmounts, applicableBanks, forcedBankTypeId, bypassBankAvailability = false) => {
3446
3462
  let accountedForItems = new Array();
3447
3463
  let itemsToCheck = this.data().items;
3448
3464
  // allow payment only if the cart contains at least one item that is associated to only one bank
@@ -3484,7 +3500,8 @@ class Cart extends baseService_1.BaseServiceClass {
3484
3500
  // check that not all banks to use are disabled in the promise to purchase
3485
3501
  // if banks to use is disabled make remainingAmounts an empty array :
3486
3502
  // the cart won't use bank because no bank corresponding to the cart is enabled in the promise to purchase
3487
- if (!!remainingAmounts.length) {
3503
+ // If the PA was applied in the creation process, allow applying the PA in modification process even if the bank is inactive
3504
+ if (!bypassBankAvailability && !!remainingAmounts.length) {
3488
3505
  const banksToUse = remainingAmounts;
3489
3506
  const promiseBanksToUse = banksToUse
3490
3507
  .map((bankToUse) => {
@@ -3553,6 +3570,17 @@ class Cart extends baseService_1.BaseServiceClass {
3553
3570
  }
3554
3571
  }
3555
3572
  }
3573
+ // Get esc supp. parent item
3574
+ const escSuppParentItem = (0, g2_1.isEscompteSuppItem)(item.sku) && !!item.is_upsell_of_sku
3575
+ ? this.data().items.find((i) => i.sku === item.is_upsell_of_sku)
3576
+ : undefined;
3577
+ const parentBankId = !!escSuppParentItem &&
3578
+ !!escSuppParentItem.promise_to_purchase_association_ids &&
3579
+ escSuppParentItem.promise_to_purchase_association_ids.length == 1
3580
+ ? escSuppParentItem.promise_to_purchase_association_ids[0]
3581
+ : undefined;
3582
+ const parentBankInRemaining = !!parentBankId && remainingAmounts.some((b) => b.bank_type_id === parentBankId);
3583
+ const isEscForParentBank = !!parentBankId && parentBankId === bank_type_id;
3556
3584
  const isServiceOrMultiple = (!!item.promise_to_purchase_association_ids &&
3557
3585
  !!!item.promise_to_purchase_association_ids.length &&
3558
3586
  !!item.is_service &&
@@ -3561,7 +3589,8 @@ class Cart extends baseService_1.BaseServiceClass {
3561
3589
  !!multipleBankItems.some((i) => i.sku === item.sku);
3562
3590
  return ((!!bankIDInAssociatedPromises ||
3563
3591
  !!isEscSupp ||
3564
- (!!isServiceOrMultiple && bank.bank_type_id === mostUsedBank.id)) &&
3592
+ !!isEscForParentBank ||
3593
+ (!!isServiceOrMultiple && !parentBankInRemaining && bank.bank_type_id === mostUsedBank.id)) &&
3565
3594
  !!!accountedForItems.includes(item.sku));
3566
3595
  });
3567
3596
  amountToRemove = (0, sumBy_1.default)(itemsToAccount, (item) => {
@@ -3570,7 +3599,7 @@ class Cart extends baseService_1.BaseServiceClass {
3570
3599
  return priceToPay * item.qte;
3571
3600
  });
3572
3601
  }
3573
- if (amountToRemove > 0 && amount < 1)
3602
+ if (!bypassBankAvailability && amountToRemove > 0 && amount < 1)
3574
3603
  throw new Error(PromiseToPurchase_2.ApplyBanksToCartErrorsEnum.EMPTY_BANK);
3575
3604
  if (amountToRemove > 0) {
3576
3605
  // Update banks used array
@@ -3607,14 +3636,23 @@ class Cart extends baseService_1.BaseServiceClass {
3607
3636
  * @param customPriceList a list of custom price items
3608
3637
  * @param space the space
3609
3638
  * @param forcedCartType Optionnal. If provided, overrides cart type found by check cart item types.
3639
+ * @param isCartModification Optionnal. Pass true when called from the POS order modification flow so escompte lines are rebuilt even on a paid cart.
3640
+ * @param originalPromiseToPurchase Optionnal. The PA the order was originally paid with. In modification, its banks are re-applied even if now disabled.
3610
3641
  * @returns the updated cart and a boolean canBePaid determining if the cart can be paid with the promise or not
3611
3642
  */
3612
- this.canBePaidWithPA = async (applicableBanks, customerID, customPriceList, space, forcedBankTypeId) => {
3643
+ this.canBePaidWithPA = async (applicableBanks, customerID, customPriceList, space, forcedBankTypeId, isCartModification = false, originalPromiseToPurchase) => {
3613
3644
  const contingency = space.promisesToPurchase.getContingency();
3614
3645
  const escomptesItems = await space.promisesToPurchase.getEscompteItems();
3646
+ // In modification, put the order's original PA banks back and ignore disabled bank
3647
+ const bypassBankAvailability = isCartModification && !!originalPromiseToPurchase && !!originalPromiseToPurchase.banks_used.length;
3648
+ // only the original PA banks may overdraw past the contingency, newly added banks are not concerned
3649
+ const contingencyExemptBankTypeIds = originalPromiseToPurchase === null || originalPromiseToPurchase === void 0 ? void 0 : originalPromiseToPurchase.banks_used.map((b) => b.bank_type_id);
3650
+ const effectiveApplicableBanks = bypassBankAvailability && !!originalPromiseToPurchase
3651
+ ? await (0, promiseToPurchase_1.getApplicableBanksWithOrderPA)(applicableBanks, originalPromiseToPurchase, space)
3652
+ : applicableBanks;
3615
3653
  // Get use history for applicable banks
3616
3654
  let applicableBanksHistory = [];
3617
- for (let applicable of applicableBanks) {
3655
+ for (let applicable of effectiveApplicableBanks) {
3618
3656
  const { promise_id, bank } = applicable;
3619
3657
  // don't fetch history if no initial_amount
3620
3658
  if (!!!bank.initial_amount)
@@ -3632,7 +3670,7 @@ class Cart extends baseService_1.BaseServiceClass {
3632
3670
  const filteredApplicableBanksHistory = (0, flatten_1.default)(applicableBanksHistory).filter((b) => !!b);
3633
3671
  // set possible escomptes in cart so correct amounts are used when checking available amounts
3634
3672
  // only set escomptes in cart based on potential applicableBanks where pa is active, bank is active and initial amount is set
3635
- const possibleBanksToUse = applicableBanks
3673
+ const possibleBanksToUse = effectiveApplicableBanks
3636
3674
  .filter((b) => !!b.pa_is_active && !!b.bank.active && !!b.bank.initial_amount)
3637
3675
  .map((b) => ({
3638
3676
  promise_id: b.promise_id,
@@ -3640,13 +3678,13 @@ class Cart extends baseService_1.BaseServiceClass {
3640
3678
  bank_type_id: b.bank.bank_type_id,
3641
3679
  amount: 0
3642
3680
  }));
3643
- await this.updateWithPromiseToPurchasePrices(escomptesItems, customPriceList, possibleBanksToUse);
3644
- const canBePaidCheck = await this.canBePaidWithMyPromiseToPurchase(applicableBanks, filteredApplicableBanksHistory, customPriceList, contingency, forcedBankTypeId);
3681
+ await this.updateWithPromiseToPurchasePrices(escomptesItems, customPriceList, possibleBanksToUse, isCartModification);
3682
+ const canBePaidCheck = await this.canBePaidWithMyPromiseToPurchase(effectiveApplicableBanks, filteredApplicableBanksHistory, customPriceList, contingency, forcedBankTypeId, bypassBankAvailability, contingencyExemptBankTypeIds);
3645
3683
  // if banks applicable length is different from banks truly applied to cart,
3646
3684
  // adjust added escomptes with banks used for cart
3647
3685
  if (!!this._data.promise_to_purchase &&
3648
- applicableBanks.length !== this._data.promise_to_purchase.banks_used.length) {
3649
- await this.updateWithPromiseToPurchasePrices(escomptesItems, customPriceList, this._data.promise_to_purchase.banks_used);
3686
+ effectiveApplicableBanks.length !== this._data.promise_to_purchase.banks_used.length) {
3687
+ await this.updateWithPromiseToPurchasePrices(escomptesItems, customPriceList, this._data.promise_to_purchase.banks_used, isCartModification);
3650
3688
  }
3651
3689
  const canBePaid = typeof canBePaidCheck === 'boolean';
3652
3690
  return Object.assign(Object.assign({ canBePaid }, (!!!canBePaid ? { canBePaidReason: canBePaidCheck } : {})), { updatedCart: this.data() });