Template
1
0

feat: add payment module

This commit is contained in:
2025-12-05 01:56:42 +01:00
parent a818f3135a
commit be9b8e9e55
160 changed files with 8615 additions and 1158 deletions

View File

@@ -0,0 +1,9 @@
export const ledger = {
dashboard: (await import("../routes/dashboard/spec.ts")).default,
benficiaries: {
create: (await import("../routes/beneficiaries/create/spec.ts")).default,
list: (await import("../routes/beneficiaries/list/spec.ts")).default,
id: (await import("../routes/beneficiaries/:id/spec.ts")).default,
},
create: (await import("../routes/ledgers/create/spec.ts")).default,
};

View File

@@ -0,0 +1,14 @@
export default {
routes: [
(await import("../routes/dashboard/handle.ts")).default,
(await import("../routes/beneficiaries/create/handle.ts")).default,
(await import("../routes/beneficiaries/list/handle.ts")).default,
(await import("../routes/beneficiaries/:id/handle.ts")).default,
(await import("../routes/beneficiaries/ledgers/handle.ts")).default,
(await import("../routes/ledgers/create/handle.ts")).default,
(await import("../routes/ledgers/wallets/handle.ts")).default,
(await import("../routes/wallets/create/handle.ts")).default,
(await import("../routes/wallets/accounts/handle.ts")).default,
(await import("../routes/accounts/create/handle.ts")).default,
],
};

View File

View File

@@ -0,0 +1,17 @@
{
"name": "@module/payment",
"description": "A record of value transactions",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": {
"./server": "./entrypoints/server.ts",
"./client": "./entrypoints/client.ts"
},
"dependencies": {
"@platform/database": "workspace:*",
"@platform/parse": "workspace:*",
"@platform/relay": "workspace:*",
"zod": "4.1.13"
}
}

View File

@@ -0,0 +1,97 @@
import { db } from "@platform/database";
import { BadRequestError, ConflictError } from "@platform/relay";
import { type Account, type AccountInsert, AccountInsertSchema, AccountSchema } from "../schemas/account.ts";
import { getLedgerById } from "./ledger.ts";
import { getWalletById } from "./wallet.ts";
/**
* Create a new account.
*
* @param values - Account values to insert.
*/
export async function createAccount(values: AccountInsert): Promise<string> {
return db
.begin(async () => {
const _id = crypto.randomUUID();
// const wallet = await getWalletById(values.walletId);
// if (wallet === undefined) {
// throw new ConflictError(`Wallet '${values.walletId}' does not exist`);
// }
// const ledger = await getLedgerById(wallet.ledgerId);
// if (ledger === undefined) {
// // TODO: RAISE ALARMS, THIS SHOULD NEVER OCCUR
// throw new ConflictError(`Wallet ledger '${wallet.ledgerId}' does not exist`);
// }
// if (ledger.currencies.includes(values.currency) === false) {
// throw new BadRequestError(
// `Ledger does not support '${values.currency}' currency, supported currencies '${ledger.currencies.join(", ")}'`,
// );
// }
// Assert wallet exists
await db.sql`
ASSERT EXISTS (
SELECT 1
FROM payment.wallet w
WHERE w._id = ${db.text(values.walletId)}
), 'missing_wallet';
`;
// Assert wallet → ledger relationship exists AND ledger exists
await db.sql`
ASSERT EXISTS (
SELECT 1
FROM payment.wallet w
JOIN payment.ledger l ON l._id = w."ledgerId"
WHERE w._id = ${db.text(values.walletId)}
), 'missing_ledger';
`;
// Assert ledger supports the currency
await db.sql`
ASSERT EXISTS (
SELECT 1
FROM payment.wallet w
JOIN payment.ledger l ON l._id = w."ledgerId"
WHERE w._id = ${db.text(values.walletId)}
AND ${db.text(values.currency)} = ANY(l.currencies)
), 'unsupported_currency';
`;
await db.sql`INSERT INTO payment.wallet RECORDS ${db.transit({ _id, ...AccountInsertSchema.parse(values) })}`;
return _id;
})
.catch((error) => {
if (error instanceof Error === false) {
throw error;
}
switch (error.message) {
case "missing_wallet": {
throw new ConflictError("Account wallet does not exist");
}
case "missing_ledger": {
throw new ConflictError("Account ledger does not exist");
}
case "unsupported_currency": {
throw new ConflictError("Invalid account currency");
}
}
throw error;
});
}
export async function getAccountsByWalletId(walletId: string): Promise<Account[]> {
return db.schema(AccountSchema).many`
SELECT
*, _system_from as "createdAt"
FROM
payment.wallet
WHERE
"walletId" = ${walletId}
`;
}

View File

@@ -0,0 +1,101 @@
import { db } from "@platform/database";
import { ConflictError } from "@platform/relay";
import {
type Beneficiary,
type BeneficiaryInsert,
BeneficiaryInsertSchema,
BeneficiarySchema,
type BeneficiaryUpdate,
BeneficiaryUpdateSchema,
} from "../schemas/beneficiary.ts";
/**
* Create a new beneficiary entity.
*
* @param values - Beneficiary values to insert.
*/
export async function createBeneficiary({ tenantId, label }: BeneficiaryInsert): Promise<string> {
return db
.begin(async () => {
const _id = crypto.randomUUID();
await db.sql`ASSERT NOT EXISTS (SELECT 1 FROM payment.beneficiary WHERE "tenantId" = ${db.text(tenantId)}), 'duplicate_tenant'`;
await db.sql`INSERT INTO payment.beneficiary RECORDS ${db.transit({ _id, ...BeneficiaryInsertSchema.parse({ tenantId, label }) })}`;
return _id;
})
.catch((error) => {
if (error instanceof Error && error.message === "duplicate_tenant") {
throw new ConflictError(`Tenant '${tenantId}' already has a beneficiary`);
}
throw error;
});
}
/**
* Get a list of all registered beneficiaries.
*/
export async function getBeneficiaries(): Promise<any[]> {
return db.schema(BeneficiarySchema).many`
SELECT
*, _system_from as "createdAt"
FROM
payment.beneficiary
ORDER BY
_system_from DESC
`;
}
/**
* Get a beneficiary entity by provided tenant id.
*
* @param tenantId - Tenant we want to retrieve benificiary for.
*/
export async function getBeneficiaryByTenantId(tenantId: string): Promise<Beneficiary | undefined> {
return db.schema(BeneficiarySchema).one`
SELECT
*, _system_from as "createdAt"
FROM
payment.beneficiary
WHERE
"tenantId" = ${tenantId}
ORDER BY
_system_from DESC
`;
}
/**
* Get a beneficiary entity by provided id.
*
* @param id - Identity of the beneficiary to retrieve.
*/
export async function getBeneficiaryById(id: string): Promise<Beneficiary | undefined> {
return db.schema(BeneficiarySchema).one`
SELECT
*, _system_from as "createdAt"
FROM
payment.beneficiary
WHERE
_id = ${id}
ORDER BY
_system_from DESC
`;
}
/**
* Update a beneficiary entity with the given data.
*
* @param attributes - Attributes to set on the beneficiary.
*/
export async function updateBeneficiary(attributes: BeneficiaryUpdate): Promise<void> {
const { _id, label } = BeneficiaryUpdateSchema.parse(attributes);
await db.sql`UPDATE payment.beneficiary SET label = ${label} WHERE _id = ${_id}`;
}
/**
* Delete a beneficiary entity.
*
* @param id - Identity of the beneficiary to delete.
*/
export async function deleteBeneficiary(id: string): Promise<void> {
await db.sql`DELETE FROM payment.beneficiary WHERE _id = ${id}`;
}

View File

@@ -0,0 +1,57 @@
import { db } from "@platform/database";
import { ConflictError } from "@platform/relay";
import { type Ledger, type LedgerInsert, LedgerInsertSchema, LedgerSchema } from "../schemas/ledger.ts";
/**
* Create a new ledger.
*
* @param values - Ledger values to insert.
*/
export async function createLedger(values: LedgerInsert): Promise<string> {
return db
.begin(async () => {
const _id = crypto.randomUUID();
await db.sql`ASSERT EXISTS (SELECT 1 FROM payment.beneficiary WHERE _id = ${db.text(values.beneficiaryId)}), 'missing_beneficiary'`;
await db.sql`INSERT INTO payment.ledger RECORDS ${db.transit({ _id, ...LedgerInsertSchema.parse(values) })}`;
return _id;
})
.catch((error) => {
if (error instanceof Error && error.message === "missing_beneficiary") {
throw new ConflictError(`Benficiary '${values.beneficiaryId}' does not exist`);
}
throw error;
});
}
export async function getLedgersByBeneficiary(beneficiaryId: string): Promise<Ledger[]> {
console.log(
await db.sql`
SELECT
*, _system_from as "createdAt"
FROM
payment.ledger
WHERE
"beneficiaryId" = ${beneficiaryId}
`,
);
return db.schema(LedgerSchema).many`
SELECT
*, _system_from as "createdAt"
FROM
payment.ledger
WHERE
"beneficiaryId" = ${beneficiaryId}
`;
}
export async function getLedgerById(id: string): Promise<Ledger | undefined> {
return db.schema(LedgerSchema).one`
SELECT
*, _system_from as "createdAt"
FROM
payment.ledger
WHERE
_id = ${id}
`;
}

View File

@@ -0,0 +1,3 @@
import { db } from "@platform/database";
export async function createTransaction() {}

View File

@@ -0,0 +1,47 @@
import { db } from "@platform/database";
import { ConflictError } from "@platform/relay";
import { type Wallet, type WalletInsert, WalletInsertSchema, WalletSchema } from "../schemas/wallet.ts";
/**
* Create a new wallet.
*
* @param values - Wallet values to insert.
*/
export async function createWallet(values: WalletInsert): Promise<string> {
return db
.begin(async () => {
const _id = crypto.randomUUID();
await db.sql`ASSERT EXISTS (SELECT 1 FROM payment.ledger WHERE _id = ${db.text(values.ledgerId)}), 'missing_ledger'`;
await db.sql`INSERT INTO payment.wallet RECORDS ${db.transit({ _id, ...WalletInsertSchema.parse(values) })}`;
return _id;
})
.catch((error) => {
if (error instanceof Error && error.message === "missing_beneficiary") {
throw new ConflictError(`Ledger '${values.ledgerId}' does not exist`);
}
throw error;
});
}
export async function getWalletsByLedgerId(ledgerId: string): Promise<Wallet[]> {
return db.schema(WalletSchema).many`
SELECT
*, _system_from as "createdAt"
FROM
payment.wallet
WHERE
"ledgerId" = ${ledgerId}
`;
}
export async function getWalletById(id: string): Promise<Wallet | undefined> {
return db.schema(WalletSchema).one`
SELECT
*, _system_from as "createdAt"
FROM
payment.wallet
WHERE
_id = ${id}
`;
}

View File

@@ -0,0 +1,4 @@
import { createAccount } from "../../../repositories/account.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ body }) => createAccount(body));

View File

@@ -0,0 +1,6 @@
import { route } from "@platform/relay";
import z from "zod";
import { AccountInsertSchema } from "../../../schemas/account.ts";
export default route.post("/api/v1/payment/accounts").body(AccountInsertSchema).response(z.uuid());

View File

@@ -0,0 +1,12 @@
import { NotFoundError } from "@platform/relay";
import { getBeneficiaryById } from "../../../repositories/beneficiary.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ params: { id } }) => {
const beneficiary = await getBeneficiaryById(id);
if (beneficiary === undefined) {
return new NotFoundError();
}
return beneficiary;
});

View File

@@ -0,0 +1,8 @@
import { route } from "@platform/relay";
import { BeneficiarySchema } from "../../../schemas/beneficiary.ts";
export default route
.get("/api/v1/payment/beneficiaries/:id")
.params({ id: BeneficiarySchema.shape._id })
.response(BeneficiarySchema);

View File

@@ -0,0 +1,4 @@
import { createBeneficiary } from "../../../repositories/beneficiary.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ body }) => createBeneficiary(body));

View File

@@ -0,0 +1,5 @@
import { route } from "@platform/relay";
import { BeneficiaryInsertSchema, BeneficiarySchema } from "../../../schemas/beneficiary.ts";
export default route.post("/api/v1/payment/beneficiaries").body(BeneficiaryInsertSchema).response(BeneficiarySchema);

View File

@@ -0,0 +1,4 @@
import { getLedgersByBeneficiary } from "../../../repositories/ledger.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ params: { id } }) => getLedgersByBeneficiary(id));

View File

@@ -0,0 +1,9 @@
import { route } from "@platform/relay";
import z from "zod";
import { LedgerSchema } from "../../../schemas/ledger.ts";
export default route
.get("/api/v1/payment/beneficiaries/:id/ledgers")
.params({ id: z.uuid() })
.response(z.array(LedgerSchema));

View File

@@ -0,0 +1,4 @@
import { getBeneficiaries } from "../../../repositories/beneficiary.ts";
import route from "./spec.ts";
export default route.access("public").handle(async () => getBeneficiaries());

View File

@@ -0,0 +1,6 @@
import { route } from "@platform/relay";
import z from "zod";
import { BeneficiarySchema } from "../../../schemas/beneficiary.ts";
export default route.get("/api/v1/payment/beneficiaries").response(z.array(BeneficiarySchema));

View File

@@ -0,0 +1,31 @@
import { db } from "@platform/database";
import { NotFoundError } from "@platform/relay";
import route, { DashboardSchema } from "./spec.ts";
export default route.access("public").handle(async ({ params: { id } }) => {
const dashboard = await db.schema(DashboardSchema).one`
SELECT
pb.*,
pb._system_from AS "createdAt",
NEST_MANY(
SELECT
pl.*,
pl._system_from AS "createdAt",
FROM
payment.ledger pl
WHERE
pl."beneficiaryId" = pb._id
ORDER BY
pl._id
) AS ledgers
FROM
payment.beneficiary pb
WHERE
pb._id = ${id}
`;
if (dashboard === undefined) {
return new NotFoundError("Beneficiary not found");
}
return dashboard;
});

View File

@@ -0,0 +1,16 @@
import { nestMany } from "@platform/parse";
import { route } from "@platform/relay";
import z from "zod";
import { BeneficiarySchema } from "../../schemas/beneficiary.ts";
import { LedgerSchema } from "../../schemas/ledger.ts";
export const DashboardSchema = z.strictObject({
...BeneficiarySchema.shape,
ledgers: nestMany(LedgerSchema),
});
export default route
.get("/api/v1/payment/dashboard/:id")
.params({ id: BeneficiarySchema.shape._id })
.response(DashboardSchema);

View File

@@ -0,0 +1,4 @@
import { createLedger } from "../../../repositories/ledger.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ body }) => createLedger(body));

View File

@@ -0,0 +1,6 @@
import { route } from "@platform/relay";
import z from "zod";
import { LedgerInsertSchema } from "../../../schemas/ledger.ts";
export default route.post("/api/v1/payment/ledgers").body(LedgerInsertSchema).response(z.uuid());

View File

@@ -0,0 +1,4 @@
import { getWalletsByLedgerId } from "../../../repositories/wallet.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ params: { id } }) => getWalletsByLedgerId(id));

View File

@@ -0,0 +1,9 @@
import { route } from "@platform/relay";
import z from "zod";
import { WalletSchema } from "../../../schemas/wallet.ts";
export default route
.get("/api/v1/payment/ledgers/:id/wallets")
.params({ id: z.uuid() })
.response(z.array(WalletSchema));

View File

@@ -0,0 +1,4 @@
import { getAccountsByWalletId } from "../../../repositories/account.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ params: { id } }) => getAccountsByWalletId(id));

View File

@@ -0,0 +1,9 @@
import { route } from "@platform/relay";
import z from "zod";
import { AccountSchema } from "../../../schemas/account.ts";
export default route
.get("/api/v1/payment/wallets/:id/accounts")
.params({ id: z.uuid() })
.response(z.array(AccountSchema));

View File

@@ -0,0 +1,4 @@
import { createWallet } from "../../../repositories/wallet.ts";
import route from "./spec.ts";
export default route.access("public").handle(async ({ body }) => createWallet(body));

View File

@@ -0,0 +1,6 @@
import { route } from "@platform/relay";
import z from "zod";
import { WalletInsertSchema } from "../../../schemas/wallet.ts";
export default route.post("/api/v1/payment/wallets").body(WalletInsertSchema).response(z.uuid());

View File

@@ -0,0 +1,35 @@
import z from "zod";
import { CurrencySchema } from "./currency.ts";
/*
|--------------------------------------------------------------------------------
| Account
|--------------------------------------------------------------------------------
|
| An account is a entity which can be the sender or recipient in a transaction.
|
*/
export const AccountSchema = z.strictObject({
_id: z.uuid().describe("Primary identifier of the account"),
walletId: z.string().describe("Identifier of the wallet this account belongs to"),
label: z.string().describe("Human-readable name for the account"),
currency: CurrencySchema.describe("Currency this account trades in"),
});
export type Account = z.output<typeof AccountSchema>;
/*
|--------------------------------------------------------------------------------
| Database
|--------------------------------------------------------------------------------
*/
export const AccountInsertSchema = z.strictObject({
walletId: AccountSchema.shape.walletId,
label: z.string().nullable().default(null).describe("Human-readable identifier for the account"),
currency: AccountSchema.shape.currency,
});
export type AccountInsert = z.input<typeof AccountInsertSchema>;

View File

@@ -0,0 +1,40 @@
import z from "zod";
/*
|--------------------------------------------------------------------------------
| Beneficiary
|--------------------------------------------------------------------------------
|
| A beneficiary is an entity (person, organization, or system) that owns one or
| more ledgers. All financial activity is scoped under the beneficiary.
|
*/
export const BeneficiarySchema = z.strictObject({
_id: z.uuid().describe("Primary identifier of the beneficiary"),
tenantId: z.string().describe("Identifier of the tenant this beneficiary belongs to"),
label: z.string().optional().describe("Human-readable name for the beneficiary"),
createdAt: z.coerce.date().describe("Timestamp when the beneficiary was created"),
});
export type Beneficiary = z.output<typeof BeneficiarySchema>;
/*
|--------------------------------------------------------------------------------
| Database
|--------------------------------------------------------------------------------
*/
export const BeneficiaryInsertSchema = z.strictObject({
tenantId: BeneficiarySchema.shape.tenantId,
label: z.string().nullable().default(null).describe("Human-readable name for the beneficiary"),
});
export type BeneficiaryInsert = z.input<typeof BeneficiaryInsertSchema>;
export const BeneficiaryUpdateSchema = z.strictObject({
_id: z.uuid().describe("Primary identifier of the beneficiary"),
label: z.string().nullable().default(null).describe("Human-readable name for the beneficiary"),
});
export type BeneficiaryUpdate = z.input<typeof BeneficiaryUpdateSchema>;

View File

@@ -0,0 +1,24 @@
import z from "zod";
/*
|--------------------------------------------------------------------------------
| Currency
|--------------------------------------------------------------------------------
|
| A union of currencies the system supports trade in.
|
*/
export const CurrencySchema = z.union([
z.literal("USD").describe("United States Dollar"),
z.literal("EUR").describe("Euro"),
z.literal("GBP").describe("British Pound Sterling"),
z.literal("CHF").describe("Swiss Franc"),
z.literal("JPY").describe("Japanese Yen"),
z.literal("CAD").describe("Canadian Dollar"),
z.literal("AUD").describe("Australian Dollar"),
z.literal("NOK").describe("Norwegian Krone"),
z.literal("SEK").describe("Swedish Krona"),
]);
export type Currency = z.output<typeof CurrencySchema>;

View File

@@ -0,0 +1,36 @@
import z from "zod";
import { CurrencySchema } from "./currency.ts";
/*
|--------------------------------------------------------------------------------
| Ledger
|--------------------------------------------------------------------------------
|
| A ledger is the primary container in which transactions are held.
|
*/
export const LedgerSchema = z.strictObject({
_id: z.uuid().describe("Primary identifier of the ledger"),
beneficiaryId: z.uuid().describe("Identifier of the beneficiary this ledger belongs to"),
label: z.string().optional().describe("Human-readable identifier for the ledger"),
currencies: z.array(CurrencySchema).describe("Currency this ledger trades in"),
createdAt: z.coerce.date().describe("Timestamp the ledger was created"),
});
export type Ledger = z.output<typeof LedgerSchema>;
/*
|--------------------------------------------------------------------------------
| Database
|--------------------------------------------------------------------------------
*/
export const LedgerInsertSchema = z.strictObject({
beneficiaryId: LedgerSchema.shape.beneficiaryId,
label: z.string().nullable().default(null).describe("Human-readable identifier for the ledger"),
currencies: LedgerSchema.shape.currencies,
});
export type LedgerInsert = z.input<typeof LedgerInsertSchema>;

View File

@@ -0,0 +1,17 @@
import z from "zod";
/*
|--------------------------------------------------------------------------------
| Transaction Participant
|--------------------------------------------------------------------------------
|
| A participant is either an internal account or an external entity.
|
*/
export const TransactionParticipantType = z.union([
z.literal("account").describe("Participant is an internal account on the ledger"),
z.literal("external").describe("Participant is a opaque external entity"),
]);
export type TransactionParticipant = z.output<typeof TransactionParticipantType>;

View File

@@ -0,0 +1,40 @@
import z from "zod";
import { TransactionParticipantType } from "./transaction-participant.ts";
/*
|--------------------------------------------------------------------------------
| Transaction
|--------------------------------------------------------------------------------
|
| A transaction is a description of value being moved from a source to a target.
| Transaction must have at least one "account" participant or it is considered
| invalid as our system does not support "external" -> "external" transactions.
|
| Which ledger the transaction resides in is determined by the participants
| account traced upwards tx -> account -> wallet -> ledger. A transaction is
| invalid if both source and target participant account leads to different
| ledgers.
|
*/
export const TransactionSchema = z.strictObject({
_id: z.uuid().describe("Primary identifier of the transaction"),
sourceType: TransactionParticipantType,
sourceId: z.string().describe("Identifier of the source sending value"),
targetType: TransactionParticipantType,
targetId: z.string().describe("Identifier of the target receiving value"),
amount: z.string().describe("Value amount being transferred"),
conversionRate: z
.number()
.optional()
.describe("Conversation rate from source to target if they operate in different currencies"),
occurredAt: z.coerce.date().describe("Timestamp of when the transaction occured"),
approvedBy: z.string().describe("Identifier of the individual who approved the transfer"),
});
export type Transaction = z.output<typeof TransactionSchema>;

View File

@@ -0,0 +1,35 @@
import z from "zod";
/*
|--------------------------------------------------------------------------------
| Wallet
|--------------------------------------------------------------------------------
|
| A wallet can hold one or more accounts and is a complete overview of entities
| funds in a ledger.
|
*/
export const WalletSchema = z.strictObject({
_id: z.uuid().describe("Primary identifier of the wallet"),
ledgerId: z.uuid().describe("Identifier of the ledger this wallet belongs to"),
entityId: z.string().describe("Identifier of the entity this wallet belongs to"),
label: z.string().optional().describe("Human-readable identifier for the wallet"),
createdAt: z.coerce.date().describe("Timestamp the wallet was created"),
});
export type Wallet = z.output<typeof WalletSchema>;
/*
|--------------------------------------------------------------------------------
| Database
|--------------------------------------------------------------------------------
*/
export const WalletInsertSchema = z.strictObject({
ledgerId: WalletSchema.shape.ledgerId,
entityId: WalletSchema.shape.entityId,
label: z.string().nullable().default(null).describe("Human-readable identifier for the wallet"),
});
export type WalletInsert = z.input<typeof WalletInsertSchema>;