@stamhoofd/backend 2.143.1 → 2.144.0

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.
@@ -12,10 +12,10 @@ import { SettlementStatus } from '@stamhoofd/structures/settlements/SettlementSt
12
12
  import Stripe from 'stripe';
13
13
 
14
14
  import { ApplicationFeeService } from '../services/ApplicationFeeService.js';
15
- import { ReportedRows, SettlementService } from '../services/SettlementService.js';
15
+ import { SettlementService } from '../services/SettlementService.js';
16
16
  import { ApplicationFeeDetails } from './ApplicationFeeDetails.js';
17
- import { passthroughFetch } from './passthroughFetch.js';
18
17
  import { getPaymentIdForStripeCharge } from './getPaymentIdForStripeCharge.js';
18
+ import { passthroughFetch } from './passthroughFetch.js';
19
19
  import { WebmasterReport } from './WebmasterReport.js';
20
20
 
21
21
  /**
@@ -109,8 +109,7 @@ export class StripeSettlementSync {
109
109
  }
110
110
 
111
111
  /**
112
- * Sync all paid payouts that arrived in the window. A failing payout is marked, reported and
113
- * skipped so the other payouts still sync; the summary tells the caller how bad it was.
112
+ * Sync all paid payouts that arrived in the window.
114
113
  */
115
114
  async syncPayouts({ start, end, force = false, abort }: { start: Date; end?: Date; force?: boolean; abort?: AbortSignal }): Promise<{ synced: number; skipped: number; failed: number }> {
116
115
  const result = { synced: 0, skipped: 0, failed: 0 };
@@ -180,7 +179,7 @@ export class StripeSettlementSync {
180
179
 
181
180
  // Storing a fee can link it to a balance item right away (a month the legacy invoicer
182
181
  // billed). When it is already paid out, its payout needs the derived line for it
183
- const invoicedFeeBalanceItemIds = new Set<string>();
182
+ const settledApplicationFeeBalanceItems = new Set<string>();
184
183
 
185
184
  try {
186
185
  for await (const transaction of this.stripe.balanceTransactions.list({
@@ -195,7 +194,7 @@ export class StripeSettlementSync {
195
194
  abort?.throwIfAborted();
196
195
 
197
196
  try {
198
- await this.#handleApplicationFee(transaction, { invoicedFeeBalanceItemIds });
197
+ await this.#handleApplicationFee(transaction, { settledApplicationFeeBalanceItems });
199
198
  } catch (e) {
200
199
  // The month is only invoiced after a walk without errors, so an interrupted
201
200
  // walk has to stop the walk itself instead of joining the errors of its
@@ -209,11 +208,11 @@ export class StripeSettlementSync {
209
208
  } catch (e) {
210
209
  // The payouts of the fees stored so far still need their derived lines, but failing to
211
210
  // update them may not hide what broke the walk
212
- await SettlementService.updatePaymentSettlementsForAccountDeductionBalanceItems([...invoicedFeeBalanceItemIds]).catch(console.error);
211
+ await SettlementService.updatePaymentSettlementsForApplicationFeeBalanceItems([...settledApplicationFeeBalanceItems]).catch(console.error);
213
212
  throw e;
214
213
  }
215
214
 
216
- await SettlementService.updatePaymentSettlementsForAccountDeductionBalanceItems([...invoicedFeeBalanceItemIds]);
215
+ await SettlementService.updatePaymentSettlementsForApplicationFeeBalanceItems([...settledApplicationFeeBalanceItems]);
217
216
 
218
217
  if (errors.length > 0) {
219
218
  throw new SimpleError({
@@ -234,7 +233,7 @@ export class StripeSettlementSync {
234
233
  * be updated afterwards. Filled while storing, not from the return value: a fee that is
235
234
  * stored before a later one throws still needs its derived line.
236
235
  */
237
- invoicedFeeBalanceItemIds?: Set<string>;
236
+ settledApplicationFeeBalanceItems?: Set<string>;
238
237
  } = {}): Promise<{ fees: ApplicationFee[]; charges: SettlementCharge[] }> {
239
238
  const fee = transaction.source as Stripe.ApplicationFee;
240
239
  const payingAccountId = typeof fee.account === 'string' ? fee.account : fee.account.id;
@@ -317,7 +316,7 @@ export class StripeSettlementSync {
317
316
  // An invoiced fee is explained by the derived line of its fee payment instead of by
318
317
  // itself, so the payouts it sits in have to rebuild those lines
319
318
  if (storedFee.balanceItemId && storedFee.settlementId) {
320
- options.invoicedFeeBalanceItemIds?.add(storedFee.balanceItemId);
319
+ options.settledApplicationFeeBalanceItems?.add(storedFee.balanceItemId);
321
320
  }
322
321
  }
323
322
 
@@ -467,12 +466,11 @@ export class StripeSettlementSync {
467
466
  }
468
467
 
469
468
  async #walkPayout(payout: Stripe.Payout, settlement: Settlement, abort: AbortSignal) {
470
- const reported = new ReportedRows();
471
469
  let transactionCount = 0;
472
470
 
473
- // Invoiced fees linked to or unlinked from this settlement during the walk: their fee
474
- // payments' derived lines must follow
475
- const invoicedFeeBalanceItemIds = new Set<string>();
471
+ // Keep track of all balance items linked to (settled) application fees that are created or updated.
472
+ // So we can update the settlement status of the associated payments
473
+ const settledApplicationFeeBalanceItems = new Set<string>();
476
474
 
477
475
  try {
478
476
  for await (const transaction of this.stripe.balanceTransactions.list({
@@ -482,67 +480,51 @@ export class StripeSettlementSync {
482
480
  ? ['data.source', 'data.source.application_fee', 'data.source.application_fee.originating_transaction', 'data.source.charge']
483
481
  : ['data.source', 'data.source.originating_transaction', 'data.source.charge'],
484
482
  })) {
485
- // Between two transactions is a safe point to stop: only a complete walk sweeps
486
- // and marks the settlement synced, so an interrupted one is re-walked from scratch
487
483
  abort.throwIfAborted();
488
484
 
489
485
  transactionCount += 1;
490
- await this.#handleTransaction(transaction, settlement, reported, invoicedFeeBalanceItemIds);
486
+ await this.#handleTransaction(transaction, settlement, settledApplicationFeeBalanceItems);
491
487
  }
492
488
 
493
- // Stripe reported nothing for money that did move: storing that as a complete sync
494
- // would silently hide the whole payout
495
489
  if (transactionCount === 0 && settlement.amount !== 0) {
496
490
  throw new SimpleError({
497
491
  code: 'empty_payout',
498
492
  message: 'Payout ' + payout.id + ' of ' + settlement.amount + ' has no balance transactions',
499
493
  });
500
494
  }
501
-
502
- // Only a complete walk may sweep: it can't tell a row that moved away from one this
503
- // walk never reached
504
- const { unlinkedFees } = await SettlementService.sweepSettlement(settlement, reported);
505
- for (const fee of unlinkedFees) {
506
- if (fee.balanceItemId) {
507
- invoicedFeeBalanceItemIds.add(fee.balanceItemId);
508
- }
509
- }
510
495
  } catch (e) {
511
496
  // The fee payments still follow the fees this walk linked before it broke (a fee may
512
497
  // never sit in a payout that has no line for it), but failing to update them may not
513
498
  // hide what broke the walk
514
- await SettlementService.updatePaymentSettlementsForAccountDeductionBalanceItems([...invoicedFeeBalanceItemIds]).catch(console.error);
499
+ await SettlementService.updatePaymentSettlementsForApplicationFeeBalanceItems([...settledApplicationFeeBalanceItems]).catch(console.error);
515
500
  throw e;
516
501
  }
517
502
 
518
- await SettlementService.updatePaymentSettlementsForAccountDeductionBalanceItems([...invoicedFeeBalanceItemIds]);
503
+ await SettlementService.updatePaymentSettlementsForApplicationFeeBalanceItems([...settledApplicationFeeBalanceItems]);
519
504
  await SettlementService.finishSync(settlement, { transactionCount });
520
505
  }
521
506
 
522
- async #handleTransaction(transaction: Stripe.BalanceTransaction, settlement: Settlement, reported: ReportedRows, invoicedFeeBalanceItemIds: Set<string>) {
507
+ async #handleTransaction(transaction: Stripe.BalanceTransaction, settlement: Settlement, settledApplicationFeeBalanceItems: Set<string>) {
523
508
  const occurredAt = new Date(transaction.created * 1000);
524
509
 
525
- // A plain string switch: the pinned SDK's type union misses some real-world types
526
- // (e.g. network_cost)
527
510
  switch (transaction.type as string) {
528
511
  case 'charge':
529
512
  case 'payment': {
530
513
  const payment = await this.#resolvePayment(transaction);
531
514
 
532
- // A destination charge only passes through our balance on its way to the
533
- // organization: its own payout settles it, ours stays out of it
534
515
  if (payment.organizationId !== settlement.organizationId) {
535
- await this.#storePaidFeesForTransaction(transaction, settlement, reported, { paymentId: null });
516
+ // Destination charge via the platform
517
+ await this.#storePaidFeesForTransaction(transaction, settlement, { paymentId: null });
536
518
  return;
537
519
  }
538
520
 
539
- reported.paymentLine(await SettlementService.upsertPaymentLine(settlement, {
521
+ await SettlementService.upsertPaymentLine(settlement, {
540
522
  paymentId: payment.id,
541
523
  amount: transaction.amount * 100,
542
524
  externalId: transaction.id,
543
525
  occurredAt,
544
- }));
545
- await this.#storePaidFeesForTransaction(transaction, settlement, reported, { paymentId: payment.id });
526
+ });
527
+ await this.#storePaidFeesForTransaction(transaction, settlement, { paymentId: payment.id });
546
528
  await this.#updateTransferFee(transaction, settlement, payment);
547
529
  await SettlementService.updateLegacySettlementReference(payment);
548
530
  return;
@@ -559,30 +541,28 @@ export class StripeSettlementSync {
559
541
  const isReturned = transaction.type === 'refund_failure';
560
542
  const refunded = await this.#resolveRefundedPayment(transaction);
561
543
 
562
- // The reverse of the pass-through above: refunding another organization's payment
563
- // only moves the money back through our balance
564
544
  if (refunded.organizationId !== settlement.organizationId) {
565
- await this.#storePaidFeesForTransaction(transaction, settlement, reported, { paymentId: null });
545
+ // Destination charge via the platform
546
+ await this.#storePaidFeesForTransaction(transaction, settlement, { paymentId: null });
566
547
  return;
567
548
  }
568
549
 
569
550
  const payment = await this.#resolveReversingPayment(transaction, refunded, { negated: isReturned });
570
- reported.paymentLine(await SettlementService.upsertPaymentLine(settlement, {
551
+ await SettlementService.upsertPaymentLine(settlement, {
571
552
  paymentId: payment.id,
572
553
  amount: transaction.amount * 100,
573
554
  externalId: transaction.id,
574
555
  occurredAt,
575
- }));
576
- await this.#storePaidFeesForTransaction(transaction, settlement, reported, { paymentId: payment.id });
556
+ });
557
+ await this.#storePaidFeesForTransaction(transaction, settlement, { paymentId: payment.id });
577
558
  await SettlementService.updateLegacySettlementReference(payment);
578
559
  return;
579
560
  }
580
561
 
581
562
  case 'application_fee': {
582
563
  // The fee rows, now linked to the platform payout that contains them
583
- const { fees } = await this.#handleApplicationFee(transaction, { settlementId: settlement.id, invoicedFeeBalanceItemIds });
584
- reported.applicationFees(fees);
585
- await this.#storePaidFeesForTransaction(transaction, settlement, reported, { paymentId: null });
564
+ await this.#handleApplicationFee(transaction, { settlementId: settlement.id, settledApplicationFeeBalanceItems });
565
+ await this.#storePaidFeesForTransaction(transaction, settlement, { paymentId: null });
586
566
  return;
587
567
  }
588
568
 
@@ -612,7 +592,7 @@ export class StripeSettlementSync {
612
592
  case 'stripe_fee':
613
593
  case 'network_cost':
614
594
  case 'tax_fee': {
615
- const charge = await SettlementService.upsertCharge({
595
+ await SettlementService.upsertCharge({
616
596
  type: transaction.type === 'tax_fee' ? SettlementChargeType.Tax : SettlementChargeType.ProviderAccountFee,
617
597
  externalId: transaction.id,
618
598
  amount: transaction.amount * 100,
@@ -622,7 +602,6 @@ export class StripeSettlementSync {
622
602
  description: transaction.description ?? '',
623
603
  occurredAt,
624
604
  });
625
- reported.charge(charge);
626
605
  return;
627
606
  }
628
607
 
@@ -630,7 +609,7 @@ export class StripeSettlementSync {
630
609
  case 'reserved_funds':
631
610
  case 'reserve_hold':
632
611
  case 'reserve_release': {
633
- const charge = await SettlementService.upsertCharge({
612
+ await SettlementService.upsertCharge({
634
613
  type: SettlementChargeType.Reserve,
635
614
  externalId: transaction.id,
636
615
  amount: transaction.amount * 100,
@@ -639,14 +618,13 @@ export class StripeSettlementSync {
639
618
  description: transaction.description ?? '',
640
619
  occurredAt,
641
620
  });
642
- reported.charge(charge);
643
621
  return;
644
622
  }
645
623
 
646
624
  case 'adjustment':
647
625
  case 'payment_reversal': {
648
626
  const paymentId = await this.#tryResolveAdjustmentPayment(transaction, settlement);
649
- const charge = await SettlementService.upsertCharge({
627
+ await SettlementService.upsertCharge({
650
628
  type: SettlementChargeType.Adjustment,
651
629
  externalId: transaction.id,
652
630
  amount: transaction.amount * 100,
@@ -657,8 +635,7 @@ export class StripeSettlementSync {
657
635
  description: transaction.description ?? '',
658
636
  occurredAt,
659
637
  });
660
- reported.charge(charge);
661
- await this.#storePaidFeesForTransaction(transaction, settlement, reported, { paymentId });
638
+ await this.#storePaidFeesForTransaction(transaction, settlement, { paymentId });
662
639
  return;
663
640
  }
664
641
 
@@ -672,7 +649,7 @@ export class StripeSettlementSync {
672
649
  case 'connect_collection_transfer':
673
650
  case 'stripe_balance_payment_debit':
674
651
  case 'stripe_balance_payment_debit_reversal': {
675
- const charge = await SettlementService.upsertCharge({
652
+ await SettlementService.upsertCharge({
676
653
  type: SettlementChargeType.BalanceMovement,
677
654
  externalId: transaction.id,
678
655
  amount: transaction.amount * 100,
@@ -681,8 +658,7 @@ export class StripeSettlementSync {
681
658
  description: transaction.description ?? transaction.type,
682
659
  occurredAt,
683
660
  });
684
- reported.charge(charge);
685
- await this.#storePaidFeesForTransaction(transaction, settlement, reported, { paymentId: null });
661
+ await this.#storePaidFeesForTransaction(transaction, settlement, { paymentId: null });
686
662
  return;
687
663
  }
688
664
 
@@ -703,7 +679,7 @@ export class StripeSettlementSync {
703
679
  * connected account also the application fee we charged. The amounts always come from the
704
680
  * balance transaction itself.
705
681
  */
706
- async #storePaidFeesForTransaction(transaction: Stripe.BalanceTransaction, settlement: Settlement, reported: ReportedRows, { paymentId }: { paymentId: string | null }) {
682
+ async #storePaidFeesForTransaction(transaction: Stripe.BalanceTransaction, settlement: Settlement, { paymentId }: { paymentId: string | null }) {
707
683
  const occurredAt = new Date(transaction.created * 1000);
708
684
 
709
685
  for (const [index, detail] of (transaction.fee_details ?? []).entries()) {
@@ -712,7 +688,7 @@ export class StripeSettlementSync {
712
688
  }
713
689
 
714
690
  if (detail.type === 'application_fee') {
715
- await this.#storePaidApplicationFeeForTransaction(transaction, detail, settlement, reported, { paymentId });
691
+ await this.#storePaidApplicationFeeForTransaction(transaction, detail, settlement, { paymentId });
716
692
  continue;
717
693
  }
718
694
 
@@ -729,7 +705,6 @@ export class StripeSettlementSync {
729
705
  description: detail.description ?? '',
730
706
  occurredAt,
731
707
  });
732
- reported.charge(charge);
733
708
  }
734
709
  }
735
710
 
@@ -740,7 +715,7 @@ export class StripeSettlementSync {
740
715
  * applicationFeeId both sides of one kind sum to zero. This walk fills their settlementId; the
741
716
  * rows themselves usually already exist (created by the fee walk).
742
717
  */
743
- async #storePaidApplicationFeeForTransaction(transaction: Stripe.BalanceTransaction, detail: Stripe.BalanceTransaction.FeeDetail, settlement: Settlement, reported: ReportedRows, { paymentId }: { paymentId: string | null }) {
718
+ async #storePaidApplicationFeeForTransaction(transaction: Stripe.BalanceTransaction, detail: Stripe.BalanceTransaction.FeeDetail, settlement: Settlement, { paymentId }: { paymentId: string | null }) {
744
719
  if (!this.stripeAccount) {
745
720
  throw new SimpleError({
746
721
  code: 'unexpected_application_fee_detail',
@@ -803,7 +778,6 @@ export class StripeSettlementSync {
803
778
  stripeAccountId: this.stripeAccount.id,
804
779
  occurredAt,
805
780
  });
806
- reported.charge(charge);
807
781
 
808
782
  // What the organization pays here is what we receive on the other side. The two are
809
783
  // written from different Stripe transactions, so a divergence would silently bill the
@@ -3,7 +3,6 @@ import { isSimpleError, isSimpleErrors, SimpleError } from '@simonbackx/simple-e
3
3
  import type { Company } from '@stamhoofd/structures';
4
4
  import { PeppolScheme } from '@stamhoofd/structures';
5
5
  import { Country } from '@stamhoofd/types/Country';
6
- import axios from 'axios';
7
6
  import jsvat from 'jsvat-next';
8
7
  import { PeppolDirectoryService } from '../services/PeppolDirectoryService.js';
9
8
 
@@ -15,17 +14,25 @@ export class ViesHelperStatic {
15
14
 
16
15
  console.log('[VIES REQUEST]', method, url, content ? '\n [VIES REQUEST] ' : undefined, json);
17
16
 
18
- const response = await axios.request({
17
+ const response = await fetch(url, {
19
18
  method,
20
- url,
21
19
  headers: {
22
20
  'Content-Type': json.length > 0 ? 'application/json' : 'text/plain',
23
21
  },
24
- data: json,
25
-
22
+ body: json.length > 0 ? json : undefined,
23
+ signal: AbortSignal.timeout(5_000),
26
24
  });
27
- console.log('[VIES RESPONSE]', method, url, '\n[VIES RESPONSE]', JSON.stringify(response.data));
28
- return response.data;
25
+
26
+ if (!response.ok) {
27
+ throw new Error(`VIES request failed with status ${response.status}`);
28
+ }
29
+
30
+ const data = await response.json();
31
+ console.log('[VIES RESPONSE]', method, url, '\n[VIES RESPONSE]', JSON.stringify(data));
32
+ return {
33
+ data,
34
+ response,
35
+ };
29
36
  }
30
37
 
31
38
  async checkCompany(company: Company, patch: AutoEncoderPatchType<Company> | Company) {
@@ -177,17 +184,17 @@ export class ViesHelperStatic {
177
184
 
178
185
  try {
179
186
  const cleaned = formatted.substring(2).replace(/(?:\.-\s)+/g, '');
180
- const response = await this.request('POST', 'https://ec.europa.eu/taxation_customs/vies/rest-api/check-vat-number', {
187
+ const { data, response } = await this.request('POST', 'https://ec.europa.eu/taxation_customs/vies/rest-api/check-vat-number', {
181
188
  countryCode: country,
182
189
  vatNumber: cleaned,
183
190
  });
184
191
 
185
- if (typeof response !== 'object' || response === null || typeof response.valid !== 'boolean') {
186
- // APi error
192
+ if (typeof data !== 'object' || data === null || typeof data.valid !== 'boolean') {
193
+ console.error('VIES error', response.status, response.statusText, data);
187
194
  throw new Error('Invalid response from VIES');
188
195
  }
189
196
 
190
- if (!response.valid) {
197
+ if (!data.valid) {
191
198
  throw new SimpleError({
192
199
  code: 'invalid_field',
193
200
  message: $t('%1TG', { 'vat-number': formatted }),
@@ -14,7 +14,7 @@ import { fetchToAsyncIterator } from './fetchToAsyncIterator.js';
14
14
  * They are read page by page and added up right away, so they are never all in memory at once. Above
15
15
  * this many objects a breakdown takes too long to wait for, so we ask the user to narrow down instead.
16
16
  */
17
- export const MAX_BREAKDOWN_OBJECTS = 10000;
17
+ export const MAX_BREAKDOWN_OBJECTS = 50_000;
18
18
 
19
19
  const PAGE_SIZE = 100;
20
20
 
@@ -9,7 +9,7 @@ import { BalanceItemStatus, BalanceItemType, PaymentMethod, PaymentProvider, Pay
9
9
  import { ApplicationFeeType } from '@stamhoofd/structures/settlements/ApplicationFeeType.js';
10
10
  import { SettlementChargeType } from '@stamhoofd/structures/settlements/SettlementChargeType.js';
11
11
  import { v4 as uuidv4 } from 'uuid';
12
- import { ReportedRows, SettlementService } from './SettlementService.js';
12
+ import { SettlementService } from './SettlementService.js';
13
13
 
14
14
  describe('SettlementService', () => {
15
15
  let organization: Organization;
@@ -272,79 +272,7 @@ describe('SettlementService', () => {
272
272
  });
273
273
  });
274
274
 
275
- describe('sweepSettlement', () => {
276
- test('deletes payout-only rows, but unlinks what outlives the payout', async () => {
277
- const payment = await createPayment();
278
- const settlement = await SettlementService.upsertSettlement(settlementData());
279
-
280
- const keptLine = await SettlementService.upsertPaymentLine(settlement, {
281
- paymentId: payment.id, amount: 50_00_00, externalId: 'txn_kept', occurredAt: new Date(2026, 0, 14),
282
- });
283
- const movedLine = await SettlementService.upsertPaymentLine(settlement, {
284
- paymentId: payment.id, amount: 10_00_00, externalId: 'txn_moved', occurredAt: new Date(2026, 0, 14),
285
- });
286
-
287
- // A derived fee line is never reported by a walk: it belongs to the fee payment
288
- const derivedLine = await SettlementService.upsertPaymentLine(settlement, {
289
- paymentId: payment.id, amount: 2_00_00, externalId: null, occurredAt: new Date(2026, 0, 14),
290
- });
291
-
292
- const { fee, charge: referencedCharge } = await createApplicationFee({ settlement });
293
- const providerFee = await SettlementService.upsertCharge({
294
- type: SettlementChargeType.ProviderTransactionFee,
295
- externalId: 'txn_moved:fee:0',
296
- amount: -30_00,
297
- settlementId: settlement.id,
298
- organizationId: organization.id,
299
- occurredAt: new Date(2026, 0, 14),
300
- });
301
- const keptFee = await SettlementService.upsertCharge({
302
- type: SettlementChargeType.ProviderTransactionFee,
303
- externalId: 'txn_kept:fee:0',
304
- amount: -25_00,
305
- settlementId: settlement.id,
306
- organizationId: organization.id,
307
- occurredAt: new Date(2026, 0, 14),
308
- });
309
-
310
- // The deduction charge is linked to this settlement too, but no longer reported
311
- referencedCharge.settlementId = settlement.id;
312
- await referencedCharge.save();
313
-
314
- const reported = new ReportedRows();
315
- reported.paymentLine(keptLine);
316
- reported.charge(keptFee);
317
- const { unlinkedFees } = await SettlementService.sweepSettlement(settlement, reported);
318
-
319
- expect(await PaymentSettlement.getByID(keptLine.id)).toBeDefined();
320
- expect(await PaymentSettlement.getByID(movedLine.id)).toBeUndefined();
321
- expect(await PaymentSettlement.getByID(derivedLine.id)).toBeDefined();
322
- expect(await SettlementCharge.getByID(providerFee.id)).toBeUndefined();
323
- expect((await SettlementCharge.getByID(keptFee.id))?.settlementId).toBe(settlement.id);
324
-
325
- // A charge an application fee points at may never be deleted (foreign key), only unlinked
326
- const unlinkedCharge = await SettlementCharge.getByID(referencedCharge.id);
327
- expect(unlinkedCharge).toBeDefined();
328
- expect(unlinkedCharge!.settlementId).toBe(null);
329
-
330
- expect(unlinkedFees.map(f => f.id)).toEqual([fee.id]);
331
- expect((await ApplicationFee.getByID(fee.id))!.settlementId).toBe(null);
332
- });
333
-
334
- test('keeps the application fees the walk reported', async () => {
335
- const settlement = await SettlementService.upsertSettlement(settlementData());
336
- const { fee } = await createApplicationFee({ settlement });
337
-
338
- const reported = new ReportedRows();
339
- reported.applicationFee(fee);
340
- const { unlinkedFees } = await SettlementService.sweepSettlement(settlement, reported);
341
-
342
- expect(unlinkedFees).toHaveLength(0);
343
- expect((await ApplicationFee.getByID(fee.id))!.settlementId).toBe(settlement.id);
344
- });
345
- });
346
-
347
- describe('updatePaymentSettlementsForAccountDeductionPayment', () => {
275
+ describe('updatePaymentSettlementsForApplicationFeePayment', () => {
348
276
  test('one line per payout, summing the fees it contained', async () => {
349
277
  const { payment, balanceItem } = await createFeePayment(3_25_00);
350
278
  const first = await SettlementService.upsertSettlement(settlementData({ settledAt: new Date(2026, 0, 10) }));
@@ -357,7 +285,7 @@ describe('SettlementService', () => {
357
285
  // A fee that isn't paid out yet doesn't produce a line
358
286
  const { fee: pending } = await createApplicationFee({ balanceItemId: balanceItem.id, amount: 25_00 });
359
287
 
360
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
288
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
361
289
 
362
290
  const lines = await PaymentSettlement.select().where('paymentId', payment.id).fetch();
363
291
  expect(lines).toHaveLength(2);
@@ -374,7 +302,7 @@ describe('SettlementService', () => {
374
302
  // Paying out the last fee completes the payment
375
303
  pending.settlementId = second.id;
376
304
  await pending.save();
377
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
305
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
378
306
 
379
307
  const completed = await PaymentSettlement.select().where('paymentId', payment.id).fetch();
380
308
  expect(completed.reduce((total, line) => total + line.amount, 0)).toBe(payment.price);
@@ -387,10 +315,10 @@ describe('SettlementService', () => {
387
315
  await createApplicationFee({ settlement, balanceItemId: first.balanceItem.id, amount: 1_00_00 });
388
316
  await createApplicationFee({ settlement, balanceItemId: second.balanceItem.id, amount: 2_00_00 });
389
317
 
390
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(first.payment);
391
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(second.payment);
318
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(first.payment);
319
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(second.payment);
392
320
  // Re-running may not duplicate: the lines have no externalId to upsert on
393
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(first.payment);
321
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(first.payment);
394
322
 
395
323
  const lines = await PaymentSettlement.select().where('settlementId', settlement.id).fetch();
396
324
  expect(lines).toHaveLength(2);
@@ -403,19 +331,19 @@ describe('SettlementService', () => {
403
331
  const settlement = await SettlementService.upsertSettlement(settlementData());
404
332
  const { fee } = await createApplicationFee({ settlement, balanceItemId: balanceItem.id, amount: 1_00_00 });
405
333
 
406
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
334
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
407
335
  expect(await PaymentSettlement.select().where('paymentId', payment.id).count()).toBe(1);
408
336
 
409
337
  fee.settlementId = null;
410
338
  await fee.save();
411
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
339
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
412
340
 
413
341
  expect(await PaymentSettlement.select().where('paymentId', payment.id).count()).toBe(0);
414
342
  });
415
343
 
416
344
  test('other payment methods are left alone', async () => {
417
345
  const payment = await createPayment();
418
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
346
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
419
347
  expect(await PaymentSettlement.select().where('paymentId', payment.id).count()).toBe(0);
420
348
  });
421
349
  });
@@ -464,7 +392,7 @@ describe('SettlementService', () => {
464
392
  const { payment, balanceItem } = await createFeePayment(1_00_00);
465
393
  fee.balanceItemId = balanceItem.id;
466
394
  await fee.save();
467
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
395
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
468
396
 
469
397
  const invoiced = await Settlement.getByID(settlement.id);
470
398
  expect(invoiced!.pendingFees).toBe(0);
@@ -476,7 +404,7 @@ describe('SettlementService', () => {
476
404
  const { payment, balanceItem } = await createFeePayment(1_00_00);
477
405
  const { fee } = await createApplicationFee({ settlement, balanceItemId: balanceItem.id, amount: 1_00_00 });
478
406
 
479
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
407
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
480
408
  await SettlementService.finishSync(settlement, { transactionCount: 1 });
481
409
  expect(settlement.pendingFees).toBe(0);
482
410
  expect(settlement.unexplainedAmount).toBe(0);
@@ -484,7 +412,7 @@ describe('SettlementService', () => {
484
412
  // The payout no longer contains the fee: its line goes, and so does what it explained
485
413
  fee.settlementId = null;
486
414
  await fee.save();
487
- await SettlementService.updatePaymentSettlementsForAccountDeductionPayment(payment);
415
+ await SettlementService.updatePaymentSettlementsForApplicationFeePayment(payment);
488
416
 
489
417
  const unlinked = await Settlement.getByID(settlement.id);
490
418
  expect(unlinked!.pendingFees).toBe(0);