Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion functions/api/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
55 changes: 54 additions & 1 deletion functions/movements/adapters/rtdbMovementRepository.js
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions functions/movements/adapters/rtdbMovementRepository.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
});
});
});
});
106 changes: 106 additions & 0 deletions functions/movements/application/payArrival.js
Original file line number Diff line number Diff line change
@@ -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 };
105 changes: 105 additions & 0 deletions functions/movements/application/payArrival.spec.js
Original file line number Diff line number Diff line change
@@ -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 });
});
});
});
Loading
Loading