From a56226d6acb5c5d4f43bf0040fa8d388ce3e6b2d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:33:22 +0000 Subject: [PATCH 1/2] Move the arrival wizard's payment choice into the util Which payment methods the wizard offers (the enabled ones, the card terminal only for local sign-ins, invoice only with recipients) and whether it asks for payment at all (a fee, not a home-base aircraft unless homebasePayment) were written inline in ArrivalFinishContainer and Finish. They are now getSelectablePaymentMethods and isPaymentDue in src/util/paymentMethods.ts, so the movement API can be held to the same rules by a parity test. No change in behaviour. --- .../wizards/ArrivalWizard/Finish/Finish.tsx | 3 ++- src/containers/ArrivalFinishContainer.tsx | 11 +++++------ src/util/paymentMethods.ts | 13 +++++++++++++ 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/components/wizards/ArrivalWizard/Finish/Finish.tsx b/src/components/wizards/ArrivalWizard/Finish/Finish.tsx index 5b9fc271..9f4a9ed5 100644 --- a/src/components/wizards/ArrivalWizard/Finish/Finish.tsx +++ b/src/components/wizards/ArrivalWizard/Finish/Finish.tsx @@ -8,6 +8,7 @@ import Heading from './Heading'; import {ReferenceNumberMessage} from './Message'; import FinishActions from './FinishActions' import PaymentMethodImport from '../../../../containers/PaymentMethodContainer' +import {isPaymentDue} from '../../../../util/paymentMethods' const PaymentMethod = PaymentMethodImport as any import {HeadingType} from '../../MovementWizard' import Fees from './Fees' @@ -46,7 +47,7 @@ const Finish = props => { ? t('arrival.created') : undefined; - const showPayment = (isHomeBase === false || __CONF__.homebasePayment) && !isUpdate && !!fees && fees.totalGross > 0 + const showPayment = !isUpdate && !!fees && isPaymentDue(isHomeBase, __CONF__.homebasePayment === true, fees.totalGross) const { landings, diff --git a/src/containers/ArrivalFinishContainer.tsx b/src/containers/ArrivalFinishContainer.tsx index 8f3d9507..67e3397f 100644 --- a/src/containers/ArrivalFinishContainer.tsx +++ b/src/containers/ArrivalFinishContainer.tsx @@ -7,7 +7,7 @@ import {saveMovement} from '../modules/movements'; import Finish, {FinishLoading} from '../components/wizards/ArrivalWizard/Finish'; import {HeadingType} from '../components/wizards/MovementWizard'; import objectToArray from '../util/objectToArray'; -import {getEnabledPaymentMethods} from '../util/paymentMethods'; +import {getSelectablePaymentMethods} from '../util/paymentMethods'; import {RootState} from '../modules'; interface Fees { @@ -73,12 +73,11 @@ const ArrivalFinishContainer = (props: Props) => { return ; } - const enabledPaymentMethods = getEnabledPaymentMethods( + const enabledPaymentMethods = getSelectablePaymentMethods( objectToArray(__CONF__.paymentMethods), - auth.data, - ) - .filter((method: string) => method === 'card' ? localUser : true) - .filter((method: string) => method === 'invoice' ? invoiceRecipients.length > 0 : true); + {...auth.data, local: !!localUser}, + invoiceRecipients, + ); const isHomeBase = (aircraftSettings.club as any)[immatriculation] === true || diff --git a/src/util/paymentMethods.ts b/src/util/paymentMethods.ts index 9ea3a4f2..d24a3c0f 100644 --- a/src/util/paymentMethods.ts +++ b/src/util/paymentMethods.ts @@ -16,6 +16,19 @@ export const getEnabledPaymentMethods = (paymentMethods, auth) => paymentMethods .filter(method => method.authCondition ? AUTH_CONDITIONS[method.authCondition](auth) : true) .map(method => typeof method === 'string' ? method : method.name) +// What the arrival wizard offers a user: the enabled methods, the card +// terminal only for local sign-ins, invoice only with invoice recipients. +// The movement API offers the same (functions/movements/domain/paymentOptions.js). +export const getSelectablePaymentMethods = (paymentMethods, auth, invoiceRecipients: string[]) => + getEnabledPaymentMethods(paymentMethods, auth) + .filter((method: string) => method === 'card' ? auth.local === true : true) + .filter((method: string) => method === 'invoice' ? invoiceRecipients.length > 0 : true) + +// Whether the arrival wizard asks for payment: a fee is due and the aircraft +// is not a home-base or club aircraft, unless homebasePayment. +export const isPaymentDue = (isHomeBase: boolean, homebasePayment: boolean, totalGross?: number) => + (isHomeBase === false || homebasePayment === true) && !!totalGross && totalGross > 0 + export const getLabel = (value, t: (key: string) => string) => { const method = PAYMENT_METHODS.find(method => method.value === value.method) From e82cda55798ec41bb586dc993885503ae20dcf0f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 21 Nov 2026 08:33:22 +0000 Subject: [PATCH 2/2] Pay the landing fee through the app API GET/POST /app/movements/arrivals/:key/payment (also under /api, scope movements:write for central login tokens): how the caller may pay the landing fee of an arrival, and paying it, for API clients such as the Open Digital MCP hub. - domain/paymentOptions.js offers exactly what the arrival wizard offers (parity spec against src/util/paymentMethods.ts for every project and kind of user): payment when a fee is due and the aircraft is not home-based unless homebasePayment; the configured methods whose authCondition holds, the card terminal only for local sign-ins, invoice once per recipient listing the caller's e-mail - the server config and policy carry paymentMethods and homebasePayment (with client __CONF__ parity) - application/payArrival.js records the method through saveMovement (ownership, lock); for checkout it then pushes the /card-payments entry the app writes (amount: the arrival's fee in cents) as the caller and waits for the payment service's checkout URL; updateArrivalPaymentStatus marks the arrival paid as for the app - emulator test against the lsze rules: card payment and method accepted for a login caller, denied on another pilot's arrival --- functions/api/index.spec.js | 5 +- .../adapters/rtdbMovementRepository.js | 55 +++++++- .../adapters/rtdbMovementRepository.spec.js | 42 ++++++ functions/movements/application/payArrival.js | 106 +++++++++++++++ .../movements/application/payArrival.spec.js | 105 +++++++++++++++ functions/movements/domain/paymentOptions.js | 122 ++++++++++++++++++ .../movements/domain/paymentOptions.spec.js | 69 ++++++++++ functions/movements/domain/policy.js | 7 +- functions/movements/domain/policy.spec.js | 11 ++ functions/movements/http/movementRoutes.js | 71 +++++++++- .../movements/http/movementRoutes.spec.js | 44 +++++++ package.json | 2 +- projects/Configuration.md | 12 ++ src/util/paymentOptions.parity.spec.js | 62 +++++++++ tasks/generateServerConfig.js | 28 ++++ tasks/generateServerConfig.spec.js | 4 + test/rules/movementApiPayment.rules.js | 121 +++++++++++++++++ 17 files changed, 860 insertions(+), 6 deletions(-) create mode 100644 functions/movements/application/payArrival.js create mode 100644 functions/movements/application/payArrival.spec.js create mode 100644 functions/movements/domain/paymentOptions.js create mode 100644 functions/movements/domain/paymentOptions.spec.js create mode 100644 src/util/paymentOptions.parity.spec.js create mode 100644 test/rules/movementApiPayment.rules.js diff --git a/functions/api/index.spec.js b/functions/api/index.spec.js index 52864bf3..c38906b3 100644 --- a/functions/api/index.spec.js +++ b/functions/api/index.spec.js @@ -142,10 +142,13 @@ describe('functions', () => { [['post'], ['/app/movements/:type', '/api/app/movements/:type']], [['patch'], ['/app/movements/:type/:key', '/api/app/movements/:type/:key']], [['get'], ['/app/movements', '/api/app/movements']], + [['get'], ['/app/movements/arrivals/:key/payment', '/api/app/movements/arrivals/:key/payment']], + [['post'], ['/app/movements/arrivals/:key/payment', '/api/app/movements/arrivals/:key/payment']], ]); // Writes: requestId, appAuth, requireScope, JSON body, handler; the // list: requestId, appAuth, requireScope, handler. - expect(movementLayers.map(layer => layer.route.stack.length)).toEqual([5, 5, 4]); + // Payment: requestId, appAuth, requireScope, (JSON body,) handler. + expect(movementLayers.map(layer => layer.route.stack.length)).toEqual([5, 5, 4, 4, 5]); }); it('lets admins manage API keys when the tenant has an API feature', () => { diff --git a/functions/movements/adapters/rtdbMovementRepository.js b/functions/movements/adapters/rtdbMovementRepository.js index fddb6f4f..12393fb7 100644 --- a/functions/movements/adapters/rtdbMovementRepository.js +++ b/functions/movements/adapters/rtdbMovementRepository.js @@ -3,6 +3,7 @@ const { getDatabase } = require('firebase-admin/database'); const { createDatabaseRestClient } = require('./databaseRest'); const { toOrderKey } = require('../domain/orderKey'); +const fetchUserInvoiceRecipients = require('../../api/fetchUserInvoiceRecipients'); // Realtime Database implementation of the movement repository port (see // functions/movements/application/saveMovement.js). @@ -71,8 +72,60 @@ const byNewest = (a, b) => (a[1].negativeTimestamp ?? 0) - (b[1].negativeTimesta // for callers of the central login. const defaultAuth = () => require('firebase-admin/auth').getAuth(); -function createRtdbMovementRepository({ db = getDatabase, auth = defaultAuth, rest = createDatabaseRestClient() } = {}) { +const defaultSleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + +function createRtdbMovementRepository({ + db = getDatabase, auth = defaultAuth, rest = createDatabaseRestClient(), sleep = defaultSleep, +} = {}) { return { + /** + * What decides how the actor may pay an arrival (domain/paymentOptions.js): + * {invoiceRecipientNames, isHomeBase}: the invoice recipients the actor's + * e-mail is listed for (as the app's /users/me/invoice-recipients) and + * whether the aircraft is a club or home-base aircraft (/settings/aircrafts). + */ + async loadPaymentFacts(actor, arrival) { + const database = db(); + const [invoiceRecipientNames, club, homeBase] = await Promise.all([ + fetchUserInvoiceRecipients(database, actor.email), + readValue(database, 'settings/aircrafts/club'), + readValue(database, 'settings/aircrafts/homeBase'), + ]); + const registration = arrival.immatriculation; + const isHomeBase = typeof registration === 'string' + && ((club || {})[registration] === true || (homeBase || {})[registration] === true); + return { invoiceRecipientNames, isHomeBase }; + }, + + // push() of an online payment to /card-payments as the actor; the key. + async createCardPayment(payment, actor) { + const answer = await rest.write('POST', 'card-payments', payment, authOverrideFor(actor)); + if (!answer || typeof answer.name !== 'string') { + throw new Error('Database answered a push without the new key'); + } + return answer.name; + }, + + /** + * Waits for the payment service's answer to an online payment: + * {url} (the checkout page), {failed: true}, or {pending: true} after + * `timeoutMs`. + */ + async waitForCheckout(paymentId, { timeoutMs = 10000, intervalMs = 500 } = {}) { + const database = db(); + for (let waited = 0; waited <= timeoutMs; waited += intervalMs) { + const payment = await readValue(database, `card-payments/${paymentId}`); + if (payment && typeof payment.data === 'string' && payment.data !== '') { + return { url: payment.data }; + } + if (payment && payment.status === 'failure') { + return { failed: true }; + } + await sleep(intervalMs); + } + return { pending: true }; + }, + /** * What decides which movements the actor may list (domain/readAccess.js): * {appUid, admin, allMovements}. appUid: the actor's Firebase uid; for a diff --git a/functions/movements/adapters/rtdbMovementRepository.spec.js b/functions/movements/adapters/rtdbMovementRepository.spec.js index a4b3f726..21ccbe81 100644 --- a/functions/movements/adapters/rtdbMovementRepository.spec.js +++ b/functions/movements/adapters/rtdbMovementRepository.spec.js @@ -192,5 +192,47 @@ describe('functions', () => { expect(await repository.listMovements('arrival', { fromMs: 0, toMs: 1, owner: null, limit: 1 }, { uid: 'u', email: null })).toEqual([]); }); }); + + describe('payments', () => { + it('loads the invoice recipients of the actor and whether the aircraft is home-based', async () => { + const repository = createRtdbMovementRepository({ + db: () => fakeDb({ + '/settings/invoiceRecipients': [{ name: 'Fluggruppe A', emails: ['pilot@example.com'] }, { name: 'Firma B', emails: ['x@example.com'] }], + 'settings/aircrafts/club': { HBKOF: true }, + 'settings/aircrafts/homeBase': { HBPIV: true }, + }), + rest: {}, + }); + + expect(await repository.loadPaymentFacts(PILOT, { immatriculation: 'HBPIV' })) + .toEqual({ invoiceRecipientNames: ['Fluggruppe A'], isHomeBase: true }); + expect(await repository.loadPaymentFacts({ uid: 'guest', email: null }, { immatriculation: 'HBXYZ' })) + .toEqual({ invoiceRecipientNames: [], isHomeBase: false }); + }); + + it('pushes the card payment as the actor', async () => { + const rest = { write: jest.fn(async () => ({ name: '-Npay1' })) }; + const repository = createRtdbMovementRepository({ db: () => fakeDb({}), rest }); + + expect(await repository.createCardPayment({ amount: 3000 }, PILOT)).toBe('-Npay1'); + expect(rest.write).toHaveBeenCalledWith('POST', 'card-payments', { amount: 3000 }, { uid: 'pilot-uid', token: { email: 'pilot@example.com' } }); + }); + + it('waits for the checkout URL or a failure of the payment service', async () => { + const answers = [{ status: 'pending' }, { status: 'pending', data: 'https://pay.example.com/c/1' }]; + const db = { ref: jest.fn(() => ({ once: async () => ({ val: () => answers.shift() ?? null }) })) }; + const sleep = jest.fn(async () => undefined); + const repository = createRtdbMovementRepository({ db: () => db, rest: {}, sleep }); + + expect(await repository.waitForCheckout('-Npay1')).toEqual({ url: 'https://pay.example.com/c/1' }); + expect(db.ref).toHaveBeenCalledWith('card-payments/-Npay1'); + expect(sleep).toHaveBeenCalledTimes(1); + + const failing = createRtdbMovementRepository({ db: () => fakeDb({ 'card-payments/p2': { status: 'failure' } }), rest: {}, sleep }); + expect(await failing.waitForCheckout('p2')).toEqual({ failed: true }); + const silent = createRtdbMovementRepository({ db: () => fakeDb({}), rest: {}, sleep }); + expect(await silent.waitForCheckout('p3', { timeoutMs: 1000, intervalMs: 500 })).toEqual({ pending: true }); + }); + }); }); }); diff --git a/functions/movements/application/payArrival.js b/functions/movements/application/payArrival.js new file mode 100644 index 00000000..3d9331e7 --- /dev/null +++ b/functions/movements/application/payArrival.js @@ -0,0 +1,106 @@ +'use strict'; + +const { CODES, REASONS } = require('../domain'); +const { isOwnMovement } = require('../domain/readView'); +const { checkoutPayment, paymentCaller, paymentOptions } = require('../domain/paymentOptions'); +const { saveMovement } = require('./saveMovement'); + +// Use cases: how the caller may pay the landing fee of an arrival, and +// paying it, offering exactly what the app's arrival wizard offers +// (domain/paymentOptions.js). Cash, terminal and TWINT on site and invoice +// only record the method, as the app does; an online payment also writes +// the /card-payments entry the payment service answers with the checkout +// URL, and updateArrivalPaymentStatus.js marks the arrival paid afterwards. +// +// Repository port (adapters/rtdbMovementRepository.js), besides saveMovement's: +// loadPaymentFacts(actor, arrival) -> {invoiceRecipientNames, isHomeBase} +// createCardPayment(payment, actor) -> key +// waitForCheckout(paymentId) -> {url} | {failed} | {pending} +// +// Results: {ok: true, ...} or {ok: false, code, reason}. + +// Where Flightbox prices arrivals on the server (computeArrivalFeesOnWrite), +// the fee lands just after the write: wait for it this long. +const FEE_WAIT = Object.freeze({ attempts: 6, intervalMs: 500 }); + +const reject = (code, reason) => ({ ok: false, code, reason }); + +async function loadPayment({ repository, policy, actor, key, sleep }) { + let arrival = await repository.findMovement('arrival', key); + if (arrival === null) { + return { rejection: reject(REASONS.NOT_FOUND, REASONS.NOT_FOUND) }; + } + // Like the app: the pilot's own arrivals; admins any. + if (actor.isAdmin !== true && !isOwnMovement(arrival, actor.email)) { + return { rejection: reject(CODES.PERMISSION_DENIED, REASONS.NOT_OWNER) }; + } + for (let attempt = 0; typeof arrival.feeTotalGross !== 'number' && attempt < FEE_WAIT.attempts; attempt++) { + await sleep(FEE_WAIT.intervalMs); + arrival = (await repository.findMovement('arrival', key)) || arrival; + } + const facts = await repository.loadPaymentFacts(actor, arrival); + const payment = paymentOptions({ + arrival, + policy, + caller: paymentCaller(actor), + isHomeBase: facts.isHomeBase, + invoiceRecipientNames: facts.invoiceRecipientNames, + }); + return { arrival, payment }; +} + +const defaultSleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + +/** {ok: true, due, amount, currency, options, state} or a rejection. */ +async function getArrivalPayment({ repository, policy, actor, key, sleep = defaultSleep }) { + const loaded = await loadPayment({ repository, policy, actor, key, sleep }); + return loaded.rejection || { ok: true, ...loaded.payment }; +} + +/** + * choice: {method, invoiceRecipientName?}, one of the offered options. + * Resolves with {ok: true, method, checkoutUrl?} (checkoutUrl null when the + * payment service has not answered in time) or a rejection. + */ +async function payArrival({ repository, policy, actor, key, choice, now = Date.now, sleep = defaultSleep }) { + const loaded = await loadPayment({ repository, policy, actor, key, sleep }); + if (loaded.rejection) { + return loaded.rejection; + } + const { arrival, payment } = loaded; + if (payment.state !== 'open' && payment.state !== 'pending') { + return reject(CODES.FAILED_PRECONDITION, 'already-paid'); + } + if (!payment.due) { + return reject(CODES.FAILED_PRECONDITION, 'no-payment-due'); + } + const offered = payment.options.find(option => option.method === choice.method + && (option.method !== 'invoice' || option.invoiceRecipientName === choice.invoiceRecipientName)); + if (!offered) { + return reject('invalid-argument', 'method-not-offered'); + } + + const paymentMethod = { method: offered.method }; + if (offered.method === 'invoice') { + paymentMethod.invoiceRecipientName = offered.invoiceRecipientName; + } else if (offered.method === 'checkout') { + paymentMethod.status = 'pending'; + } + // Through the movement write: ownership, lock and validation as for any change. + const saved = await saveMovement({ repository, policy, actor, type: 'arrival', key, input: { paymentMethod } }); + if (!saved.ok) { + return reject(saved.code, saved.reason || 'invalid'); + } + if (offered.method !== 'checkout') { + return { ok: true, method: offered.method, ...(offered.invoiceRecipientName ? { invoiceRecipientName: offered.invoiceRecipientName } : {}) }; + } + + const paymentId = await repository.createCardPayment(checkoutPayment(key, arrival, { owner: actor.uid, now: now() }), actor); + const checkout = await repository.waitForCheckout(paymentId); + if (checkout.failed) { + return reject(CODES.FAILED_PRECONDITION, 'checkout-failed'); + } + return { ok: true, method: 'checkout', checkoutUrl: checkout.url || null }; +} + +module.exports = { getArrivalPayment, payArrival, FEE_WAIT }; diff --git a/functions/movements/application/payArrival.spec.js b/functions/movements/application/payArrival.spec.js new file mode 100644 index 00000000..8a2b0fb8 --- /dev/null +++ b/functions/movements/application/payArrival.spec.js @@ -0,0 +1,105 @@ +'use strict'; + +const { getArrivalPayment, payArrival } = require('./payArrival'); +const { loadVariant } = require('../domain/testing/projectPolicies'); +const { stored } = require('../domain/testing/movementCases'); + +const KEY = '-Nabc123_XYZ-def4567'; +const PILOT = { uid: 'login:s1', email: 'pilot@example.com', isAdmin: false, isGuest: false, isKiosk: false, scopes: ['movements:write'] }; + +function repositoryWith({ arrival, facts = {}, checkout = { url: 'https://pay.example.com/c/1' }, feeLater } = {}) { + let current = arrival; + let reads = 0; + return { + findMovement: jest.fn(async () => { + reads += 1; + if (feeLater && reads > feeLater.after) { + current = { ...current, feeTotalGross: feeLater.fee }; + } + return current; + }), + loadWriteSettings: jest.fn(async () => ({ lockDate: null, lockDateIso: null, customsBaseUrl: null })), + updateMovement: jest.fn(async () => undefined), + loadPaymentFacts: jest.fn(async () => ({ invoiceRecipientNames: [], isHomeBase: false, ...facts })), + createCardPayment: jest.fn(async () => '-Npay1'), + waitForCheckout: jest.fn(async () => checkout), + }; +} + +describe('functions', () => { + describe('movements/application/payArrival', () => { + const { policy } = loadVariant('lsze'); // checkout (notKiosk), card_external (kiosk), invoice; homebasePayment + const arrival = (overrides = {}) => ({ + ...stored('arrival', policy, { createdBy: PILOT.email }), + landingFeeSingle: 27.75, landingFeeTotal: 27.75, feeTotalGross: 30, ...overrides, + }); + const sleep = jest.fn(async () => undefined); + const run = (useCase, repository, props = {}) => + useCase({ repository, policy, actor: PILOT, key: KEY, sleep, now: () => 1700000000000, ...props }); + + beforeEach(() => sleep.mockClear()); + + it('offers the pilot what the app would: online payment, invoice to their recipients', async () => { + const repository = repositoryWith({ arrival: arrival(), facts: { invoiceRecipientNames: ['Fluggruppe A'] } }); + + expect(await run(getArrivalPayment, repository)).toEqual({ + ok: true, due: true, amount: 30, currency: 'CHF', state: 'open', + options: [{ method: 'checkout' }, { method: 'invoice', invoiceRecipientName: 'Fluggruppe A' }], + }); + expect(repository.loadPaymentFacts).toHaveBeenCalledWith(PILOT, expect.objectContaining({ feeTotalGross: 30 })); + }); + + it('waits briefly for the fee the server computes after the write', async () => { + const repository = repositoryWith({ arrival: arrival({ feeTotalGross: undefined }), feeLater: { after: 2, fee: 30 } }); + + expect((await run(getArrivalPayment, repository)).amount).toBe(30); + expect(sleep).toHaveBeenCalledTimes(2); + }); + + it('starts an online payment: method pending, the card payment as the app writes it, the checkout URL', async () => { + const repository = repositoryWith({ arrival: arrival() }); + + expect(await run(payArrival, repository, { choice: { method: 'checkout' } })) + .toEqual({ ok: true, method: 'checkout', checkoutUrl: 'https://pay.example.com/c/1' }); + expect(repository.updateMovement).toHaveBeenCalledWith( + 'arrival', KEY, expect.objectContaining({ paymentMethod: { method: 'checkout', status: 'pending' } }), PILOT); + expect(repository.createCardPayment).toHaveBeenCalledWith(expect.objectContaining({ + amount: 3000, currency: 'CHF', method: 'checkout', arrivalReference: KEY, refNr: '4567', status: 'pending', owner: 'login:s1', + }), PILOT); + // The method is recorded before the payment exists, so a paid payment always finds it pending. + expect(repository.updateMovement.mock.invocationCallOrder[0]).toBeLessThan(repository.createCardPayment.mock.invocationCallOrder[0]); + }); + + it('records an invoice to an offered recipient only', async () => { + const repository = repositoryWith({ arrival: arrival(), facts: { invoiceRecipientNames: ['Fluggruppe A'] } }); + + expect(await run(payArrival, repository, { choice: { method: 'invoice', invoiceRecipientName: 'Fluggruppe A' } })) + .toEqual({ ok: true, method: 'invoice', invoiceRecipientName: 'Fluggruppe A' }); + expect(await run(payArrival, repository, { choice: { method: 'invoice', invoiceRecipientName: 'Fremde AG' } })) + .toEqual({ ok: false, code: 'invalid-argument', reason: 'method-not-offered' }); + expect(await run(payArrival, repository, { choice: { method: 'card_external' } })) + .toEqual({ ok: false, code: 'invalid-argument', reason: 'method-not-offered' }); + expect(repository.createCardPayment).not.toHaveBeenCalled(); + }); + + it('refuses what cannot be paid: another pilot\'s, paid, or nothing due', async () => { + expect(await run(payArrival, repositoryWith({ arrival: arrival({ createdBy: 'other@example.com' }) }), { choice: { method: 'checkout' } })) + .toEqual({ ok: false, code: 'permission-denied', reason: 'not-owner' }); + expect(await run(payArrival, repositoryWith({ arrival: arrival({ paymentMethod: { method: 'invoice', invoiceRecipientName: 'A' } }) }), { choice: { method: 'checkout' } })) + .toEqual({ ok: false, code: 'failed-precondition', reason: 'already-paid' }); + expect(await run(payArrival, repositoryWith({ arrival: arrival({ feeTotalGross: 0 }) }), { choice: { method: 'checkout' } })) + .toEqual({ ok: false, code: 'failed-precondition', reason: 'no-payment-due' }); + expect(await run(payArrival, repositoryWith({ arrival: null }), { choice: { method: 'checkout' } })) + .toEqual({ ok: false, code: 'not-found', reason: 'not-found' }); + }); + + it('lets a pending online payment be started again, and reports a failed or slow one', async () => { + const pending = arrival({ paymentMethod: { method: 'checkout', status: 'pending' } }); + expect((await run(payArrival, repositoryWith({ arrival: pending }), { choice: { method: 'checkout' } })).ok).toBe(true); + expect(await run(payArrival, repositoryWith({ arrival: arrival(), checkout: { failed: true } }), { choice: { method: 'checkout' } })) + .toEqual({ ok: false, code: 'failed-precondition', reason: 'checkout-failed' }); + expect(await run(payArrival, repositoryWith({ arrival: arrival(), checkout: { pending: true } }), { choice: { method: 'checkout' } })) + .toEqual({ ok: true, method: 'checkout', checkoutUrl: null }); + }); + }); +}); diff --git a/functions/movements/domain/paymentOptions.js b/functions/movements/domain/paymentOptions.js new file mode 100644 index 00000000..87793181 --- /dev/null +++ b/functions/movements/domain/paymentOptions.js @@ -0,0 +1,122 @@ +'use strict'; + +const { PAYMENT_METHODS } = require('./validateMovement'); +const { hasOwn, isPlainObject } = require('./normalize'); +// The server's port of the app's reference number (with client parity tests, +// src/util/airstatOracles/referenceNumber.spec.js). +const { getFromItemKey: referenceNumber } = require('../../reports/airstat/referenceNumber'); + +// How a landing fee can be paid, decided exactly as the app's arrival wizard +// does (parity: src/util/paymentOptions.parity.spec.ts): +// - whether to pay at all: a fee is due (feeTotalGross > 0) and the aircraft +// is not a home-base or club aircraft, unless the aerodrome wants those to +// pay too (homebasePayment) (Finish.tsx showPayment); +// - which methods: the aerodrome's paymentMethods whose authCondition holds +// for the caller (getEnabledPaymentMethods), the card terminal only for +// local sign-ins, invoice only to recipients the caller's e-mail is listed +// for (ArrivalFinishContainer.tsx), in the order of the client's +// PAYMENT_METHODS, invoice once per recipient (PaymentMethod.tsx). + +const AUTH_CONDITIONS = Object.freeze({ + kiosk: caller => caller.kiosk === true, + notKiosk: caller => caller.kiosk !== true, +}); + +/** + * The caller as the app's auth data sees it. local: guest and kiosk sessions + * (and, in the app only, a device marked as a local sign-in); a caller of the + * central login is neither. + */ +function paymentCaller(actor) { + const kiosk = actor.isKiosk === true; + return { kiosk, local: kiosk || actor.isGuest === true }; +} + +/** The method names the caller may choose (getEnabledPaymentMethods + container filters). */ +function enabledPaymentMethods(paymentMethods, caller, invoiceRecipientNames) { + return paymentMethods + .filter(method => !method.authCondition || (hasOwn(AUTH_CONDITIONS, method.authCondition) + && AUTH_CONDITIONS[method.authCondition](caller))) + .map(method => method.name) + .filter(name => (name === 'card' ? caller.local === true : true)) + .filter(name => (name === 'invoice' ? invoiceRecipientNames.length > 0 : true)); +} + +/** + * Where the payment of an arrival stands: 'open' (no method chosen), + * 'pending' (online payment started, not completed), 'paid' (completed) or + * 'arranged' (cash, terminal, TWINT or invoice: settled outside the app). + */ +function paymentState(arrival) { + const payment = arrival.paymentMethod; + if (!isPlainObject(payment) || typeof payment.method !== 'string') { + return 'open'; + } + if (payment.status === 'completed') { + return 'paid'; + } + if (payment.method === 'checkout' && payment.status === 'pending') { + return 'pending'; + } + return 'arranged'; +} + +/** + * Pure. {due, amount, currency, options: [{method, invoiceRecipientName?}], + * state}; options are empty when nothing is due. + */ +function paymentOptions({ arrival, policy, caller, isHomeBase, invoiceRecipientNames }) { + const amount = typeof arrival.feeTotalGross === 'number' ? arrival.feeTotalGross : null; + const state = paymentState(arrival); + const due = (isHomeBase !== true || policy.homebasePayment === true) && amount !== null && amount > 0; + if (!due) { + return { due: false, amount, currency: 'CHF', options: [], state }; + } + const enabled = enabledPaymentMethods(policy.paymentMethods, caller, invoiceRecipientNames); + const options = PAYMENT_METHODS + .filter(method => enabled.includes(method) && method !== 'invoice') + .map(method => ({ method })); + if (enabled.includes('invoice')) { + invoiceRecipientNames.forEach(name => options.push({ method: 'invoice', invoiceRecipientName: name })); + } + return { due: true, amount, currency: 'CHF', options, state }; +} + +/** + * Pure. The /card-payments entry of an online payment, as the app writes it + * (src/modules/ui/arrivalPayment/sagas.ts createCardPayment); the payment + * service listening there answers with the checkout URL (`data`) and the + * status. The amount is the arrival's fee in cents, which + * updateArrivalPaymentStatus.js checks before it marks the arrival paid. + */ +function checkoutPayment(key, arrival, { owner, now }) { + const payment = { + amount: Math.round(arrival.feeTotalGross * 100), + currency: 'CHF', + method: 'checkout', + email: arrival.email, + immatriculation: arrival.immatriculation, + landings: arrival.landingCount, + landingFeeSingle: arrival.landingFeeSingle, + landingFeeTotal: arrival.landingFeeTotal, + refNr: referenceNumber(key), + arrivalReference: key, + status: 'pending', + timestamp: now, + }; + if (owner) { + payment.owner = owner; + } + if (arrival.landingFeeCode) { + payment.landingFeeCode = arrival.landingFeeCode; + } + if (arrival.goAroundCount && arrival.goAroundFeeTotal) { + payment.goArounds = arrival.goAroundCount; + payment.goAroundFeeSingle = arrival.goAroundFeeSingle; + payment.goAroundFeeCode = arrival.goAroundFeeCode; + payment.goAroundFeeTotal = arrival.goAroundFeeTotal; + } + return Object.fromEntries(Object.entries(payment).filter(([, value]) => value !== undefined && value !== null)); +} + +module.exports = { paymentOptions, paymentState, paymentCaller, enabledPaymentMethods, checkoutPayment, referenceNumber }; diff --git a/functions/movements/domain/paymentOptions.spec.js b/functions/movements/domain/paymentOptions.spec.js new file mode 100644 index 00000000..f9f37884 --- /dev/null +++ b/functions/movements/domain/paymentOptions.spec.js @@ -0,0 +1,69 @@ +'use strict'; + +const { paymentOptions, paymentState, paymentCaller, checkoutPayment } = require('./paymentOptions'); + +const POLICY = { + paymentMethods: [{ name: 'checkout', authCondition: 'notKiosk' }, { name: 'card_external', authCondition: 'kiosk' }, { name: 'invoice' }, { name: 'card' }], + homebasePayment: false, +}; +const PILOT = paymentCaller({ uid: 'login:s1', isKiosk: false, isGuest: false }); +const options = (overrides = {}) => paymentOptions({ + arrival: { feeTotalGross: 30 }, policy: POLICY, caller: PILOT, isHomeBase: false, invoiceRecipientNames: [], ...overrides, +}); + +describe('movement domain', () => { + describe('paymentOptions', () => { + it('offers a remote pilot online payment, no kiosk terminal, no card terminal', () => { + expect(options()).toEqual({ due: true, amount: 30, currency: 'CHF', options: [{ method: 'checkout' }], state: 'open' }); + }); + + it('adds invoice once per recipient the pilot is listed for, last', () => { + expect(options({ invoiceRecipientNames: ['Fluggruppe A', 'Firma B'] }).options).toEqual([ + { method: 'checkout' }, + { method: 'invoice', invoiceRecipientName: 'Fluggruppe A' }, + { method: 'invoice', invoiceRecipientName: 'Firma B' }, + ]); + }); + + it('offers the kiosk its terminal and the local card terminal', () => { + const kiosk = paymentCaller({ uid: 'kiosk', isKiosk: true }); + expect(options({ caller: kiosk }).options).toEqual([{ method: 'card' }, { method: 'card_external' }]); + }); + + it('asks nothing without a fee or for home-base aircraft, unless homebasePayment', () => { + expect(options({ arrival: { feeTotalGross: 0 } }).due).toBe(false); + expect(options({ arrival: {} })).toEqual({ due: false, amount: null, currency: 'CHF', options: [], state: 'open' }); + expect(options({ isHomeBase: true }).due).toBe(false); + expect(options({ isHomeBase: true, policy: { ...POLICY, homebasePayment: true } }).due).toBe(true); + }); + }); + + describe('paymentState', () => { + it.each([ + [undefined, 'open'], + [{ method: 'checkout', status: 'pending' }, 'pending'], + [{ method: 'checkout', status: 'completed' }, 'paid'], + [{ method: 'invoice', invoiceRecipientName: 'A' }, 'arranged'], + [{ method: 'cash' }, 'arranged'], + [{}, 'open'], + ])('%j is %s', (paymentMethod, state) => { + expect(paymentState({ paymentMethod })).toBe(state); + }); + }); + + describe('checkoutPayment', () => { + it('writes what the app writes, the fee in cents', () => { + const arrival = { + feeTotalGross: 30, email: 'pilot@example.com', immatriculation: 'HBPIV', landingCount: 1, + landingFeeSingle: 27.75, landingFeeTotal: 27.75, landingFeeCode: null, + }; + expect(checkoutPayment('-Nabc123_XYZ-def4567', arrival, { owner: 'login:s1', now: 1700000000000 })).toEqual({ + amount: 3000, currency: 'CHF', method: 'checkout', email: 'pilot@example.com', immatriculation: 'HBPIV', + landings: 1, landingFeeSingle: 27.75, landingFeeTotal: 27.75, refNr: '4567', arrivalReference: '-Nabc123_XYZ-def4567', + status: 'pending', timestamp: 1700000000000, owner: 'login:s1', + }); + expect(checkoutPayment('k', { ...arrival, feeTotalGross: 36.15, goAroundCount: 1, goAroundFeeSingle: 5, goAroundFeeTotal: 5 }, { now: 1 })) + .toMatchObject({ amount: 3615, goArounds: 1, goAroundFeeTotal: 5 }); + }); + }); +}); diff --git a/functions/movements/domain/policy.js b/functions/movements/domain/policy.js index afe3f468..9010667b 100644 --- a/functions/movements/domain/policy.js +++ b/functions/movements/domain/policy.js @@ -7,7 +7,9 @@ // aircraft categories, the aerodrome ICAO (for 'circuits'), whether movements // are owner-scoped (loginForm 'email') and which movement lock applies. // Beyond the rules, for the app-level checks of the API (checkAppRules.js): -// whether helicopters record no runway (aerodrome.noRunwayIfHelicopter). +// whether helicopters record no runway (aerodrome.noRunwayIfHelicopter); for +// paying the landing fee (paymentOptions.js): the payment methods and +// homebasePayment. Configs generated before these fields offer none. function policyError(field, problem) { return new TypeError(`Invalid movement policy config: ${field} ${problem}`); @@ -65,6 +67,9 @@ function buildMovementPolicy(config) { personalAccess: config.loginForm === 'email', lockOnDateTime: config.lockOnDateTime, noRunwayIfHelicopter: aerodrome.noRunwayIfHelicopter === true, + paymentMethods: Object.freeze((Array.isArray(config.paymentMethods) ? config.paymentMethods : []) + .map(method => Object.freeze({ ...method }))), + homebasePayment: config.homebasePayment === true, }); } diff --git a/functions/movements/domain/policy.spec.js b/functions/movements/domain/policy.spec.js index 2436ccd1..5cad886f 100644 --- a/functions/movements/domain/policy.spec.js +++ b/functions/movements/domain/policy.spec.js @@ -32,9 +32,20 @@ describe('movement domain', () => { personalAccess: true, lockOnDateTime: false, noRunwayIfHelicopter: false, + paymentMethods: [], + homebasePayment: false, }); }); + it('takes the payment methods and homebasePayment from the config', () => { + const policy = buildMovementPolicy(withConfig({ + paymentMethods: [{ name: 'checkout', authCondition: 'notKiosk' }, { name: 'invoice' }], homebasePayment: true, + })); + expect(policy.paymentMethods).toEqual([{ name: 'checkout', authCondition: 'notKiosk' }, { name: 'invoice' }]); + expect(policy.homebasePayment).toBe(true); + expect(loadVariant('lsze').policy.paymentMethods.map(m => m.name)).toEqual(['checkout', 'card_external', 'invoice']); + }); + it('takes noRunwayIfHelicopter from the aerodrome (only true counts)', () => { expect(buildMovementPolicy(withAerodrome({ noRunwayIfHelicopter: true })).noRunwayIfHelicopter).toBe(true); expect(buildMovementPolicy(withAerodrome({ noRunwayIfHelicopter: 'yes' })).noRunwayIfHelicopter).toBe(false); diff --git a/functions/movements/http/movementRoutes.js b/functions/movements/http/movementRoutes.js index c6a2cbfa..2346d02f 100644 --- a/functions/movements/http/movementRoutes.js +++ b/functions/movements/http/movementRoutes.js @@ -12,6 +12,7 @@ const { ApiError, validationError, sendError } = require('../../api/http/errors' const { buildMovementPolicy } = require('../domain'); const { saveMovement, OUTCOMES } = require('../application/saveMovement'); const { listMovements } = require('../application/listMovements'); +const { getArrivalPayment, payArrival } = require('../application/payArrival'); const { createRtdbMovementRepository } = require('../adapters/rtdbMovementRepository'); const { RulesRejectedError } = require('../adapters/databaseRest'); @@ -22,6 +23,7 @@ const { RulesRejectedError } = require('../adapters/databaseRest'); const CREATE_PATHS = ['/app/movements/:type', '/api/app/movements/:type']; const UPDATE_PATHS = ['/app/movements/:type/:key', '/api/app/movements/:type/:key']; const LIST_PATHS = ['/app/movements', '/api/app/movements']; +const PAYMENT_PATHS = ['/app/movements/arrivals/:key/payment', '/api/app/movements/arrivals/:key/payment']; // A list covers at most this period (and MAX_PER_TYPE movements per type). const MAX_LIST_RANGE_MS = 31 * 24 * 60 * 60 * 1000; @@ -239,6 +241,66 @@ function listHandler({ repository, policy }) { }); } +const PAYMENT_MESSAGES = Object.freeze({ + 'not-found': 'Movement not found', + 'not-owner': 'Not allowed to pay this movement', + 'already-paid': 'The landing fee is already paid or its payment arranged', + 'no-payment-due': 'No landing fee is due for this arrival', + 'method-not-offered': 'This payment method is not offered for this arrival', + 'checkout-failed': 'The online payment could not be started', + 'movement-locked': 'Movement is locked', +}); + +function paymentRejection(result) { + return new ApiError(result.code, PAYMENT_MESSAGES[result.reason] || 'Payment not possible', { reason: result.reason }); +} + +// POST body: {method, invoiceRecipientName?} +function paymentChoiceOf(req) { + const body = inputOf(req); + const errors = []; + if (typeof body.method !== 'string' || body.method === '') { + errors.push({ field: 'method', reason: 'required' }); + } + if (body.invoiceRecipientName !== undefined && typeof body.invoiceRecipientName !== 'string') { + errors.push({ field: 'invoiceRecipientName', reason: 'not-a-string' }); + } + const unknown = Object.keys(body).filter(field => !['method', 'invoiceRecipientName'].includes(field)); + unknown.forEach(field => errors.push({ field, reason: 'unknown-field' })); + if (errors.length > 0) { + throw validationError(errors); + } + return { method: body.method, invoiceRecipientName: body.invoiceRecipientName }; +} + +function paymentHandlers({ repository, policy }) { + const run = (useCase, extra) => asyncRoute(async (req, res) => { + const key = movementKeyOf(req); + let result; + try { + result = await useCase({ repository, policy: policy(), actor: req.actor, key, ...extra(req) }); + } catch (error) { + if (error instanceof RulesRejectedError) { + logger.error('Payment write rejected by database rules after the API allowed it', { + requestId: req.requestId, key, uid: req.actor.uid, + }); + throw new ApiError('internal', 'Internal error'); + } + throw error; + } + if (!result.ok) { + throw paymentRejection(result); + } + const { ok, ...body } = result; + res.set('Cache-Control', 'no-store'); + res.status(200).json(body); + }); + return { + get: run(getArrivalPayment, () => ({})), + post: run(payArrival, req => ({ choice: paymentChoiceOf(req) })), + }; +} + /** * Registers POST /app/movements/:type (create) and PATCH * /app/movements/:type/:key (update, merged like RTDB update()), also under @@ -249,7 +311,9 @@ function listHandler({ repository, policy }) { * (also under /api): the movements of a period the caller may see, * {from, to, movements, truncated} (application/listMovements.js). Tokens of * the central login need the scope movements:write to write and - * movements:read to list. + * movements:read to list. And GET/POST /app/movements/arrivals/:key/payment: + * how the caller may pay the landing fee of an arrival, and paying it + * (application/payArrival.js), with movements:write. */ function registerMovementRoutes(app, config, { auth = getAuth, @@ -263,6 +327,9 @@ function registerMovementRoutes(app, config, { app.post(CREATE_PATHS, ...write, saveHandler({ repository, policy, isCreate: true })); app.patch(UPDATE_PATHS, ...write, saveHandler({ repository, policy, isCreate: false })); app.get(LIST_PATHS, requestId, authenticate, requireScope('movements:read'), listHandler({ repository, policy })); + const payment = paymentHandlers({ repository, policy }); + app.get(PAYMENT_PATHS, requestId, authenticate, requireScope('movements:write'), payment.get); + app.post(PAYMENT_PATHS, requestId, authenticate, requireScope('movements:write'), jsonBody(), payment.post); } -module.exports = { registerMovementRoutes, CREATE_PATHS, UPDATE_PATHS, LIST_PATHS }; +module.exports = { registerMovementRoutes, CREATE_PATHS, UPDATE_PATHS, LIST_PATHS, PAYMENT_PATHS }; diff --git a/functions/movements/http/movementRoutes.spec.js b/functions/movements/http/movementRoutes.spec.js index c59bebf2..4597b664 100644 --- a/functions/movements/http/movementRoutes.spec.js +++ b/functions/movements/http/movementRoutes.spec.js @@ -63,6 +63,9 @@ function fakeRepository({ movements = {}, settings = {} } = {}) { updateMovement: jest.fn(async () => undefined), loadReaderFacts: jest.fn(async actor => ({ appUid: actor.uid, admin: actor.isAdmin === true, allMovements: false })), listMovements: jest.fn(async () => listed), + loadPaymentFacts: jest.fn(async () => ({ invoiceRecipientNames: [], isHomeBase: false })), + createCardPayment: jest.fn(async () => '-Npay1'), + waitForCheckout: jest.fn(async () => ({ url: 'https://pay.example.com/c/1' })), }; } @@ -592,6 +595,47 @@ describe('functions', () => { }); }); + describe('GET/POST /api/app/movements/arrivals/:key/payment', () => { + const priced = { createdBy: 'pilot@example.com', landingFeeSingle: 27.75, landingFeeTotal: 27.75, feeTotalGross: 30 }; + + it('tells the pilot how to pay, as the app would', async () => { + storeArrival(KEY, priced); + + const response = await send('GET', `/api/app/movements/arrivals/${KEY}/payment`); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ + due: true, amount: 30, currency: 'CHF', state: 'open', options: [{ method: 'checkout' }], + }); + }); + + it('starts an online payment and answers the checkout URL', async () => { + storeArrival(KEY, priced); + + const response = await send('POST', `/api/app/movements/arrivals/${KEY}/payment`, { body: { method: 'checkout' } }); + + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ method: 'checkout', checkoutUrl: 'https://pay.example.com/c/1' }); + expect(repository.createCardPayment).toHaveBeenCalledWith(expect.objectContaining({ amount: 3000, arrivalReference: KEY }), actor('pilot-uid')); + }); + + it('answers 400, 403, 404 and 409 in the envelope', async () => { + storeArrival(KEY, priced); + await expectError(await send('POST', `/api/app/movements/arrivals/${KEY}/payment`, { body: { method: 'invoice', invoiceRecipientName: 'X' } }), 400, { + code: 'invalid-argument', message: 'This payment method is not offered for this arrival', details: { reason: 'method-not-offered' }, + }); + await expectError(await send('POST', `/api/app/movements/arrivals/${KEY}/payment`, { body: { foo: 1 } }), 400, { + code: 'invalid-argument', + message: 'Validation failed', + details: { reason: 'validation-failed', validationErrors: [{ field: 'method', reason: 'required' }, { field: 'foo', reason: 'unknown-field' }] }, + }); + expect((await send('GET', `/api/app/movements/arrivals/${KEY}/payment`, { uid: 'other-uid' })).status).toBe(403); + expect((await send('GET', '/api/app/movements/arrivals/-Nmissing/payment')).status).toBe(404); + storeArrival(KEY, { ...priced, paymentMethod: { method: 'checkout', status: 'completed' } }); + expect((await send('POST', `/api/app/movements/arrivals/${KEY}/payment`, { body: { method: 'checkout' } })).status).toBe(409); + }); + }); + describe('failures', () => { it('answers 500 and logs the disagreement when the rules reject an accepted write', async () => { repository.createMovement.mockRejectedValue(new RulesRejectedError('departures')); diff --git a/package.json b/package.json index bdf42e49..e3df3cf9 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "test:watch": "jest --watch", "test:coverage": "jest --coverage", "test:functions": "cd functions && npm test", - "test:rules": "firebase emulators:exec --only database --config firebase.emulator.json --project demo-rules-test \"node test/rules/movementWrite.rules.js && node test/rules/movementDomainParity.rules.js && node test/rules/movementApiWrite.rules.js && node test/rules/movementApiRead.rules.js\"", + "test:rules": "firebase emulators:exec --only database --config firebase.emulator.json --project demo-rules-test \"node test/rules/movementWrite.rules.js && node test/rules/movementDomainParity.rules.js && node test/rules/movementApiWrite.rules.js && node test/rules/movementApiRead.rules.js && node test/rules/movementApiPayment.rules.js\"", "test:app": "jest --testPathIgnorePatterns=functions", "codecov": "codecov", "cy:open": "cypress open", diff --git a/projects/Configuration.md b/projects/Configuration.md index ee71dcda..be77f88f 100644 --- a/projects/Configuration.md +++ b/projects/Configuration.md @@ -366,6 +366,18 @@ location, route, runway, counts, fees, payment method and status; not the pilot' number, remarks, route description, customs form or invoice recipient). The API reads as the caller (`auth_variable_override`; for an admin as their app user), so the read rules apply as in the app. +Paying the landing fee (`GET`/`POST /api/app/movements/arrivals//payment`, scope `movements:write`): the API +offers exactly what the app's arrival wizard offers the caller (`functions/movements/domain/paymentOptions.js`, +parity with `src/util/paymentMethods.ts` in `src/util/paymentOptions.parity.spec.js`): payment only when a fee is due +and the aircraft is not a club or home-base aircraft unless `homebasePayment`; the `paymentMethods` whose +`authCondition` holds (a caller of the central login is never a kiosk), the card terminal (`card`) only for local +sign-ins, invoice once per recipient whose `emails` list the caller. `GET` answers `{due, amount, currency, options, +state}` (`state`: `open`, `pending`, `paid`, `arranged`); `POST {method, invoiceRecipientName?}` records the method on +the arrival like any change (ownership, lock), and for `checkout` also pushes the `/card-payments` entry the app writes +(amount = the arrival's `feeTotalGross` in cents), waits up to 10 seconds for the payment service's checkout URL and +answers `{method, checkoutUrl}` (`null` when the service did not answer in time). `updateArrivalPaymentStatus` marks +the arrival paid as for the app. + Set it per environment. Only the functions read it (`functions/project-config.generated.json`, validated by `tasks/generateServerConfig.js`); without it, tokens of the login are rejected like any other unknown token. Set on `lsze` test, with the dev login (`odch-login-dev`) at its `*.run.app` address until diff --git a/src/util/paymentOptions.parity.spec.js b/src/util/paymentOptions.parity.spec.js new file mode 100644 index 00000000..a2a5a1de --- /dev/null +++ b/src/util/paymentOptions.parity.spec.js @@ -0,0 +1,62 @@ +// Parity: the movement API offers a pilot the same ways to pay the landing +// fee as the app's arrival wizard (functions/movements/domain/paymentOptions.js +// against src/util/paymentMethods.ts), for every project, kind of user, +// invoice recipients, home-base aircraft and fee. +const fs = require('fs'); +const path = require('path'); +const projects = require('../../projects'); +const objectToArray = require('./objectToArray').default; +const { buildServerConfigFor } = require('../../tasks/generateServerConfig'); +const { buildMovementPolicy } = require('../../functions/movements/domain/policy'); +const { paymentOptions, paymentCaller } = require('../../functions/movements/domain/paymentOptions'); +const { PAYMENT_METHODS, getSelectablePaymentMethods, isPaymentDue } = require('./paymentMethods'); + +const PROJECTS = fs.readdirSync(path.join(__dirname, '../../projects')) + .filter(file => file.endsWith('.json') && file !== 'default.json') + .map(file => file.replace(/\.json$/, '')) + .sort(); +const USERS = [ + ['a pilot (also through Claude)', { uid: 'u1', isKiosk: false, isGuest: false }, { kiosk: false, local: false }], + ['the kiosk', { uid: 'kiosk', isKiosk: true, isGuest: false }, { kiosk: true, local: true }], + ['the guest', { uid: 'guest', isKiosk: false, isGuest: true }, { kiosk: false, local: true }], +]; +const RECIPIENTS = [[], ['Fluggruppe A'], ['Fluggruppe A', 'Firma B']]; + +// What the wizard lists (PaymentMethod.tsx): the selectable methods in the +// order of PAYMENT_METHODS, invoice once per recipient. +function clientOptions(selectable, recipients) { + const options = PAYMENT_METHODS + .filter(m => selectable.includes(m.value) && m.value !== 'invoice') + .map(m => ({ method: m.value })); + if (selectable.includes('invoice')) { + recipients.forEach(name => options.push({ method: 'invoice', invoiceRecipientName: name })); + } + return options; +} + +describe('payment options: API and app agree', () => { + describe.each(PROJECTS)('%s', project => { + const conf = projects.load(project); + const policy = buildMovementPolicy(buildServerConfigFor(project, 'test')); + + it.each(USERS)('for %s', (_, actor, auth) => { + for (const recipients of RECIPIENTS) { + for (const isHomeBase of [false, true]) { + for (const fee of [0, 30]) { + const server = paymentOptions({ + arrival: { feeTotalGross: fee }, + policy, + caller: paymentCaller(actor), + isHomeBase, + invoiceRecipientNames: recipients, + }); + const due = isPaymentDue(isHomeBase, conf.homebasePayment === true, fee); + const selectable = getSelectablePaymentMethods(objectToArray(conf.paymentMethods), auth, recipients); + expect({ due: server.due, options: server.options }) + .toEqual({ due, options: due ? clientOptions(selectable, recipients) : [] }); + } + } + } + }); + }); +}); diff --git a/tasks/generateServerConfig.js b/tasks/generateServerConfig.js index b41b89fb..8ec7a79e 100644 --- a/tasks/generateServerConfig.js +++ b/tasks/generateServerConfig.js @@ -119,6 +119,31 @@ function buildFlightTypes(project, env, merged) { }); } +// The client's PAYMENT_METHODS (src/util/paymentMethods.ts) and the +// conditions of getEnabledPaymentMethods. +const PAYMENT_METHOD_NAMES = ['card', 'checkout', 'cash', 'card_external', 'twint_external', 'invoice']; +const PAYMENT_AUTH_CONDITIONS = ['kiosk', 'notKiosk']; + +// paymentMethods as the client reads them (objectToArray of the packinized +// list): a name, or {name, authCondition}. The movement API offers a pilot +// the same methods as the app's arrival wizard. +function buildPaymentMethods(project, env, merged) { + const methods = hasOwn(merged, 'paymentMethods') ? merged.paymentMethods : defaultConf.paymentMethods; + if (!Array.isArray(methods)) { + throw configError(project, env, 'paymentMethods', 'must be an array'); + } + return clientOrder(methods).map(method => { + const entry = typeof method === 'string' ? { name: method } : method; + if (!isPlainObject(entry) || !PAYMENT_METHOD_NAMES.includes(entry.name)) { + throw configError(project, env, 'paymentMethods', `contains an unknown method: ${JSON.stringify(method)}`); + } + if (hasOwn(entry, 'authCondition') && !PAYMENT_AUTH_CONDITIONS.includes(entry.authCondition)) { + throw configError(project, env, 'paymentMethods', `contains an unknown authCondition: ${JSON.stringify(method)}`); + } + return hasOwn(entry, 'authCondition') ? { name: entry.name, authCondition: entry.authCondition } : { name: entry.name }; + }); +} + function buildLoginForm(project, env, merged) { const loginForm = hasOwn(merged, 'loginForm') ? merged.loginForm : defaultConf.loginForm; if (typeof loginForm !== 'string' || loginForm === '') { @@ -230,6 +255,9 @@ function buildServerConfig(project, conf, env) { // Not per project: the list the database rules accept (aircraftCategory). aircraftCategories: aircraftCategoriesData.map(category => category.name), aerodrome, + // What the arrival wizard offers for paying the landing fee. + paymentMethods: buildPaymentMethods(project, env, merged), + homebasePayment: readFlag(project, env, merged, 'homebasePayment'), ...buildCentralLogin(project, env, merged) }; } diff --git a/tasks/generateServerConfig.spec.js b/tasks/generateServerConfig.spec.js index 43122787..584c6617 100644 --- a/tasks/generateServerConfig.spec.js +++ b/tasks/generateServerConfig.spec.js @@ -133,6 +133,10 @@ describe('tasks/generateServerConfig', () => { arrivalRoutes: objectToArray(client.aerodrome.arrivalRoutes).map(({ name }) => ({ name })), noRunwayIfHelicopter: client.aerodrome.noRunwayIfHelicopter === true }, + paymentMethods: objectToArray(client.paymentMethods).map(method => (typeof method === 'string' + ? { name: method } + : { name: method.name, ...(method.authCondition ? { authCondition: method.authCondition } : {}) })), + homebasePayment: client.homebasePayment === true, ...(client.centralLogin ? { centralLogin: client.centralLogin } : {}) }); }); diff --git a/test/rules/movementApiPayment.rules.js b/test/rules/movementApiPayment.rules.js new file mode 100644 index 00000000..ce3da68d --- /dev/null +++ b/test/rules/movementApiPayment.rules.js @@ -0,0 +1,121 @@ +/** + * Emulator test: paying a landing fee through the app API + * (application/payArrival.js) against the built database rules of lsze. + * + * Run via: npm run test:rules (starts the RTDB emulator, then runs this). + * + * With the real RTDB adapter, as a pilot with a token of the central login: + * - an online payment records the method (pending) on the arrival and + * pushes the /card-payments entry as the caller; the rules accept both; + * a stand-in for the payment service answers with the checkout URL; + * - an invoice to a recipient the pilot is listed for is recorded; + * - the rules still deny writing a payment method on another pilot's + * arrival, sent straight through the adapter. + */ +'use strict'; + +const assert = require('assert'); +const path = require('path'); + +const fromFunctions = name => require(require.resolve(name, { paths: [path.join(__dirname, '../../functions')] })); +const { initializeApp, deleteApp } = fromFunctions('firebase-admin/app'); +const { getDatabase } = fromFunctions('firebase-admin/database'); + +const { emulatorRulesFor } = require('./emulatorRules'); +const { loadVariant } = require('../../functions/movements/domain/testing/projectPolicies'); +const { stored } = require('../../functions/movements/domain/testing/movementCases'); +const { payArrival, getArrivalPayment } = require('../../functions/movements/application/payArrival'); +const { loginActor } = require('../../functions/api/http/appAuth'); +const { createRtdbMovementRepository } = require('../../functions/movements/adapters/rtdbMovementRepository'); +const { RulesRejectedError, createDatabaseRestClient } = require('../../functions/movements/adapters/databaseRest'); + +const NAMESPACE = 'demo-movement-api'; +const EMULATOR_HOST = process.env.FIREBASE_DATABASE_EMULATOR_HOST; + +let failures = 0; +async function check(label, test) { + try { + await test(); + console.log(` ✓ ${label}`); + } catch (e) { + failures++; + console.error(` ✗ ${label} — ${e.stack}`); + } +} + +async function main() { + assert.ok(EMULATOR_HOST, 'FIREBASE_DATABASE_EMULATOR_HOST is not set; run via npm run test:rules'); + const credential = { getAccessToken: async () => ({ access_token: 'owner', expires_in: 3600 }) }; + const app = initializeApp({ projectId: NAMESPACE, databaseURL: `https://${NAMESPACE}.firebaseio.com`, credential }, 'movement-api-payment'); + const db = getDatabase(app); + const { rulesConfig, policy } = loadVariant('lsze'); + const rules = await fetch(`http://${EMULATOR_HOST}/.settings/rules.json?ns=${NAMESPACE}`, { + method: 'PUT', headers: { Authorization: 'Bearer owner' }, body: emulatorRulesFor(rulesConfig), + }); + assert.strictEqual(rules.status, 200, await rules.text()); + + const priced = createdBy => ({ + ...stored('arrival', policy, { createdBy }), + landingFeeSingle: 27.75, landingFeeTotal: 27.75, feeTotalNet: 27.75, feeVat: 2.25, feeRoundingDifference: 0, feeTotalGross: 30, + }); + await db.ref().set(null); + await db.ref('settings/invoiceRecipients').set([{ name: 'Fluggruppe A', emails: ['pilot@example.com'] }]); + await db.ref('arrivals').set({ own1: priced('pilot@example.com'), own2: priced('pilot@example.com'), other1: priced('other@example.com') }); + + const rest = createDatabaseRestClient({ app: () => app }); + const repository = createRtdbMovementRepository({ db: () => db, rest, sleep: ms => new Promise(r => setTimeout(r, Math.min(ms, 100))) }); + const pilot = loginActor({ sub: 'sub-1', email: 'pilot@example.com', scopes: ['movements:write'] }); + const run = (useCase, key, choice) => useCase({ repository, policy, actor: pilot, key, choice }); + + // Stand-in for the payment service: answers each new card payment with a checkout URL. + const service = db.ref('card-payments').on('child_added', snapshot => { + if (!snapshot.val().data) snapshot.ref.update({ data: `https://pay.example.com/c/${snapshot.key}` }); + }); + + console.log('landing fee payment through the API (rules of lsze, as the caller)'); + + await check('the pilot is offered online payment and invoice to their recipient', async () => { + const result = await run(getArrivalPayment, 'own1'); + assert.deepStrictEqual(result.options, [{ method: 'checkout' }, { method: 'invoice', invoiceRecipientName: 'Fluggruppe A' }]); + }); + + await check('an online payment: method pending and the card payment, both accepted by the rules', async () => { + const result = await run(payArrival, 'own1', { method: 'checkout' }); + assert.strictEqual(result.ok, true, JSON.stringify(result)); + assert.match(result.checkoutUrl, /^https:\/\/pay\.example\.com\/c\//); + assert.deepStrictEqual((await db.ref('arrivals/own1/paymentMethod').once('value')).val(), { method: 'checkout', status: 'pending' }); + const payments = Object.values((await db.ref('card-payments').once('value')).val()); + assert.strictEqual(payments.length, 1); + assert.strictEqual(payments[0].amount, 3000); + assert.strictEqual(payments[0].arrivalReference, 'own1'); + assert.strictEqual(payments[0].owner, 'login:sub-1'); + }); + + await check('an invoice to the pilot\'s recipient is recorded', async () => { + const result = await run(payArrival, 'own2', { method: 'invoice', invoiceRecipientName: 'Fluggruppe A' }); + assert.strictEqual(result.ok, true, JSON.stringify(result)); + assert.deepStrictEqual((await db.ref('arrivals/own2/paymentMethod').once('value')).val(), { method: 'invoice', invoiceRecipientName: 'Fluggruppe A' }); + }); + + await check('another pilot\'s arrival: refused by the API, and the rules deny the write too', async () => { + assert.strictEqual((await run(payArrival, 'other1', { method: 'checkout' })).reason, 'not-owner'); + const error = await rest.write('PATCH', 'arrivals/other1', { paymentMethod: { method: 'cash' } }, { uid: 'login:sub-1', token: { email: 'pilot@example.com' } }) + .then(() => null, e => e); + assert.ok(error instanceof RulesRejectedError, `expected a rules rejection, got ${error}`); + }); + + db.ref('card-payments').off('child_added', service); + await deleteApp(app); +} + +main().then(() => { + if (failures > 0) { + console.error(`\n${failures} payment assertion(s) failed`); + process.exit(1); + } + console.log('\nAll payment assertions passed'); + process.exit(0); +}).catch(e => { + console.error(e); + process.exit(1); +});