Add client purchase pattern analytics
All checks were successful
Build and Deploy / build-and-deploy (push) Successful in 59s

This commit is contained in:
Cauê Faleiros
2026-07-01 10:25:07 -03:00
parent b99b60b32e
commit a26bc8813e
6 changed files with 284 additions and 3 deletions

View File

@@ -942,6 +942,58 @@ const getClientFilterOptions = async () => {
};
};
const getClientPurchasePatternAnalytics = async () => {
const result = await pool.query(`
${CUSTOMER_IDENTITY_CTE},
order_events AS (
SELECT DISTINCT ON (
${CUSTOMER_KEY_SQL},
COALESCE(NULLIF(pedido_id, ''), data_pedido || '_' || valor_pedido::text)
)
data_pedido_date,
created_at
FROM identity_orders
WHERE data_pedido_date IS NOT NULL
ORDER BY
${CUSTOMER_KEY_SQL},
COALESCE(NULLIF(pedido_id, ''), data_pedido || '_' || valor_pedido::text),
created_at ASC NULLS LAST
)
SELECT
EXTRACT(DOW FROM data_pedido_date)::int as weekday,
EXTRACT(HOUR FROM created_at AT TIME ZONE 'America/Sao_Paulo')::int as hour,
COUNT(*)::int as order_count
FROM order_events
GROUP BY weekday, hour
ORDER BY weekday ASC, hour ASC;
`);
const purchaseWeekdays = WEEKDAY_LABELS.map(label => ({ label, value: 0 }));
const purchaseHours = Array.from({ length: 24 }, (_, hour) => ({
label: `${String(hour).padStart(2, '0')}h`,
value: 0
}));
result.rows.forEach(row => {
const weekday = row.weekday === null || row.weekday === undefined ? null : Number(row.weekday);
const hour = row.hour === null || row.hour === undefined ? null : Number(row.hour);
const orderCount = toNumber(row.order_count);
if (weekday !== null && Number.isInteger(weekday) && purchaseWeekdays[weekday]) {
purchaseWeekdays[weekday].value += orderCount;
}
if (hour !== null && Number.isInteger(hour) && purchaseHours[hour]) {
purchaseHours[hour].value += orderCount;
}
});
return {
purchaseWeekdays,
purchaseHours
};
};
const getOrderGroupKey = (row) => (
row.pedido_id ||
`${row.data_pedido || getDateOnly(row.data_pedido_date) || ''}_${row.valor_pedido || 0}`
@@ -1353,6 +1405,7 @@ module.exports = {
getFrequencyScore,
getClientDetailsAnalytics,
getClientFilterOptions,
getClientPurchasePatternAnalytics,
getPreviousDate,
getRecencyScore,
getRfmAnalytics,