74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { AccessStore } from '../identity/access.store';
|
|
import type { Principal } from '../identity/identity.types';
|
|
import { Prisma } from '../generated/prisma/client';
|
|
import { accountingSourceQuery } from './source-query';
|
|
import {
|
|
sourceScope,
|
|
decodeSourceCursor,
|
|
encodeSourceCursor,
|
|
} from './source-cursor';
|
|
import type { SourceQuery } from './source.schemas';
|
|
type SourceRow = {
|
|
eventType: string;
|
|
operation: string;
|
|
sourceId: string;
|
|
occurredAt: Date;
|
|
businessDate: string | null;
|
|
currency: string;
|
|
amount: string;
|
|
merchandiseAmount: string | null;
|
|
taxAmount: string | null;
|
|
shippingAmount: string | null;
|
|
relatedId: string;
|
|
relatedType: string;
|
|
counterpartyId: string;
|
|
counterpartyType: string;
|
|
reversesEventKey: string | null;
|
|
};
|
|
const fixed = (amount: string) => new Prisma.Decimal(amount).toFixed(2);
|
|
@Injectable()
|
|
export class AccountingSourceStore {
|
|
constructor(private readonly access: AccessStore) {}
|
|
events(actor: Principal, query: SourceQuery) {
|
|
return this.access.mutate(
|
|
actor,
|
|
'accounting.read',
|
|
async (tx) => {
|
|
const scope = sourceScope(actor.organizationId, query);
|
|
const cursor = decodeSourceCursor(query.cursor, scope, query);
|
|
const rows = await tx.$queryRaw<SourceRow[]>(
|
|
accountingSourceQuery(actor.organizationId, query, cursor),
|
|
);
|
|
const page = rows.slice(0, query.limit);
|
|
return {
|
|
schemaVersion: 1,
|
|
window: {
|
|
from: query.from.toISOString(),
|
|
to: query.to.toISOString(),
|
|
currency: query.currency ?? null,
|
|
kind: query.kind ?? null,
|
|
},
|
|
events: page.map((row) => ({
|
|
...row,
|
|
eventKey: row.eventType + ':' + row.sourceId,
|
|
amount: fixed(row.amount),
|
|
merchandiseAmount:
|
|
row.merchandiseAmount === null
|
|
? null
|
|
: fixed(row.merchandiseAmount),
|
|
taxAmount: row.taxAmount === null ? null : fixed(row.taxAmount),
|
|
shippingAmount:
|
|
row.shippingAmount === null ? null : fixed(row.shippingAmount),
|
|
})),
|
|
nextCursor:
|
|
rows.length > query.limit
|
|
? encodeSourceCursor(page[page.length - 1], scope)
|
|
: null,
|
|
};
|
|
},
|
|
false,
|
|
);
|
|
}
|
|
}
|