291 lines
9.1 KiB
TypeScript
291 lines
9.1 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
|
import { secondActor, seedProduct } from './helpers/commerce';
|
|
import { checkoutFixture, couponInput } from './helpers/checkout';
|
|
|
|
describe('date-bounded commerce activity analytics', () => {
|
|
let ctx: IdentityApp;
|
|
beforeAll(async () => {
|
|
ctx = await identityApp();
|
|
});
|
|
afterAll(async () => {
|
|
await ctx.close();
|
|
});
|
|
beforeEach(async () => {
|
|
await ctx.clearLimits();
|
|
});
|
|
const range = { from: '2026-01-01T00:00:00Z', to: '2026-01-02T00:00:00Z' };
|
|
const report = (kind = 'daily', query: object = range, token = ctx.token) =>
|
|
ctx
|
|
.api()
|
|
.get('/api/v1/analytics/commerce/' + kind)
|
|
.auth(token, { type: 'bearer' })
|
|
.query(query);
|
|
async function seed(
|
|
variantId: string,
|
|
quantity: number,
|
|
status: 'PENDING_PAYMENT' | 'CANCELLED',
|
|
expiresAt: Date,
|
|
createdAt = new Date('2026-01-01T12:00:00Z'),
|
|
currency = 'INR',
|
|
extraVariantId?: string,
|
|
) {
|
|
const value = (quantity / 10).toFixed(2);
|
|
const subtotal = ((quantity / 10) * (extraVariantId ? 2 : 1)).toFixed(2);
|
|
return ctx.db.order.create({
|
|
data: {
|
|
userId: ctx.owner.userId,
|
|
organizationId: ctx.owner.organizationId,
|
|
currency,
|
|
status,
|
|
subtotal,
|
|
discount: '0.00',
|
|
merchandiseTotal: subtotal,
|
|
addressSnapshot: { recipient: 'Private recipient' },
|
|
idempotencyKey: randomUUID(),
|
|
requestHash: 'a'.repeat(64),
|
|
createdAt,
|
|
expiresAt,
|
|
lines: {
|
|
create: [variantId, ...(extraVariantId ? [extraVariantId] : [])].map(
|
|
(id) => ({
|
|
variantId: id,
|
|
sku: 'FROZEN-SKU',
|
|
productName: 'Frozen product',
|
|
variantName: 'Frozen variant',
|
|
quantity,
|
|
unitPrice: '0.10',
|
|
lineTotal: value,
|
|
}),
|
|
),
|
|
},
|
|
},
|
|
});
|
|
}
|
|
it('aggregates exact currency totals and separates open, expired and cancelled states', async () => {
|
|
const item = await seedProduct(ctx, true);
|
|
const future = new Date(Date.now() + 3600000);
|
|
await seed(item.variant.id, 1, 'PENDING_PAYMENT', future);
|
|
await seed(
|
|
item.variant.id,
|
|
2,
|
|
'PENDING_PAYMENT',
|
|
new Date('2026-01-01T13:00:00Z'),
|
|
);
|
|
await seed(item.variant.id, 3, 'CANCELLED', future);
|
|
await seed(
|
|
item.variant.id,
|
|
4,
|
|
'PENDING_PAYMENT',
|
|
future,
|
|
new Date('2026-01-01T12:00:00Z'),
|
|
'USD',
|
|
);
|
|
const result = await report().expect(200);
|
|
expect(result.body.days).toEqual([
|
|
{
|
|
day: '2026-01-01',
|
|
currency: 'INR',
|
|
orderCount: 3,
|
|
openOrderCount: 1,
|
|
expiredOrderCount: 1,
|
|
cancelledOrderCount: 1,
|
|
capturedSubtotal: '0.60',
|
|
capturedDiscount: '0.00',
|
|
capturedMerchandiseValue: '0.60',
|
|
openMerchandiseValue: '0.10',
|
|
expiredMerchandiseValue: '0.20',
|
|
cancelledMerchandiseValue: '0.30',
|
|
},
|
|
{
|
|
day: '2026-01-01',
|
|
currency: 'USD',
|
|
orderCount: 1,
|
|
openOrderCount: 1,
|
|
expiredOrderCount: 0,
|
|
cancelledOrderCount: 0,
|
|
capturedSubtotal: '0.40',
|
|
capturedDiscount: '0.00',
|
|
capturedMerchandiseValue: '0.40',
|
|
openMerchandiseValue: '0.40',
|
|
expiredMerchandiseValue: '0.00',
|
|
cancelledMerchandiseValue: '0.00',
|
|
},
|
|
]);
|
|
expect(JSON.stringify(result.body)).not.toMatch(
|
|
/recipient|address|userId|requestHash|idempotencyKey|revenue/,
|
|
);
|
|
const usd = await report('daily', { ...range, currency: 'USD' }).expect(
|
|
200,
|
|
);
|
|
expect(usd.body.days).toHaveLength(1);
|
|
expect(usd.body.days[0].currency).toBe('USD');
|
|
});
|
|
it('uses UTC buckets and an inclusive start/exclusive end without joining line fanout', async () => {
|
|
const item = await seedProduct(ctx, true);
|
|
const extra = await seedProduct(ctx, true);
|
|
await seed(
|
|
item.variant.id,
|
|
1,
|
|
'PENDING_PAYMENT',
|
|
new Date(Date.now() + 3600000),
|
|
new Date('2026-02-01T00:00:00Z'),
|
|
'INR',
|
|
extra.variant.id,
|
|
);
|
|
await seed(
|
|
item.variant.id,
|
|
1,
|
|
'PENDING_PAYMENT',
|
|
new Date(Date.now() + 3600000),
|
|
new Date('2026-02-02T00:00:00Z'),
|
|
);
|
|
const input = {
|
|
from: '2026-02-01T05:30:00+05:30',
|
|
to: '2026-02-02T05:30:00+05:30',
|
|
};
|
|
const result = await report('daily', input).expect(200);
|
|
expect(result.body.window).toMatchObject({
|
|
from: '2026-02-01T00:00:00.000Z',
|
|
to: '2026-02-02T00:00:00.000Z',
|
|
});
|
|
expect(result.body.days).toHaveLength(1);
|
|
expect(result.body.days[0]).toMatchObject({
|
|
day: '2026-02-01',
|
|
orderCount: 1,
|
|
capturedMerchandiseValue: '0.20',
|
|
});
|
|
await report('daily', {
|
|
from: '2026-02-03T00:00:00Z',
|
|
to: '2026-02-04T00:00:00Z',
|
|
})
|
|
.expect(200)
|
|
.then((r) => expect(r.body.days).toEqual([]));
|
|
});
|
|
it('preserves frozen variant descriptors and paginates captured demand without calling it sales', async () => {
|
|
const item = await seedProduct(ctx, true);
|
|
const when = new Date('2026-03-01T12:00:00Z');
|
|
const future = new Date(Date.now() + 3600000);
|
|
await seed(item.variant.id, 1, 'PENDING_PAYMENT', future, when);
|
|
await seed(
|
|
item.variant.id,
|
|
2,
|
|
'PENDING_PAYMENT',
|
|
new Date('2026-03-01T13:00:00Z'),
|
|
when,
|
|
);
|
|
await seed(item.variant.id, 3, 'CANCELLED', future, when);
|
|
await seed(item.variant.id, 4, 'PENDING_PAYMENT', future, when, 'USD');
|
|
const variantRange = {
|
|
from: '2026-03-01T00:00:00Z',
|
|
to: '2026-03-02T00:00:00Z',
|
|
};
|
|
const result = await report('variants', {
|
|
...variantRange,
|
|
limit: 1,
|
|
}).expect(200);
|
|
expect(result.body.variants).toHaveLength(1);
|
|
expect(result.body.variants[0]).toMatchObject({
|
|
currency: 'INR',
|
|
sku: 'FROZEN-SKU',
|
|
productName: 'Frozen product',
|
|
variantName: 'Frozen variant',
|
|
orderCount: 3,
|
|
capturedQuantity: '6',
|
|
openQuantity: '1',
|
|
expiredQuantity: '2',
|
|
cancelledQuantity: '3',
|
|
capturedLineValue: '0.60',
|
|
});
|
|
const id = result.body.variants[0].variantId;
|
|
await ctx.db.productVariant.update({
|
|
where: { id },
|
|
data: { name: 'Renamed variant', price: '9.99' },
|
|
});
|
|
const updated = await report('variants', {
|
|
...variantRange,
|
|
limit: 1,
|
|
}).expect(200);
|
|
expect(updated.body.variants).toEqual(result.body.variants);
|
|
const second = await report('variants', {
|
|
...variantRange,
|
|
limit: 1,
|
|
offset: 1,
|
|
}).expect(200);
|
|
expect(second.body.variants[0].currency).toBe('USD');
|
|
});
|
|
it('reports real checkout discounts once and reflects later cancellation', async () => {
|
|
const f = await checkoutFixture(ctx);
|
|
const coupon = couponInput();
|
|
await ctx
|
|
.api()
|
|
.post('/api/v1/coupons')
|
|
.auth(ctx.token, { type: 'bearer' })
|
|
.send(coupon)
|
|
.expect(201);
|
|
const checkoutInput = { ...f.input, couponCode: coupon.code };
|
|
const created = await ctx
|
|
.api()
|
|
.post('/api/v1/checkout')
|
|
.auth(f.actor.token, { type: 'bearer' })
|
|
.send(checkoutInput)
|
|
.expect(201);
|
|
await ctx
|
|
.api()
|
|
.post('/api/v1/checkout')
|
|
.auth(f.actor.token, { type: 'bearer' })
|
|
.send(checkoutInput)
|
|
.expect(201);
|
|
const when = new Date(created.body.createdAt);
|
|
const input = {
|
|
from: when.toISOString(),
|
|
to: new Date(when.getTime() + 1).toISOString(),
|
|
};
|
|
const first = await report('daily', input).expect(200);
|
|
expect(first.body.days[0]).toMatchObject({
|
|
orderCount: 1,
|
|
capturedSubtotal: '998.00',
|
|
capturedDiscount: '99.80',
|
|
capturedMerchandiseValue: '898.20',
|
|
});
|
|
await ctx
|
|
.api()
|
|
.post('/api/v1/orders/' + created.body.id + '/cancel')
|
|
.auth(f.actor.token, { type: 'bearer' })
|
|
.expect(201);
|
|
expect(
|
|
(await report('daily', input).expect(200)).body.days[0],
|
|
).toMatchObject({
|
|
orderCount: 1,
|
|
cancelledOrderCount: 1,
|
|
cancelledMerchandiseValue: '898.20',
|
|
openOrderCount: 0,
|
|
});
|
|
});
|
|
it('enforces analytics permission, scope, date limits and strict query input', async () => {
|
|
const customer = await secondActor(ctx);
|
|
await report('daily', range, customer.token).expect(403);
|
|
const foreign = await secondActor(ctx, false, ['analytics.read']);
|
|
expect(
|
|
(await report('daily', range, foreign.token).expect(200)).body.days,
|
|
).toEqual([]);
|
|
const staff = await secondActor(ctx, true, ['analytics.read']);
|
|
await report('daily', range, staff.token).expect(200);
|
|
await ctx
|
|
.api()
|
|
.get('/api/v1/analytics/commerce/daily')
|
|
.query(range)
|
|
.expect(401);
|
|
for (const query of [
|
|
{ from: range.from },
|
|
{ ...range, to: range.from },
|
|
{ ...range, to: '2027-01-03T00:00:00Z' },
|
|
{ ...range, currency: 'inr' },
|
|
{ ...range, organizationId: foreign.organizationId },
|
|
])
|
|
await report('daily', query).expect(400);
|
|
await report('variants', { ...range, limit: 101 }).expect(400);
|
|
await report('variants', { ...range, offset: -1 }).expect(400);
|
|
});
|
|
});
|