@@ -0,0 +1,249 @@
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { DashboardGranularity } from '@dukang/shared-types';
|
||||
|
||||
const COL_ALLOW = new Set([
|
||||
'u.created_at',
|
||||
'o.created_at',
|
||||
'o.paid_at',
|
||||
'p.created_at',
|
||||
's.created_at',
|
||||
'r.created_at',
|
||||
]);
|
||||
|
||||
const SERIES_COL_ALLOW = new Set([
|
||||
'promo.promo_code_id',
|
||||
'u.assoc_partner_account_id',
|
||||
'ap.activity_poster_id',
|
||||
's.partner_account_id',
|
||||
'o.user_id',
|
||||
'o.product_id',
|
||||
'r.store_id',
|
||||
]);
|
||||
|
||||
export function sqlSeriesId(column: string): Prisma.Sql {
|
||||
if (!SERIES_COL_ALLOW.has(column)) throw new Error(`bad series col ${column}`);
|
||||
return Prisma.sql`COALESCE(CAST(${Prisma.raw(column)} AS CHAR), 'none')`;
|
||||
}
|
||||
|
||||
export function shanghaiSqlBucket(column: string, grain: DashboardGranularity): Prisma.Sql {
|
||||
if (!COL_ALLOW.has(column)) throw new Error(`bad column ${column}`);
|
||||
const col = Prisma.raw(column);
|
||||
switch (grain) {
|
||||
case 'day':
|
||||
return Prisma.sql`DATE_FORMAT(CONVERT_TZ(${col}, '+00:00', '+08:00'), '%Y-%m-%d')`;
|
||||
case 'week':
|
||||
return Prisma.sql`DATE_FORMAT(DATE_SUB(DATE(CONVERT_TZ(${col}, '+00:00', '+08:00')), INTERVAL WEEKDAY(DATE(CONVERT_TZ(${col}, '+00:00', '+08:00'))) DAY), '%Y-%m-%d')`;
|
||||
case 'month':
|
||||
return Prisma.sql`DATE_FORMAT(CONVERT_TZ(${col}, '+00:00', '+08:00'), '%Y-%m')`;
|
||||
case 'quarter':
|
||||
return Prisma.sql`CONCAT(YEAR(CONVERT_TZ(${col}, '+00:00', '+08:00')), '-Q', QUARTER(CONVERT_TZ(${col}, '+00:00', '+08:00')))`;
|
||||
case 'year':
|
||||
return Prisma.sql`DATE_FORMAT(CONVERT_TZ(${col}, '+00:00', '+08:00'), '%Y')`;
|
||||
}
|
||||
}
|
||||
|
||||
export type CityFilter =
|
||||
| { kind: 'all' }
|
||||
| { kind: 'none' }
|
||||
| { kind: 'empty' }
|
||||
| { kind: 'ids'; ids: bigint[]; codes: string[] };
|
||||
|
||||
export function sqlAnd(parts: Prisma.Sql[]): Prisma.Sql {
|
||||
return parts.length ? Prisma.join(parts, ' AND ') : Prisma.sql`1=1`;
|
||||
}
|
||||
|
||||
export function sqlInBigints(columnSql: Prisma.Sql, ids: bigint[]): Prisma.Sql {
|
||||
if (!ids.length) return Prisma.sql`1=0`;
|
||||
return Prisma.sql`${columnSql} IN (${Prisma.join(ids)})`;
|
||||
}
|
||||
|
||||
export function sqlInStrings(columnSql: Prisma.Sql, values: string[]): Prisma.Sql {
|
||||
if (!values.length) return Prisma.sql`1=0`;
|
||||
return Prisma.sql`${columnSql} IN (${Prisma.join(values)})`;
|
||||
}
|
||||
|
||||
export function sqlRange(columnSql: Prisma.Sql, start: Date, endExclusive: Date): Prisma.Sql {
|
||||
return Prisma.sql`${columnSql} >= ${start} AND ${columnSql} < ${endExclusive}`;
|
||||
}
|
||||
|
||||
export type PromoPick = { none?: boolean; id?: bigint };
|
||||
|
||||
export type UserWhereOpts = {
|
||||
city: CityFilter;
|
||||
promo?: PromoPick;
|
||||
assocPartnerId?: bigint;
|
||||
activityPosterId?: bigint;
|
||||
createdStart?: Date | null;
|
||||
createdEndExclusive?: Date | null;
|
||||
createdLte?: Date | null;
|
||||
};
|
||||
|
||||
export type OrderWhereOpts = {
|
||||
city: CityFilter;
|
||||
promo?: PromoPick;
|
||||
assocPartnerId?: bigint;
|
||||
activityPosterId?: bigint;
|
||||
productId?: bigint;
|
||||
createdStart?: Date | null;
|
||||
createdEndExclusive?: Date | null;
|
||||
};
|
||||
|
||||
function sqlAssocPartnerUsers(assocPartnerId: bigint): Prisma.Sql {
|
||||
return Prisma.sql`SELECT id FROM user_user WHERE assoc_partner_account_id = ${assocPartnerId} AND status = 1 AND merged_into_user_id IS NULL`;
|
||||
}
|
||||
|
||||
function sqlActivityPosterUsers(activityPosterId: bigint): Prisma.Sql {
|
||||
return Prisma.sql`SELECT u.id FROM user_user u INNER JOIN partner_account p ON p.id = u.assoc_partner_account_id WHERE p.activity_poster_id = ${activityPosterId} AND p.is_primary = 1 AND u.status = 1 AND u.merged_into_user_id IS NULL`;
|
||||
}
|
||||
|
||||
function sqlActivityPosterPartners(activityPosterId: bigint): Prisma.Sql {
|
||||
return Prisma.sql`SELECT id FROM partner_account WHERE activity_poster_id = ${activityPosterId} AND is_primary = 1`;
|
||||
}
|
||||
|
||||
function applyPromo(parts: Prisma.Sql[], columnSql: Prisma.Sql, promo?: PromoPick) {
|
||||
if (promo?.none) parts.push(Prisma.sql`${columnSql} IS NULL`);
|
||||
else if (promo?.id !== undefined) parts.push(Prisma.sql`${columnSql} = ${promo.id}`);
|
||||
}
|
||||
|
||||
export function userSqlWhere(opts: UserWhereOpts): Prisma.Sql {
|
||||
const parts: Prisma.Sql[] = [
|
||||
Prisma.sql`u.status = 1`,
|
||||
Prisma.sql`u.merged_into_user_id IS NULL`,
|
||||
];
|
||||
if (opts.createdStart && opts.createdEndExclusive) {
|
||||
parts.push(sqlRange(Prisma.sql`u.created_at`, opts.createdStart, opts.createdEndExclusive));
|
||||
} else if (opts.createdLte) {
|
||||
parts.push(Prisma.sql`u.created_at <= ${opts.createdLte}`);
|
||||
}
|
||||
if (opts.city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||
else if (opts.city.kind === 'none') {
|
||||
parts.push(Prisma.sql`(pref.id IS NULL OR pref.selected_city_code IS NULL)`);
|
||||
} else if (opts.city.kind === 'ids') {
|
||||
parts.push(sqlInStrings(Prisma.sql`pref.selected_city_code`, opts.city.codes));
|
||||
}
|
||||
if (opts.promo?.none) parts.push(Prisma.sql`promo.id IS NULL`);
|
||||
else if (opts.promo?.id !== undefined) parts.push(Prisma.sql`promo.promo_code_id = ${opts.promo.id}`);
|
||||
if (opts.assocPartnerId !== undefined) {
|
||||
parts.push(Prisma.sql`u.assoc_partner_account_id = ${opts.assocPartnerId}`);
|
||||
}
|
||||
if (opts.activityPosterId !== undefined) {
|
||||
parts.push(Prisma.sql`u.assoc_partner_account_id IN (${sqlActivityPosterPartners(opts.activityPosterId)})`);
|
||||
}
|
||||
return sqlAnd(parts);
|
||||
}
|
||||
|
||||
export function orderSqlWhere(opts: OrderWhereOpts): Prisma.Sql {
|
||||
const parts: Prisma.Sql[] = [];
|
||||
if (opts.createdStart && opts.createdEndExclusive) {
|
||||
parts.push(sqlRange(Prisma.sql`o.created_at`, opts.createdStart, opts.createdEndExclusive));
|
||||
}
|
||||
if (opts.city.kind === 'none' || opts.city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||
else if (opts.city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`o.city_id`, opts.city.ids));
|
||||
applyPromo(parts, Prisma.sql`o.promo_code_id`, opts.promo);
|
||||
if (opts.assocPartnerId !== undefined) {
|
||||
parts.push(Prisma.sql`o.user_id IN (${sqlAssocPartnerUsers(opts.assocPartnerId)})`);
|
||||
}
|
||||
if (opts.activityPosterId !== undefined) {
|
||||
parts.push(Prisma.sql`o.user_id IN (${sqlActivityPosterUsers(opts.activityPosterId)})`);
|
||||
}
|
||||
if (opts.productId !== undefined) parts.push(Prisma.sql`o.product_id = ${opts.productId}`);
|
||||
return sqlAnd(parts.length ? parts : [Prisma.sql`1=1`]);
|
||||
}
|
||||
|
||||
export function paidOrderSqlWhere(
|
||||
opts: OrderWhereOpts & {
|
||||
paidStart: Date;
|
||||
paidEndExclusive: Date;
|
||||
partnerIdAtPay?: bigint;
|
||||
},
|
||||
): Prisma.Sql {
|
||||
const parts: Prisma.Sql[] = [
|
||||
Prisma.sql`o.pay_status = 'PAID'`,
|
||||
sqlRange(Prisma.sql`o.paid_at`, opts.paidStart, opts.paidEndExclusive),
|
||||
];
|
||||
if (opts.city.kind === 'none' || opts.city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||
else if (opts.city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`o.city_id`, opts.city.ids));
|
||||
applyPromo(parts, Prisma.sql`o.promo_code_id`, opts.promo);
|
||||
if (opts.partnerIdAtPay !== undefined) {
|
||||
parts.push(Prisma.sql`o.partner_account_id_at_pay = ${opts.partnerIdAtPay}`);
|
||||
}
|
||||
if (opts.assocPartnerId !== undefined) {
|
||||
parts.push(Prisma.sql`o.user_id IN (${sqlAssocPartnerUsers(opts.assocPartnerId)})`);
|
||||
}
|
||||
if (opts.activityPosterId !== undefined) {
|
||||
parts.push(Prisma.sql`o.user_id IN (${sqlActivityPosterUsers(opts.activityPosterId)})`);
|
||||
}
|
||||
if (opts.productId !== undefined) parts.push(Prisma.sql`o.product_id = ${opts.productId}`);
|
||||
return sqlAnd(parts);
|
||||
}
|
||||
|
||||
export function partnerSqlWhere(
|
||||
city: CityFilter,
|
||||
partnerId: bigint | undefined,
|
||||
createdStart: Date | null,
|
||||
createdEndExclusive: Date | null,
|
||||
createdLte: Date | null,
|
||||
): Prisma.Sql {
|
||||
const parts: Prisma.Sql[] = [Prisma.sql`p.is_primary = 1`];
|
||||
if (createdStart && createdEndExclusive) {
|
||||
parts.push(sqlRange(Prisma.sql`p.created_at`, createdStart, createdEndExclusive));
|
||||
} else if (createdLte) {
|
||||
parts.push(Prisma.sql`p.created_at <= ${createdLte}`);
|
||||
}
|
||||
if (city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||
else if (city.kind === 'none') parts.push(Prisma.sql`p.city_id IS NULL`);
|
||||
else if (city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`p.city_id`, city.ids));
|
||||
if (partnerId !== undefined) parts.push(Prisma.sql`p.id = ${partnerId}`);
|
||||
return sqlAnd(parts);
|
||||
}
|
||||
|
||||
export function storeSqlWhere(
|
||||
city: CityFilter,
|
||||
partnerId: bigint | undefined,
|
||||
createdStart: Date | null,
|
||||
createdEndExclusive: Date | null,
|
||||
createdLte: Date | null,
|
||||
): Prisma.Sql {
|
||||
const parts: Prisma.Sql[] = [];
|
||||
if (createdStart && createdEndExclusive) {
|
||||
parts.push(sqlRange(Prisma.sql`s.created_at`, createdStart, createdEndExclusive));
|
||||
} else if (createdLte) {
|
||||
parts.push(Prisma.sql`s.created_at <= ${createdLte}`);
|
||||
}
|
||||
if (city.kind === 'none' || city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||
else if (city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`s.city_id`, city.ids));
|
||||
if (partnerId !== undefined) parts.push(Prisma.sql`s.partner_account_id = ${partnerId}`);
|
||||
return sqlAnd(parts.length ? parts : [Prisma.sql`1=1`]);
|
||||
}
|
||||
|
||||
export function redeemSqlWhere(
|
||||
city: CityFilter,
|
||||
createdStart: Date,
|
||||
createdEndExclusive: Date,
|
||||
opts?: { storeId?: bigint; assocPartnerId?: bigint; storePartnerId?: bigint },
|
||||
): Prisma.Sql {
|
||||
const parts: Prisma.Sql[] = [
|
||||
sqlRange(Prisma.sql`r.created_at`, createdStart, createdEndExclusive),
|
||||
];
|
||||
if (city.kind === 'none' || city.kind === 'empty') parts.push(Prisma.sql`1=0`);
|
||||
else if (city.kind === 'ids') parts.push(sqlInBigints(Prisma.sql`s.city_id`, city.ids));
|
||||
if (opts?.storeId !== undefined) parts.push(Prisma.sql`r.store_id = ${opts.storeId}`);
|
||||
if (opts?.storePartnerId !== undefined) {
|
||||
parts.push(Prisma.sql`s.partner_account_id = ${opts.storePartnerId}`);
|
||||
}
|
||||
if (opts?.assocPartnerId !== undefined) {
|
||||
parts.push(Prisma.sql`r.user_id IN (${sqlAssocPartnerUsers(opts.assocPartnerId)})`);
|
||||
}
|
||||
return sqlAnd(parts);
|
||||
}
|
||||
|
||||
export function money(v: unknown): number {
|
||||
if (v == null) return 0;
|
||||
const n = typeof v === 'number' ? v : Number(v);
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
export function toCount(v: unknown): number {
|
||||
if (v == null) return 0;
|
||||
return typeof v === 'number' ? v : Number(v);
|
||||
}
|
||||
@@ -0,0 +1,909 @@
|
||||
import type {
|
||||
DashboardLineChart,
|
||||
DashboardLineHref,
|
||||
DashboardLineUnit,
|
||||
DashboardGranularity,
|
||||
HqPermissionKey,
|
||||
} from '@dukang/shared-types';
|
||||
import {
|
||||
buildDimensionLines,
|
||||
buildSingleLine,
|
||||
normalizeSeriesId,
|
||||
shanghaiYmd,
|
||||
type DashboardNamedSeries,
|
||||
type DashboardSeriesPoint,
|
||||
} from '@dukang/domain';
|
||||
import type { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import {
|
||||
type CityFilter,
|
||||
money,
|
||||
orderSqlWhere,
|
||||
paidOrderSqlWhere,
|
||||
partnerSqlWhere,
|
||||
redeemSqlWhere,
|
||||
shanghaiSqlBucket,
|
||||
sqlSeriesId,
|
||||
storeSqlWhere,
|
||||
toCount,
|
||||
userSqlWhere,
|
||||
} from './admin-dashboard-analytics';
|
||||
|
||||
const EPOCH = new Date(0);
|
||||
|
||||
type AggRow = {
|
||||
period: string | Date;
|
||||
series_id: string | null;
|
||||
series_name: string | null;
|
||||
value: unknown;
|
||||
};
|
||||
|
||||
type BaseRow = {
|
||||
series_id: string | null;
|
||||
series_name: string | null;
|
||||
value: unknown;
|
||||
};
|
||||
|
||||
export type LineQueryCtx = {
|
||||
prisma: PrismaService;
|
||||
grain: DashboardGranularity;
|
||||
city: CityFilter;
|
||||
rangeStart: Date;
|
||||
rangeEndExclusive: Date;
|
||||
periodKeys: string[];
|
||||
can: (key: HqPermissionKey) => boolean;
|
||||
};
|
||||
|
||||
function namesFrom(rows: Array<{ series_id: string | null; series_name: string | null }>): Map<string, string> {
|
||||
const map = new Map<string, string>();
|
||||
for (const row of rows) {
|
||||
const id = normalizeSeriesId(row.series_id);
|
||||
const name = (row.series_name || '').trim();
|
||||
if (id !== 'none' && name) map.set(id, name);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function periodKey(raw: string | Date): string {
|
||||
if (raw instanceof Date) return shanghaiYmd(raw);
|
||||
return String(raw);
|
||||
}
|
||||
|
||||
function toPoints(rows: AggRow[], asMoney: boolean): DashboardSeriesPoint[] {
|
||||
return rows.map((row) => ({
|
||||
seriesId: normalizeSeriesId(row.series_id),
|
||||
period: periodKey(row.period),
|
||||
value: asMoney ? money(row.value) : toCount(row.value),
|
||||
}));
|
||||
}
|
||||
|
||||
function toBaselines(rows: BaseRow[], asMoney: boolean): Array<{ seriesId: string; value: number }> {
|
||||
return rows.map((row) => ({
|
||||
seriesId: normalizeSeriesId(row.series_id),
|
||||
value: asMoney ? money(row.value) : toCount(row.value),
|
||||
}));
|
||||
}
|
||||
|
||||
function pairCharts(
|
||||
href: DashboardLineHref,
|
||||
unit: DashboardLineUnit,
|
||||
totalKey: string,
|
||||
totalTitle: string,
|
||||
incKey: string,
|
||||
incTitle: string,
|
||||
lines: { total: DashboardNamedSeries[]; increment: DashboardNamedSeries[] },
|
||||
): DashboardLineChart[] {
|
||||
return [
|
||||
{ key: totalKey, title: totalTitle, unit, href, series: lines.total },
|
||||
{ key: incKey, title: incTitle, unit, href, series: lines.increment },
|
||||
];
|
||||
}
|
||||
|
||||
function pairSingle(
|
||||
href: DashboardLineHref,
|
||||
unit: DashboardLineUnit,
|
||||
totalKey: string,
|
||||
totalTitle: string,
|
||||
incKey: string,
|
||||
incTitle: string,
|
||||
line: { total: DashboardNamedSeries; increment: DashboardNamedSeries },
|
||||
): DashboardLineChart[] {
|
||||
return pairCharts(href, unit, totalKey, totalTitle, incKey, incTitle, {
|
||||
total: [line.total],
|
||||
increment: [line.increment],
|
||||
});
|
||||
}
|
||||
|
||||
function mergeNames(...maps: Array<Map<string, string>>): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const map of maps) {
|
||||
for (const [k, v] of map) out.set(k, v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function beforeRange(rangeStart: Date): Date {
|
||||
return new Date(rangeStart.getTime() - 1);
|
||||
}
|
||||
|
||||
export async function loadDashboardLineCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const jobs: Array<Promise<DashboardLineChart[]>> = [];
|
||||
if (ctx.can('users')) jobs.push(loadUserCharts(ctx));
|
||||
if (ctx.can('partners')) jobs.push(loadPartnerCharts(ctx));
|
||||
if (ctx.can('stores')) jobs.push(loadStoreCharts(ctx));
|
||||
if (ctx.can('orders')) jobs.push(loadOrderCharts(ctx));
|
||||
if (ctx.can('benefit')) jobs.push(loadRedeemCharts(ctx));
|
||||
const groups = await Promise.all(jobs);
|
||||
return groups.flat();
|
||||
}
|
||||
|
||||
async function loadUserCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const out: DashboardLineChart[] = [];
|
||||
const dims: Array<Promise<DashboardLineChart[]>> = [];
|
||||
if (ctx.can('promo_codes')) dims.push(loadUserPromo(ctx));
|
||||
if (ctx.can('partners')) dims.push(loadUserPartner(ctx));
|
||||
if (ctx.can('activity_posters')) dims.push(loadUserActivity(ctx));
|
||||
if (dims.length) {
|
||||
out.push(...(await Promise.all(dims)).flat());
|
||||
return out;
|
||||
}
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||
NULL AS series_name, COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||
GROUP BY period
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||
`,
|
||||
]);
|
||||
return pairSingle(
|
||||
'users',
|
||||
'count',
|
||||
'users.total',
|
||||
'用户总量',
|
||||
'users.increment',
|
||||
'用户增量',
|
||||
buildSingleLine({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc, false),
|
||||
baseline: toCount(base[0]?.value),
|
||||
name: '用户',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function loadUserPromo(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('promo.promo_code_id')} AS series_id,
|
||||
MAX(CONCAT(pc.name, '(', pc.code, ')')) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
LEFT JOIN user_promo_attribution promo ON promo.user_id = u.id
|
||||
LEFT JOIN common_promo_code pc ON pc.id = promo.promo_code_id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('promo.promo_code_id')} AS series_id,
|
||||
MAX(CONCAT(pc.name, '(', pc.code, ')')) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
LEFT JOIN user_promo_attribution promo ON promo.user_id = u.id
|
||||
LEFT JOIN common_promo_code pc ON pc.id = promo.promo_code_id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
return pairCharts(
|
||||
'users',
|
||||
'count',
|
||||
'users.total.promo',
|
||||
'用户总量 · 推广码',
|
||||
'users.increment.promo',
|
||||
'用户增量 · 推广码',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc, false),
|
||||
baselines: toBaselines(base, false),
|
||||
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||
noneLabel: '自然量',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function loadUserPartner(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
return pairCharts(
|
||||
'users',
|
||||
'count',
|
||||
'users.total.partner',
|
||||
'用户总量 · 关联合伙人',
|
||||
'users.increment.partner',
|
||||
'用户增量 · 关联合伙人',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc, false),
|
||||
baselines: toBaselines(base, false),
|
||||
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||
noneLabel: '未关联',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function loadUserActivity(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('u.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('ap.activity_poster_id')} AS series_id,
|
||||
MAX(poster.title) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
LEFT JOIN partner_account ap ON ap.id = u.assoc_partner_account_id
|
||||
LEFT JOIN activity_poster poster ON poster.id = ap.activity_poster_id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('ap.activity_poster_id')} AS series_id,
|
||||
MAX(poster.title) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_user u
|
||||
LEFT JOIN user_city_preference pref ON pref.user_id = u.id
|
||||
LEFT JOIN partner_account ap ON ap.id = u.assoc_partner_account_id
|
||||
LEFT JOIN activity_poster poster ON poster.id = ap.activity_poster_id
|
||||
WHERE ${userSqlWhere({ city: ctx.city, createdLte: beforeRange(ctx.rangeStart) })}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
return pairCharts(
|
||||
'users',
|
||||
'count',
|
||||
'users.total.activity',
|
||||
'用户总量 · 活动',
|
||||
'users.increment.activity',
|
||||
'用户增量 · 活动',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc, false),
|
||||
baselines: toBaselines(base, false),
|
||||
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||
noneLabel: '无活动',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function loadPartnerCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('p.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||
NULL AS series_name, COUNT(*) AS value
|
||||
FROM partner_account p
|
||||
WHERE ${partnerSqlWhere(ctx.city, undefined, ctx.rangeStart, ctx.rangeEndExclusive, null)}
|
||||
GROUP BY period
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS value
|
||||
FROM partner_account p
|
||||
WHERE ${partnerSqlWhere(ctx.city, undefined, null, null, beforeRange(ctx.rangeStart))}
|
||||
`,
|
||||
]);
|
||||
return pairSingle(
|
||||
'partners',
|
||||
'count',
|
||||
'partners.total',
|
||||
'合伙人总量',
|
||||
'partners.increment',
|
||||
'合伙人增量',
|
||||
buildSingleLine({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc, false),
|
||||
baseline: toCount(base[0]?.value),
|
||||
name: '合伙人',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function loadStoreCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
if (!ctx.can('partners')) {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('s.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||
NULL AS series_name, COUNT(*) AS value
|
||||
FROM store_store s
|
||||
WHERE ${storeSqlWhere(ctx.city, undefined, ctx.rangeStart, ctx.rangeEndExclusive, null)}
|
||||
GROUP BY period
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS value
|
||||
FROM store_store s
|
||||
WHERE ${storeSqlWhere(ctx.city, undefined, null, null, beforeRange(ctx.rangeStart))}
|
||||
`,
|
||||
]);
|
||||
return pairSingle(
|
||||
'stores',
|
||||
'count',
|
||||
'stores.total',
|
||||
'门店总量',
|
||||
'stores.increment',
|
||||
'门店增量',
|
||||
buildSingleLine({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc, false),
|
||||
baseline: toCount(base[0]?.value),
|
||||
name: '门店',
|
||||
}),
|
||||
);
|
||||
}
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('s.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('s.partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM store_store s
|
||||
LEFT JOIN partner_account p ON p.id = s.partner_account_id
|
||||
WHERE ${storeSqlWhere(ctx.city, undefined, ctx.rangeStart, ctx.rangeEndExclusive, null)}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('s.partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM store_store s
|
||||
LEFT JOIN partner_account p ON p.id = s.partner_account_id
|
||||
WHERE ${storeSqlWhere(ctx.city, undefined, null, null, beforeRange(ctx.rangeStart))}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
return pairCharts(
|
||||
'stores',
|
||||
'count',
|
||||
'stores.total.partner',
|
||||
'门店总量 · 关联合伙人',
|
||||
'stores.increment.partner',
|
||||
'门店增量 · 关联合伙人',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc, false),
|
||||
baselines: toBaselines(base, false),
|
||||
names: mergeNames(namesFrom(inc), namesFrom(base)),
|
||||
noneLabel: '未关联',
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function loadOrderCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const user = await loadOrderUser(ctx);
|
||||
const partner = ctx.can('partners') ? await loadOrderPartner(ctx) : [];
|
||||
const product = await loadOrderProduct(ctx);
|
||||
const take = (charts: DashboardLineChart[], unit: DashboardLineUnit) =>
|
||||
charts.filter((c) => c.unit === unit);
|
||||
return [
|
||||
...take(user, 'count'),
|
||||
...take(partner, 'count'),
|
||||
...take(product, 'count'),
|
||||
...take(user, 'amount'),
|
||||
...take(partner, 'amount'),
|
||||
...take(product, 'amount'),
|
||||
];
|
||||
}
|
||||
|
||||
async function loadOrderUser(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [countInc, countBase, amountInc, amountBase] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('o.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('o.user_id')} AS series_id,
|
||||
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('o.user_id')} AS series_id,
|
||||
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: EPOCH, createdEndExclusive: ctx.rangeStart })}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('o.paid_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('o.user_id')} AS series_id,
|
||||
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
WHERE ${paidOrderSqlWhere({
|
||||
city: ctx.city,
|
||||
paidStart: ctx.rangeStart,
|
||||
paidEndExclusive: ctx.rangeEndExclusive,
|
||||
})}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('o.user_id')} AS series_id,
|
||||
MAX(COALESCE(NULLIF(u.nickname, ''), u.user_no)) AS series_name,
|
||||
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
WHERE ${paidOrderSqlWhere({
|
||||
city: ctx.city,
|
||||
paidStart: EPOCH,
|
||||
paidEndExclusive: ctx.rangeStart,
|
||||
})}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
const countNames = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||
const amountNames = mergeNames(namesFrom(amountInc), namesFrom(amountBase));
|
||||
return [
|
||||
...pairCharts(
|
||||
'orders',
|
||||
'count',
|
||||
'orders.count.total.user',
|
||||
'订单笔数总量 · 用户',
|
||||
'orders.count.increment.user',
|
||||
'订单笔数增量 · 用户',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(countInc, false),
|
||||
baselines: toBaselines(countBase, false),
|
||||
names: countNames,
|
||||
noneLabel: '未知用户',
|
||||
}),
|
||||
),
|
||||
...pairCharts(
|
||||
'orders',
|
||||
'amount',
|
||||
'orders.amount.total.user',
|
||||
'订单金额总量 · 用户',
|
||||
'orders.amount.increment.user',
|
||||
'订单金额增量 · 用户',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(amountInc, true),
|
||||
baselines: toBaselines(amountBase, true),
|
||||
names: amountNames,
|
||||
noneLabel: '未知用户',
|
||||
round: money,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
async function loadOrderPartner(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [countInc, countBase, amountInc, amountBase] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('o.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: EPOCH, createdEndExclusive: ctx.rangeStart })}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('o.paid_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${paidOrderSqlWhere({
|
||||
city: ctx.city,
|
||||
paidStart: ctx.rangeStart,
|
||||
paidEndExclusive: ctx.rangeEndExclusive,
|
||||
})}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||
FROM user_order o
|
||||
INNER JOIN user_user u ON u.id = o.user_id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${paidOrderSqlWhere({
|
||||
city: ctx.city,
|
||||
paidStart: EPOCH,
|
||||
paidEndExclusive: ctx.rangeStart,
|
||||
})}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
const countNames = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||
const amountNames = mergeNames(namesFrom(amountInc), namesFrom(amountBase));
|
||||
return [
|
||||
...pairCharts(
|
||||
'orders',
|
||||
'count',
|
||||
'orders.count.total.partner',
|
||||
'订单笔数总量 · 关联合伙人',
|
||||
'orders.count.increment.partner',
|
||||
'订单笔数增量 · 关联合伙人',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(countInc, false),
|
||||
baselines: toBaselines(countBase, false),
|
||||
names: countNames,
|
||||
noneLabel: '未关联',
|
||||
}),
|
||||
),
|
||||
...pairCharts(
|
||||
'orders',
|
||||
'amount',
|
||||
'orders.amount.total.partner',
|
||||
'订单金额总量 · 关联合伙人',
|
||||
'orders.amount.increment.partner',
|
||||
'订单金额增量 · 关联合伙人',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(amountInc, true),
|
||||
baselines: toBaselines(amountBase, true),
|
||||
names: amountNames,
|
||||
noneLabel: '未关联',
|
||||
round: money,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
async function loadOrderProduct(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [countInc, countBase, amountInc, amountBase] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('o.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('o.product_id')} AS series_id,
|
||||
MAX(o.product_name) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_order o
|
||||
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: ctx.rangeStart, createdEndExclusive: ctx.rangeEndExclusive })}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('o.product_id')} AS series_id,
|
||||
MAX(o.product_name) AS series_name,
|
||||
COUNT(*) AS value
|
||||
FROM user_order o
|
||||
WHERE ${orderSqlWhere({ city: ctx.city, createdStart: EPOCH, createdEndExclusive: ctx.rangeStart })}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<AggRow[]>`
|
||||
SELECT ${shanghaiSqlBucket('o.paid_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('o.product_id')} AS series_id,
|
||||
MAX(o.product_name) AS series_name,
|
||||
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||
FROM user_order o
|
||||
WHERE ${paidOrderSqlWhere({
|
||||
city: ctx.city,
|
||||
paidStart: ctx.rangeStart,
|
||||
paidEndExclusive: ctx.rangeEndExclusive,
|
||||
})}
|
||||
GROUP BY period, series_id
|
||||
`,
|
||||
ctx.prisma.$queryRaw<BaseRow[]>`
|
||||
SELECT ${sqlSeriesId('o.product_id')} AS series_id,
|
||||
MAX(o.product_name) AS series_name,
|
||||
COALESCE(SUM(o.pay_amount), 0) AS value
|
||||
FROM user_order o
|
||||
WHERE ${paidOrderSqlWhere({
|
||||
city: ctx.city,
|
||||
paidStart: EPOCH,
|
||||
paidEndExclusive: ctx.rangeStart,
|
||||
})}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
const countNames = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||
const amountNames = mergeNames(namesFrom(amountInc), namesFrom(amountBase));
|
||||
return [
|
||||
...pairCharts(
|
||||
'orders',
|
||||
'count',
|
||||
'orders.count.total.product',
|
||||
'订单笔数总量 · 商品',
|
||||
'orders.count.increment.product',
|
||||
'订单笔数增量 · 商品',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(countInc, false),
|
||||
baselines: toBaselines(countBase, false),
|
||||
names: countNames,
|
||||
noneLabel: '未知商品',
|
||||
}),
|
||||
),
|
||||
...pairCharts(
|
||||
'orders',
|
||||
'amount',
|
||||
'orders.amount.total.product',
|
||||
'订单金额总量 · 商品',
|
||||
'orders.amount.increment.product',
|
||||
'订单金额增量 · 商品',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(amountInc, true),
|
||||
baselines: toBaselines(amountBase, true),
|
||||
names: amountNames,
|
||||
noneLabel: '未知商品',
|
||||
round: money,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
async function loadRedeemCharts(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const store = ctx.can('stores') ? await loadRedeemStore(ctx) : [];
|
||||
const partner = ctx.can('partners') ? await loadRedeemPartner(ctx) : [];
|
||||
if (!store.length && !partner.length) return loadRedeemSingle(ctx);
|
||||
const take = (charts: DashboardLineChart[], unit: DashboardLineUnit) =>
|
||||
charts.filter((c) => c.unit === unit);
|
||||
return [
|
||||
...take(store, 'count'),
|
||||
...take(partner, 'count'),
|
||||
...take(store, 'amount'),
|
||||
...take(partner, 'amount'),
|
||||
];
|
||||
}
|
||||
|
||||
async function loadRedeemStore(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<Array<AggRow & { cnt: unknown; amount: unknown }>>`
|
||||
SELECT ${shanghaiSqlBucket('r.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('r.store_id')} AS series_id,
|
||||
MAX(s.name) AS series_name,
|
||||
COUNT(*) AS cnt,
|
||||
COALESCE(SUM(r.amount), 0) AS amount
|
||||
FROM user_redeem_record r
|
||||
INNER JOIN store_store s ON s.id = r.store_id
|
||||
WHERE ${redeemSqlWhere(ctx.city, ctx.rangeStart, ctx.rangeEndExclusive)}
|
||||
GROUP BY period, series_id
|
||||
`.then(splitCountAmount),
|
||||
ctx.prisma.$queryRaw<Array<BaseRow & { cnt: unknown; amount: unknown }>>`
|
||||
SELECT ${sqlSeriesId('r.store_id')} AS series_id,
|
||||
MAX(s.name) AS series_name,
|
||||
COUNT(*) AS cnt,
|
||||
COALESCE(SUM(r.amount), 0) AS amount
|
||||
FROM user_redeem_record r
|
||||
INNER JOIN store_store s ON s.id = r.store_id
|
||||
WHERE ${redeemSqlWhere(ctx.city, EPOCH, ctx.rangeStart)}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
const countInc = inc.count;
|
||||
const amountInc = inc.amount;
|
||||
const countBase: BaseRow[] = base.map((r) => ({
|
||||
series_id: r.series_id,
|
||||
series_name: r.series_name,
|
||||
value: r.cnt,
|
||||
}));
|
||||
const amountBase: BaseRow[] = base.map((r) => ({
|
||||
series_id: r.series_id,
|
||||
series_name: r.series_name,
|
||||
value: r.amount,
|
||||
}));
|
||||
const names = mergeNames(namesFrom(countInc), namesFrom(countBase));
|
||||
return [
|
||||
...pairCharts(
|
||||
'redeems',
|
||||
'count',
|
||||
'redeems.count.total.store',
|
||||
'核销单数总量 · 门店',
|
||||
'redeems.count.increment.store',
|
||||
'核销单数增量 · 门店',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(countInc, false),
|
||||
baselines: toBaselines(countBase, false),
|
||||
names,
|
||||
noneLabel: '未知门店',
|
||||
}),
|
||||
),
|
||||
...pairCharts(
|
||||
'redeems',
|
||||
'amount',
|
||||
'redeems.amount.total.store',
|
||||
'核销金额总量 · 门店',
|
||||
'redeems.amount.increment.store',
|
||||
'核销金额增量 · 门店',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(amountInc, true),
|
||||
baselines: toBaselines(amountBase, true),
|
||||
names,
|
||||
noneLabel: '未知门店',
|
||||
round: money,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
async function loadRedeemPartner(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<Array<AggRow & { cnt: unknown; amount: unknown }>>`
|
||||
SELECT ${shanghaiSqlBucket('r.created_at', ctx.grain)} AS period,
|
||||
${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS cnt,
|
||||
COALESCE(SUM(r.amount), 0) AS amount
|
||||
FROM user_redeem_record r
|
||||
INNER JOIN store_store s ON s.id = r.store_id
|
||||
INNER JOIN user_user u ON u.id = r.user_id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${redeemSqlWhere(ctx.city, ctx.rangeStart, ctx.rangeEndExclusive)}
|
||||
GROUP BY period, series_id
|
||||
`.then(splitCountAmount),
|
||||
ctx.prisma.$queryRaw<Array<BaseRow & { cnt: unknown; amount: unknown }>>`
|
||||
SELECT ${sqlSeriesId('u.assoc_partner_account_id')} AS series_id,
|
||||
MAX(CONCAT(COALESCE(NULLIF(p.company_name, ''), '未填企业'), '-', COALESCE(NULLIF(p.name, ''), '未填姓名'))) AS series_name,
|
||||
COUNT(*) AS cnt,
|
||||
COALESCE(SUM(r.amount), 0) AS amount
|
||||
FROM user_redeem_record r
|
||||
INNER JOIN store_store s ON s.id = r.store_id
|
||||
INNER JOIN user_user u ON u.id = r.user_id
|
||||
LEFT JOIN partner_account p ON p.id = u.assoc_partner_account_id
|
||||
WHERE ${redeemSqlWhere(ctx.city, EPOCH, ctx.rangeStart)}
|
||||
GROUP BY series_id
|
||||
`,
|
||||
]);
|
||||
const countBase: BaseRow[] = base.map((r) => ({
|
||||
series_id: r.series_id,
|
||||
series_name: r.series_name,
|
||||
value: r.cnt,
|
||||
}));
|
||||
const amountBase: BaseRow[] = base.map((r) => ({
|
||||
series_id: r.series_id,
|
||||
series_name: r.series_name,
|
||||
value: r.amount,
|
||||
}));
|
||||
const names = mergeNames(namesFrom(inc.count), namesFrom(countBase));
|
||||
return [
|
||||
...pairCharts(
|
||||
'redeems',
|
||||
'count',
|
||||
'redeems.count.total.partner',
|
||||
'核销单数总量 · 关联合伙人',
|
||||
'redeems.count.increment.partner',
|
||||
'核销单数增量 · 关联合伙人',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc.count, false),
|
||||
baselines: toBaselines(countBase, false),
|
||||
names,
|
||||
noneLabel: '未关联',
|
||||
}),
|
||||
),
|
||||
...pairCharts(
|
||||
'redeems',
|
||||
'amount',
|
||||
'redeems.amount.total.partner',
|
||||
'核销金额总量 · 关联合伙人',
|
||||
'redeems.amount.increment.partner',
|
||||
'核销金额增量 · 关联合伙人',
|
||||
buildDimensionLines({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc.amount, true),
|
||||
baselines: toBaselines(amountBase, true),
|
||||
names,
|
||||
noneLabel: '未关联',
|
||||
round: money,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
async function loadRedeemSingle(ctx: LineQueryCtx): Promise<DashboardLineChart[]> {
|
||||
const [inc, base] = await Promise.all([
|
||||
ctx.prisma.$queryRaw<Array<AggRow & { cnt: unknown; amount: unknown }>>`
|
||||
SELECT ${shanghaiSqlBucket('r.created_at', ctx.grain)} AS period, 'all' AS series_id,
|
||||
NULL AS series_name, COUNT(*) AS cnt, COALESCE(SUM(r.amount), 0) AS amount
|
||||
FROM user_redeem_record r
|
||||
INNER JOIN store_store s ON s.id = r.store_id
|
||||
WHERE ${redeemSqlWhere(ctx.city, ctx.rangeStart, ctx.rangeEndExclusive)}
|
||||
GROUP BY period
|
||||
`.then(splitCountAmount),
|
||||
ctx.prisma.$queryRaw<Array<BaseRow & { cnt: unknown; amount: unknown }>>`
|
||||
SELECT 'all' AS series_id, NULL AS series_name, COUNT(*) AS cnt, COALESCE(SUM(r.amount), 0) AS amount
|
||||
FROM user_redeem_record r
|
||||
INNER JOIN store_store s ON s.id = r.store_id
|
||||
WHERE ${redeemSqlWhere(ctx.city, EPOCH, ctx.rangeStart)}
|
||||
`,
|
||||
]);
|
||||
return [
|
||||
...pairSingle(
|
||||
'redeems',
|
||||
'count',
|
||||
'redeems.count.total',
|
||||
'核销单数总量',
|
||||
'redeems.count.increment',
|
||||
'核销单数增量',
|
||||
buildSingleLine({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc.count, false),
|
||||
baseline: toCount(base[0]?.cnt),
|
||||
name: '核销单数',
|
||||
}),
|
||||
),
|
||||
...pairSingle(
|
||||
'redeems',
|
||||
'amount',
|
||||
'redeems.amount.total',
|
||||
'核销金额总量',
|
||||
'redeems.amount.increment',
|
||||
'核销金额增量',
|
||||
buildSingleLine({
|
||||
periodKeys: ctx.periodKeys,
|
||||
points: toPoints(inc.amount, true),
|
||||
baseline: money(base[0]?.amount),
|
||||
name: '核销金额',
|
||||
round: money,
|
||||
}),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
function splitCountAmount(
|
||||
rows: Array<AggRow & { cnt: unknown; amount: unknown }>,
|
||||
): { count: AggRow[]; amount: AggRow[] } {
|
||||
return {
|
||||
count: rows.map((r) => ({
|
||||
period: r.period,
|
||||
series_id: r.series_id,
|
||||
series_name: r.series_name,
|
||||
value: r.cnt,
|
||||
})),
|
||||
amount: rows.map((r) => ({
|
||||
period: r.period,
|
||||
series_id: r.series_id,
|
||||
series_name: r.series_name,
|
||||
value: r.amount,
|
||||
})),
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,17 @@
|
||||
import { ForbiddenException, Injectable } from '@nestjs/common';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { HqPermissionKey } from '@dukang/shared-types';
|
||||
import type {
|
||||
DashboardAnalytics,
|
||||
DashboardGranularity,
|
||||
HqPermissionKey,
|
||||
} from '@dukang/shared-types';
|
||||
import {
|
||||
addShanghaiDays,
|
||||
defaultShanghaiRangeYmds,
|
||||
eachShanghaiBuckets,
|
||||
parseShanghaiYmd,
|
||||
shanghaiYmd,
|
||||
} from '@dukang/domain';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import {
|
||||
HqPermissionsResolver,
|
||||
@@ -9,43 +20,8 @@ import {
|
||||
type HqCityScope,
|
||||
} from '../../common/guards/hq-permission.guard';
|
||||
import type { AdminDashboardAnalyticsQueryDto } from './dto/admin-query.dto';
|
||||
|
||||
function startOfDay(d: Date) {
|
||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0);
|
||||
}
|
||||
|
||||
function endOfDay(d: Date) {
|
||||
return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999);
|
||||
}
|
||||
|
||||
function parseYmd(s: string): Date | null {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
|
||||
const d = new Date(`${s}T00:00:00`);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
function formatYmd(d: Date): string {
|
||||
const y = d.getFullYear();
|
||||
const m = String(d.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(d.getDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
function eachDate(from: Date, to: Date): string[] {
|
||||
const out: string[] = [];
|
||||
const cur = startOfDay(from);
|
||||
const end = startOfDay(to);
|
||||
while (cur <= end) {
|
||||
out.push(formatYmd(cur));
|
||||
cur.setDate(cur.getDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function num(v: Prisma.Decimal | number | string | null | undefined): number {
|
||||
if (v == null) return 0;
|
||||
return typeof v === 'number' ? v : Number(v);
|
||||
}
|
||||
import { type CityFilter } from './admin-dashboard-analytics';
|
||||
import { loadDashboardLineCharts } from './admin-dashboard-lines';
|
||||
|
||||
function isWithdrawOverdue(appliedAt: Date, now = new Date()): boolean {
|
||||
const day = appliedAt.getDay();
|
||||
@@ -296,17 +272,20 @@ export class AdminDashboardService {
|
||||
};
|
||||
}
|
||||
|
||||
async getAnalytics(actorId: bigint, query: AdminDashboardAnalyticsQueryDto) {
|
||||
const today = startOfDay(new Date());
|
||||
const defaultFrom = new Date(today);
|
||||
defaultFrom.setDate(defaultFrom.getDate() - 29);
|
||||
|
||||
const from =
|
||||
(query.dateFrom ? parseYmd(query.dateFrom) : null) ?? defaultFrom;
|
||||
const to =
|
||||
(query.dateTo ? parseYmd(query.dateTo) : null) ?? today;
|
||||
const rangeStart = startOfDay(from <= to ? from : to);
|
||||
const rangeEnd = endOfDay(from <= to ? to : from);
|
||||
async getAnalytics(
|
||||
actorId: bigint,
|
||||
query: AdminDashboardAnalyticsQueryDto,
|
||||
): Promise<DashboardAnalytics> {
|
||||
const grain: DashboardGranularity = query.granularity ?? 'day';
|
||||
const defaults = defaultShanghaiRangeYmds(grain);
|
||||
const fromYmd = /^\d{4}-\d{2}-\d{2}$/.test(query.dateFrom ?? '')
|
||||
? query.dateFrom!
|
||||
: defaults.from;
|
||||
const toYmd = /^\d{4}-\d{2}-\d{2}$/.test(query.dateTo ?? '') ? query.dateTo! : defaults.to;
|
||||
const fromDay = parseShanghaiYmd(fromYmd <= toYmd ? fromYmd : toYmd);
|
||||
const toDay = parseShanghaiYmd(fromYmd <= toYmd ? toYmd : fromYmd);
|
||||
const rangeStart = fromDay;
|
||||
const rangeEndExclusive = addShanghaiDays(toDay, 1);
|
||||
|
||||
const [{ keys, isSuperAdmin }, scope] = await Promise.all([
|
||||
this.hqPermissions.resolveAccess(actorId),
|
||||
@@ -314,518 +293,46 @@ export class AdminDashboardService {
|
||||
]);
|
||||
const can = (k: HqPermissionKey) => isSuperAdmin || keys.includes(k);
|
||||
|
||||
let filterCityCode: string | string[] | null | undefined;
|
||||
let filterCityId: bigint | bigint[] | null | undefined;
|
||||
let city: CityFilter = { kind: 'all' };
|
||||
if (query.cityId === 'none') {
|
||||
if (scope !== null) {
|
||||
throw new ForbiddenException('无权按未选城筛选');
|
||||
}
|
||||
filterCityCode = null;
|
||||
filterCityId = null;
|
||||
if (scope !== null) throw new ForbiddenException('无权按未选城筛选');
|
||||
city = { kind: 'none' };
|
||||
} else if (query.cityId) {
|
||||
const city = await this.prisma.commonCity.findUnique({
|
||||
const row = await this.prisma.commonCity.findUnique({
|
||||
where: { id: BigInt(query.cityId) },
|
||||
select: { id: true, code: true },
|
||||
});
|
||||
if (!city) {
|
||||
throw new ForbiddenException('无权访问该城市的门店');
|
||||
}
|
||||
assertHqCityInScope(scope, city.id);
|
||||
filterCityCode = city.code;
|
||||
filterCityId = city.id;
|
||||
if (!row) throw new ForbiddenException('无权访问该城市的门店');
|
||||
assertHqCityInScope(scope, row.id);
|
||||
city = { kind: 'ids', ids: [row.id], codes: [row.code] };
|
||||
} else if (scope !== null) {
|
||||
if (!scope.length) {
|
||||
filterCityId = [];
|
||||
filterCityCode = [];
|
||||
city = { kind: 'empty' };
|
||||
} else {
|
||||
const scopedCities = await this.prisma.commonCity.findMany({
|
||||
where: { id: { in: scope } },
|
||||
select: { id: true, code: true },
|
||||
});
|
||||
filterCityId = scope;
|
||||
filterCityCode = scopedCities.map((c) => c.code);
|
||||
city = { kind: 'ids', ids: scope, codes: scopedCities.map((c) => c.code) };
|
||||
}
|
||||
}
|
||||
|
||||
const filterPromoNone = query.promoCodeId === 'none';
|
||||
const filterPromoId =
|
||||
can('promo_codes') && query.promoCodeId && query.promoCodeId !== 'none'
|
||||
? BigInt(query.promoCodeId)
|
||||
: undefined;
|
||||
const filterPartnerId =
|
||||
can('partners') && query.partnerAccountId
|
||||
? BigInt(query.partnerAccountId)
|
||||
: undefined;
|
||||
|
||||
if (filterPartnerId !== undefined && scope !== null) {
|
||||
const partner = await this.prisma.partnerAccount.findUnique({
|
||||
where: { id: filterPartnerId },
|
||||
select: { cityId: true },
|
||||
});
|
||||
if (partner?.cityId) {
|
||||
assertHqCityInScope(scope, partner.cityId);
|
||||
} else if (scope !== null) {
|
||||
throw new ForbiddenException('无权访问该城市的门店');
|
||||
}
|
||||
}
|
||||
|
||||
const userWhere: Prisma.UserWhereInput = {
|
||||
status: 1,
|
||||
mergedIntoUserId: null,
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityCode === null) {
|
||||
userWhere.OR = [
|
||||
{ cityPreference: null },
|
||||
{ cityPreference: { selectedCityCode: null } },
|
||||
];
|
||||
} else if (Array.isArray(filterCityCode)) {
|
||||
userWhere.cityPreference = {
|
||||
selectedCityCode: { in: filterCityCode.length ? filterCityCode : [''] },
|
||||
};
|
||||
} else if (filterCityCode) {
|
||||
userWhere.cityPreference = { selectedCityCode: filterCityCode };
|
||||
}
|
||||
if (can('promo_codes') && filterPromoNone) {
|
||||
userWhere.promoTouch = { is: null };
|
||||
} else if (filterPromoId !== undefined) {
|
||||
userWhere.promoTouch = { promoCodeId: filterPromoId };
|
||||
}
|
||||
|
||||
const orderWhere: Prisma.OrderWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
orderWhere.id = { in: [] };
|
||||
} else if (Array.isArray(filterCityId)) {
|
||||
orderWhere.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
||||
} else if (filterCityId !== undefined) {
|
||||
orderWhere.cityId = filterCityId;
|
||||
}
|
||||
if (can('promo_codes') && filterPromoNone) {
|
||||
orderWhere.promoCodeId = null;
|
||||
} else if (filterPromoId !== undefined) {
|
||||
orderWhere.promoCodeId = filterPromoId;
|
||||
}
|
||||
|
||||
const partnerWhere: Prisma.PartnerAccountWhereInput = {
|
||||
isPrimary: 1,
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
partnerWhere.cityId = null;
|
||||
} else if (Array.isArray(filterCityId)) {
|
||||
partnerWhere.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
||||
} else if (filterCityId !== undefined) {
|
||||
partnerWhere.cityId = filterCityId;
|
||||
}
|
||||
if (filterPartnerId !== undefined) {
|
||||
partnerWhere.id = filterPartnerId;
|
||||
}
|
||||
|
||||
const storeWhere: Prisma.StoreWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
storeWhere.id = { in: [] };
|
||||
} else if (Array.isArray(filterCityId)) {
|
||||
storeWhere.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
||||
} else if (filterCityId !== undefined) {
|
||||
storeWhere.cityId = filterCityId;
|
||||
}
|
||||
if (filterPartnerId !== undefined) {
|
||||
storeWhere.partnerAccountId = filterPartnerId;
|
||||
}
|
||||
|
||||
const redeemWhere: Prisma.RedeemRecordWhereInput = {
|
||||
createdAt: { gte: rangeStart, lte: rangeEnd },
|
||||
};
|
||||
if (filterCityId === null) {
|
||||
redeemWhere.id = { in: [] };
|
||||
} else {
|
||||
const storeFilter: Prisma.StoreWhereInput = {};
|
||||
if (Array.isArray(filterCityId)) {
|
||||
storeFilter.cityId = { in: filterCityId.length ? filterCityId : [BigInt(0)] };
|
||||
} else if (filterCityId !== undefined) {
|
||||
storeFilter.cityId = filterCityId;
|
||||
}
|
||||
if (filterPartnerId !== undefined) storeFilter.partnerAccountId = filterPartnerId;
|
||||
if (Object.keys(storeFilter).length) {
|
||||
redeemWhere.store = storeFilter;
|
||||
}
|
||||
}
|
||||
|
||||
const skipOrders = filterCityId === null || !can('orders');
|
||||
const cityListWhere: Prisma.CommonCityWhereInput =
|
||||
scope === null ? {} : { id: { in: scope.length ? scope : [BigInt(0)] } };
|
||||
|
||||
const [users, orders, partners, stores, redeems, cities, promos, partnerNames] =
|
||||
await Promise.all([
|
||||
can('users')
|
||||
? this.prisma.user.findMany({
|
||||
where: userWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityPreference: { select: { selectedCityCode: true } },
|
||||
promoTouch: { select: { promoCodeId: true } },
|
||||
},
|
||||
})
|
||||
: emptyRows<
|
||||
Prisma.UserGetPayload<{
|
||||
select: {
|
||||
id: true;
|
||||
createdAt: true;
|
||||
cityPreference: { select: { selectedCityCode: true } };
|
||||
promoTouch: { select: { promoCodeId: true } };
|
||||
};
|
||||
}>
|
||||
>(),
|
||||
skipOrders
|
||||
? emptyRows<
|
||||
Prisma.OrderGetPayload<{
|
||||
select: {
|
||||
id: true;
|
||||
userId: true;
|
||||
createdAt: true;
|
||||
cityId: true;
|
||||
promoCodeId: true;
|
||||
payStatus: true;
|
||||
};
|
||||
}>
|
||||
>()
|
||||
: this.prisma.order.findMany({
|
||||
where: orderWhere,
|
||||
select: {
|
||||
id: true,
|
||||
userId: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
promoCodeId: true,
|
||||
payStatus: true,
|
||||
},
|
||||
}),
|
||||
can('partners')
|
||||
? this.prisma.partnerAccount.findMany({
|
||||
where: partnerWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
companyName: true,
|
||||
name: true,
|
||||
},
|
||||
})
|
||||
: emptyRows<
|
||||
Prisma.PartnerAccountGetPayload<{
|
||||
select: { id: true; createdAt: true; cityId: true; companyName: true; name: true };
|
||||
}>
|
||||
>(),
|
||||
can('stores')
|
||||
? this.prisma.store.findMany({
|
||||
where: storeWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
cityId: true,
|
||||
partnerAccountId: true,
|
||||
},
|
||||
})
|
||||
: emptyRows<
|
||||
Prisma.StoreGetPayload<{
|
||||
select: { id: true; createdAt: true; cityId: true; partnerAccountId: true };
|
||||
}>
|
||||
>(),
|
||||
can('benefit')
|
||||
? this.prisma.redeemRecord.findMany({
|
||||
where: redeemWhere,
|
||||
select: {
|
||||
id: true,
|
||||
createdAt: true,
|
||||
amount: true,
|
||||
settleAmount: true,
|
||||
store: { select: { cityId: true, partnerAccountId: true } },
|
||||
},
|
||||
})
|
||||
: emptyRows<
|
||||
Prisma.RedeemRecordGetPayload<{
|
||||
select: {
|
||||
id: true;
|
||||
createdAt: true;
|
||||
amount: true;
|
||||
settleAmount: true;
|
||||
store: { select: { cityId: true; partnerAccountId: true } };
|
||||
};
|
||||
}>
|
||||
>(),
|
||||
this.prisma.commonCity.findMany({
|
||||
where: cityListWhere,
|
||||
select: { id: true, code: true, name: true },
|
||||
}),
|
||||
can('promo_codes')
|
||||
? this.prisma.commonPromoCode.findMany({
|
||||
select: { id: true, code: true, name: true },
|
||||
})
|
||||
: emptyRows<Prisma.CommonPromoCodeGetPayload<{ select: { id: true; code: true; name: true } }>>(),
|
||||
can('partners') || can('stores') || can('benefit')
|
||||
? this.prisma.partnerAccount.findMany({
|
||||
where: {
|
||||
isPrimary: 1,
|
||||
...(cityIdFilter(scope) ? { cityId: cityIdFilter(scope) } : {}),
|
||||
},
|
||||
select: { id: true, companyName: true, name: true },
|
||||
})
|
||||
: emptyRows<
|
||||
Prisma.PartnerAccountGetPayload<{
|
||||
select: { id: true; companyName: true; name: true };
|
||||
}>
|
||||
>(),
|
||||
]);
|
||||
|
||||
const cityByCode = new Map(cities.map((c) => [c.code, c]));
|
||||
const cityById = new Map(cities.map((c) => [c.id.toString(), c]));
|
||||
const promoById = new Map(promos.map((p) => [p.id.toString(), p]));
|
||||
const partnerLabel = new Map(
|
||||
partnerNames.map((p) => [
|
||||
p.id.toString(),
|
||||
p.companyName || p.name || `合伙人#${p.id}`,
|
||||
]),
|
||||
);
|
||||
|
||||
const dateKeys = eachDate(rangeStart, rangeEnd);
|
||||
type DateBucket = {
|
||||
date: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
const byDateMap = new Map<string, DateBucket>(
|
||||
dateKeys.map((d) => [
|
||||
d,
|
||||
{ date: d, users: 0, orders: 0, partners: 0, stores: 0, redeems: 0, redeemAmount: 0 },
|
||||
]),
|
||||
);
|
||||
|
||||
type CityBucket = {
|
||||
cityId: string;
|
||||
cityName: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
partners: number;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
const byCityMap = new Map<string, CityBucket>();
|
||||
|
||||
type PromoBucket = {
|
||||
promoCodeId: string | null;
|
||||
code: string;
|
||||
name: string;
|
||||
users: number;
|
||||
orders: number;
|
||||
};
|
||||
const byPromoMap = new Map<string, PromoBucket>();
|
||||
|
||||
type PartnerBucket = {
|
||||
partnerAccountId: string;
|
||||
companyName: string;
|
||||
stores: number;
|
||||
redeems: number;
|
||||
redeemAmount: number;
|
||||
};
|
||||
const byPartnerMap = new Map<string, PartnerBucket>();
|
||||
|
||||
const ensureCity = (key: string, cityId: string, cityName: string) => {
|
||||
let b = byCityMap.get(key);
|
||||
if (!b) {
|
||||
b = {
|
||||
cityId,
|
||||
cityName,
|
||||
users: 0,
|
||||
orders: 0,
|
||||
partners: 0,
|
||||
stores: 0,
|
||||
redeems: 0,
|
||||
redeemAmount: 0,
|
||||
};
|
||||
byCityMap.set(key, b);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
|
||||
const ensurePromo = (
|
||||
key: string,
|
||||
promoCodeId: string | null,
|
||||
code: string,
|
||||
name: string,
|
||||
) => {
|
||||
let b = byPromoMap.get(key);
|
||||
if (!b) {
|
||||
b = { promoCodeId, code, name, users: 0, orders: 0 };
|
||||
byPromoMap.set(key, b);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
|
||||
const ensurePartner = (key: string, companyName: string) => {
|
||||
let b = byPartnerMap.get(key);
|
||||
if (!b) {
|
||||
b = {
|
||||
partnerAccountId: key,
|
||||
companyName,
|
||||
stores: 0,
|
||||
redeems: 0,
|
||||
redeemAmount: 0,
|
||||
};
|
||||
byPartnerMap.set(key, b);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
|
||||
for (const u of users) {
|
||||
const d = formatYmd(u.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.users += 1;
|
||||
|
||||
const code = u.cityPreference?.selectedCityCode ?? null;
|
||||
if (code && cityByCode.has(code)) {
|
||||
const city = cityByCode.get(code)!;
|
||||
ensureCity(city.id.toString(), city.id.toString(), city.name).users += 1;
|
||||
} else {
|
||||
ensureCity('none', 'none', '未选城').users += 1;
|
||||
}
|
||||
|
||||
const pid = u.promoTouch?.promoCodeId?.toString() ?? null;
|
||||
if (pid && promoById.has(pid)) {
|
||||
const p = promoById.get(pid)!;
|
||||
ensurePromo(pid, pid, p.code, p.name).users += 1;
|
||||
} else {
|
||||
ensurePromo('none', null, 'ORGANIC', '自然量').users += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const payingUserIds = new Set<string>();
|
||||
for (const o of orders) {
|
||||
const d = formatYmd(o.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.orders += 1;
|
||||
|
||||
const cid = o.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).orders += 1;
|
||||
|
||||
const pid = o.promoCodeId?.toString() ?? null;
|
||||
if (pid && promoById.has(pid)) {
|
||||
const p = promoById.get(pid)!;
|
||||
ensurePromo(pid, pid, p.code, p.name).orders += 1;
|
||||
} else {
|
||||
ensurePromo('none', null, 'NONE', '无推广码').orders += 1;
|
||||
}
|
||||
|
||||
if (o.payStatus === 'PAID') {
|
||||
payingUserIds.add(o.userId.toString());
|
||||
}
|
||||
}
|
||||
|
||||
for (const p of partners) {
|
||||
const d = formatYmd(p.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.partners += 1;
|
||||
|
||||
if (p.cityId) {
|
||||
const cid = p.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).partners += 1;
|
||||
} else {
|
||||
ensureCity('none', 'none', '未绑定城市').partners += 1;
|
||||
}
|
||||
|
||||
const key = p.id.toString();
|
||||
ensurePartner(key, p.companyName || p.name || `合伙人#${key}`);
|
||||
}
|
||||
|
||||
for (const s of stores) {
|
||||
const d = formatYmd(s.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) day.stores += 1;
|
||||
|
||||
const cid = s.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
ensureCity(cid, cid, city?.name ?? `城市#${cid}`).stores += 1;
|
||||
|
||||
const pid = s.partnerAccountId.toString();
|
||||
ensurePartner(pid, partnerLabel.get(pid) || `合伙人#${pid}`).stores += 1;
|
||||
}
|
||||
|
||||
let redeemAmountTotal = 0;
|
||||
for (const r of redeems) {
|
||||
const amount = num(r.amount);
|
||||
redeemAmountTotal += amount;
|
||||
|
||||
const d = formatYmd(r.createdAt);
|
||||
const day = byDateMap.get(d);
|
||||
if (day) {
|
||||
day.redeems += 1;
|
||||
day.redeemAmount += amount;
|
||||
}
|
||||
|
||||
const cid = r.store.cityId.toString();
|
||||
const city = cityById.get(cid);
|
||||
const cityBucket = ensureCity(cid, cid, city?.name ?? `城市#${cid}`);
|
||||
cityBucket.redeems += 1;
|
||||
cityBucket.redeemAmount += amount;
|
||||
|
||||
const pid = r.store.partnerAccountId.toString();
|
||||
const partnerBucket = ensurePartner(
|
||||
pid,
|
||||
partnerLabel.get(pid) || `合伙人#${pid}`,
|
||||
);
|
||||
partnerBucket.redeems += 1;
|
||||
partnerBucket.redeemAmount += amount;
|
||||
}
|
||||
|
||||
const byCity = [...byCityMap.values()].sort(
|
||||
(a, b) =>
|
||||
b.users + b.orders + b.partners + b.stores + b.redeems -
|
||||
(a.users + a.orders + a.partners + a.stores + a.redeems),
|
||||
);
|
||||
const byPromo = [...byPromoMap.values()].sort(
|
||||
(a, b) => b.users + b.orders - (a.users + a.orders),
|
||||
);
|
||||
const byPartner = [...byPartnerMap.values()].sort(
|
||||
(a, b) => b.stores + b.redeems - (a.stores + a.redeems),
|
||||
);
|
||||
const buckets = eachShanghaiBuckets(rangeStart, toDay, grain);
|
||||
const charts = await loadDashboardLineCharts({
|
||||
prisma: this.prisma,
|
||||
grain,
|
||||
city,
|
||||
rangeStart,
|
||||
rangeEndExclusive,
|
||||
periodKeys: buckets.map((b) => b.key),
|
||||
can,
|
||||
});
|
||||
|
||||
return {
|
||||
summary: {
|
||||
users: users.length,
|
||||
orders: orders.length,
|
||||
payingUsers: payingUserIds.size,
|
||||
partners: partners.length,
|
||||
stores: stores.length,
|
||||
redeems: redeems.length,
|
||||
redeemAmount: Math.round(redeemAmountTotal * 100) / 100,
|
||||
},
|
||||
byDate: dateKeys.map((d) => {
|
||||
const row = byDateMap.get(d)!;
|
||||
return {
|
||||
...row,
|
||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
||||
};
|
||||
}),
|
||||
byCity: byCity.map((row) => ({
|
||||
...row,
|
||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
||||
})),
|
||||
byPromo,
|
||||
byPartner: byPartner.map((row) => ({
|
||||
...row,
|
||||
redeemAmount: Math.round(row.redeemAmount * 100) / 100,
|
||||
})),
|
||||
granularity: grain,
|
||||
range: { from: shanghaiYmd(fromDay), to: shanghaiYmd(toDay) },
|
||||
periods: buckets.map((b) => ({ key: b.key, label: b.label })),
|
||||
charts,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { BadRequestException, Body, Controller, Get, Param, Post, Put, UseGuards } from '@nestjs/common';
|
||||
import type { UpdateWecomReportPushRequest } from '@dukang/shared-types';
|
||||
import { HqAuthGuard } from '../../common/guards/hq-auth.guard';
|
||||
import {
|
||||
HqPermissionGuard,
|
||||
RequireHqPermissions,
|
||||
} from '../../common/guards/hq-permission.guard';
|
||||
import { HqOperation } from '../../common/hq-operation/hq-operation.decorator';
|
||||
import { HqOperationAction } from '../../common/hq-operation/hq-operation.constants';
|
||||
import { AdminWecomReportsService } from './admin-wecom-reports.service';
|
||||
|
||||
@Controller('admin/wecom-reports')
|
||||
@UseGuards(HqAuthGuard, HqPermissionGuard)
|
||||
@RequireHqPermissions('wecom_bots')
|
||||
export class AdminWecomReportsController {
|
||||
constructor(private readonly service: AdminWecomReportsService) {}
|
||||
|
||||
@Get()
|
||||
list() {
|
||||
return this.service.list();
|
||||
}
|
||||
|
||||
@Get(':kind')
|
||||
detail(@Param('kind') kind: string) {
|
||||
return this.service.detail(this.service.parseKind(kind));
|
||||
}
|
||||
|
||||
@Put(':kind')
|
||||
@HqOperation({
|
||||
action: HqOperationAction.WECOM_REPORT_UPDATE,
|
||||
refType: 'WECOM_REPORT',
|
||||
refIdField: 'kind',
|
||||
includeBody: true,
|
||||
})
|
||||
update(@Param('kind') kind: string, @Body() body: UpdateWecomReportPushRequest) {
|
||||
return this.service.update(this.service.parseKind(kind), body);
|
||||
}
|
||||
|
||||
@Post(':kind/preview')
|
||||
preview(@Param('kind') kind: string) {
|
||||
return this.service.preview(this.service.parseKind(kind));
|
||||
}
|
||||
|
||||
@Post(':kind/send')
|
||||
@HqOperation({
|
||||
action: HqOperationAction.WECOM_REPORT_SEND,
|
||||
refType: 'WECOM_REPORT',
|
||||
refIdField: 'kind',
|
||||
})
|
||||
async send(@Param('kind') kind: string) {
|
||||
const result = await this.service.send(this.service.parseKind(kind));
|
||||
if (!result.ok) throw new BadRequestException(result.message);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
Logger,
|
||||
NotFoundException,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { Cron } from '@nestjs/schedule';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import {
|
||||
formatWecomReportMarkdown,
|
||||
isWecomReportKind,
|
||||
wecomReportCutoff,
|
||||
wecomReportPeriod,
|
||||
wecomReportShouldFire,
|
||||
type WecomReportKind,
|
||||
type WecomReportStats,
|
||||
} from '@dukang/domain';
|
||||
import {
|
||||
maskWecomWebhookUrl,
|
||||
WECOM_REPORT_KIND_LABELS,
|
||||
WECOM_STORE_AUDIT_PLACEHOLDER_WEBHOOK,
|
||||
type UpdateWecomReportPushRequest,
|
||||
type WecomReportPreviewDto,
|
||||
type WecomReportPushDto,
|
||||
type WecomReportSendResultDto,
|
||||
} from '@dukang/shared-types';
|
||||
import { PrismaService } from '../../common/prisma/prisma.module';
|
||||
import { applyWecomAtMentionInContent } from '../../modules/dev-plan/dev-plan-wecom-mention.util';
|
||||
import { WecomMessagePushService } from '../../integrations/wecom/wecom-message-push.service';
|
||||
|
||||
const KIND_SEED: Array<{
|
||||
kind: WecomReportKind;
|
||||
name: string;
|
||||
sendHour: number;
|
||||
sendMinute: number;
|
||||
}> = [
|
||||
{ kind: 'daily', name: '经营日报', sendHour: 20, sendMinute: 0 },
|
||||
{ kind: 'weekly', name: '经营周报', sendHour: 9, sendMinute: 0 },
|
||||
{ kind: 'monthly', name: '经营月报', sendHour: 9, sendMinute: 0 },
|
||||
];
|
||||
|
||||
function asNumber(v: Prisma.Decimal | number | null | undefined): number {
|
||||
if (v == null) return 0;
|
||||
if (typeof v === 'number') return Number.isFinite(v) ? v : 0;
|
||||
return Number(v);
|
||||
}
|
||||
|
||||
function clampHour(n: number | undefined, fallback: number): number {
|
||||
if (n == null || !Number.isFinite(n)) return fallback;
|
||||
return Math.min(23, Math.max(0, Math.floor(n)));
|
||||
}
|
||||
|
||||
function clampMinute(n: number | undefined, fallback: number): number {
|
||||
if (n == null || !Number.isFinite(n)) return fallback;
|
||||
return Math.min(59, Math.max(0, Math.floor(n)));
|
||||
}
|
||||
|
||||
type ReportRow = {
|
||||
id: bigint;
|
||||
kind: string;
|
||||
name: string;
|
||||
webhookUrl: string;
|
||||
enabled: boolean | number;
|
||||
mentionWecomUserId: string | null;
|
||||
sendHour: number;
|
||||
sendMinute: number;
|
||||
sendWeekday: number;
|
||||
sendMonthDay: number;
|
||||
lastSentPeriod: string | null;
|
||||
lastSentAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
function asBool(v: boolean | number): boolean {
|
||||
return v === true || v === 1;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminWecomReportsService implements OnModuleInit {
|
||||
private readonly logger = new Logger(AdminWecomReportsService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly wecomPush: WecomMessagePushService,
|
||||
) {}
|
||||
|
||||
async onModuleInit(): Promise<void> {
|
||||
try {
|
||||
await this.ensureDefaults();
|
||||
} catch (e) {
|
||||
this.logger.warn(
|
||||
`wecom report ensureDefaults failed: ${e instanceof Error ? e.message : String(e)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async ensureDefaults(): Promise<void> {
|
||||
for (const seed of KIND_SEED) {
|
||||
await this.prisma.$executeRaw`
|
||||
INSERT IGNORE INTO wecom_report_push
|
||||
(kind, name, webhook_url, enabled, send_hour, send_minute, send_weekday, send_month_day)
|
||||
VALUES
|
||||
(${seed.kind}, ${seed.name}, ${WECOM_STORE_AUDIT_PLACEHOLDER_WEBHOOK}, 0, ${seed.sendHour}, ${seed.sendMinute}, 1, 1)
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
private async findByKind(kind: string): Promise<ReportRow | null> {
|
||||
const rows = await this.prisma.$queryRaw<ReportRow[]>`
|
||||
SELECT id, kind, name,
|
||||
webhook_url AS webhookUrl, enabled,
|
||||
mention_wecom_user_id AS mentionWecomUserId,
|
||||
send_hour AS sendHour, send_minute AS sendMinute,
|
||||
send_weekday AS sendWeekday, send_month_day AS sendMonthDay,
|
||||
last_sent_period AS lastSentPeriod, last_sent_at AS lastSentAt,
|
||||
created_at AS createdAt, updated_at AS updatedAt
|
||||
FROM wecom_report_push WHERE kind = ${kind} LIMIT 1
|
||||
`;
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
private async findAll(): Promise<ReportRow[]> {
|
||||
return this.prisma.$queryRaw<ReportRow[]>`
|
||||
SELECT id, kind, name,
|
||||
webhook_url AS webhookUrl, enabled,
|
||||
mention_wecom_user_id AS mentionWecomUserId,
|
||||
send_hour AS sendHour, send_minute AS sendMinute,
|
||||
send_weekday AS sendWeekday, send_month_day AS sendMonthDay,
|
||||
last_sent_period AS lastSentPeriod, last_sent_at AS lastSentAt,
|
||||
created_at AS createdAt, updated_at AS updatedAt
|
||||
FROM wecom_report_push
|
||||
`;
|
||||
}
|
||||
|
||||
parseKind(raw: string): WecomReportKind {
|
||||
if (!isWecomReportKind(raw)) {
|
||||
throw new BadRequestException('报告类型须为 daily / weekly / monthly');
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
async list(): Promise<WecomReportPushDto[]> {
|
||||
await this.ensureDefaults();
|
||||
const rows = await this.findAll();
|
||||
const byKind = new Map(rows.map((r) => [r.kind, r]));
|
||||
return KIND_SEED.map((s) => {
|
||||
const row = byKind.get(s.kind);
|
||||
if (!row) throw new NotFoundException(`${WECOM_REPORT_KIND_LABELS[s.kind]}未初始化`);
|
||||
return this.toDto(row);
|
||||
});
|
||||
}
|
||||
|
||||
async detail(kind: WecomReportKind): Promise<WecomReportPushDto> {
|
||||
await this.ensureDefaults();
|
||||
const row = await this.findByKind(kind);
|
||||
if (!row) throw new NotFoundException('报告配置不存在');
|
||||
return this.toDto(row);
|
||||
}
|
||||
|
||||
async update(kind: WecomReportKind, dto: UpdateWecomReportPushRequest): Promise<WecomReportPushDto> {
|
||||
await this.ensureDefaults();
|
||||
const existing = await this.findByKind(kind);
|
||||
if (!existing) throw new NotFoundException('报告配置不存在');
|
||||
|
||||
const webhookUrl =
|
||||
dto.webhookUrl !== undefined ? dto.webhookUrl.trim() : existing.webhookUrl;
|
||||
if (!webhookUrl) throw new BadRequestException('请填写 Webhook URL');
|
||||
|
||||
const name = dto.name !== undefined ? dto.name.trim() || existing.name : existing.name;
|
||||
const enabled = dto.enabled !== undefined ? (dto.enabled ? 1 : 0) : asBool(existing.enabled) ? 1 : 0;
|
||||
const mention =
|
||||
dto.mentionWecomUserId === undefined
|
||||
? existing.mentionWecomUserId
|
||||
: dto.mentionWecomUserId?.trim() || null;
|
||||
const sendHour = dto.sendHour !== undefined ? clampHour(dto.sendHour, existing.sendHour) : existing.sendHour;
|
||||
const sendMinute =
|
||||
dto.sendMinute !== undefined ? clampMinute(dto.sendMinute, existing.sendMinute) : existing.sendMinute;
|
||||
const sendWeekday =
|
||||
dto.sendWeekday !== undefined
|
||||
? Math.min(7, Math.max(1, Math.floor(dto.sendWeekday) || 1))
|
||||
: existing.sendWeekday;
|
||||
const sendMonthDay =
|
||||
dto.sendMonthDay !== undefined
|
||||
? Math.min(31, Math.max(1, Math.floor(dto.sendMonthDay) || 1))
|
||||
: existing.sendMonthDay;
|
||||
|
||||
await this.prisma.$executeRaw`
|
||||
UPDATE wecom_report_push SET
|
||||
name = ${name},
|
||||
webhook_url = ${webhookUrl},
|
||||
enabled = ${enabled},
|
||||
mention_wecom_user_id = ${mention},
|
||||
send_hour = ${sendHour},
|
||||
send_minute = ${sendMinute},
|
||||
send_weekday = ${sendWeekday},
|
||||
send_month_day = ${sendMonthDay}
|
||||
WHERE kind = ${kind}
|
||||
`;
|
||||
const row = await this.findByKind(kind);
|
||||
if (!row) throw new NotFoundException('报告配置不存在');
|
||||
return this.toDto(row);
|
||||
}
|
||||
|
||||
async preview(kind: WecomReportKind): Promise<WecomReportPreviewDto> {
|
||||
const period = wecomReportPeriod(kind);
|
||||
const stats = await this.loadStats(period.start, wecomReportCutoff(period));
|
||||
return {
|
||||
kind,
|
||||
periodKey: period.periodKey,
|
||||
title: period.title,
|
||||
rangeLabel: period.rangeLabel,
|
||||
markdown: formatWecomReportMarkdown(period, stats),
|
||||
stats,
|
||||
};
|
||||
}
|
||||
|
||||
async send(kind: WecomReportKind, opts?: { markSent?: boolean }): Promise<WecomReportSendResultDto> {
|
||||
await this.ensureDefaults();
|
||||
const row = await this.findByKind(kind);
|
||||
if (!row) throw new NotFoundException('报告配置不存在');
|
||||
const url = row.webhookUrl.trim();
|
||||
if (!url || url.includes('key=PENDING')) {
|
||||
throw new BadRequestException('请先填写有效的企微群机器人 Webhook');
|
||||
}
|
||||
|
||||
const period = wecomReportPeriod(kind);
|
||||
const stats = await this.loadStats(period.start, wecomReportCutoff(period));
|
||||
let content = formatWecomReportMarkdown(period, stats);
|
||||
if (row.mentionWecomUserId) {
|
||||
content = applyWecomAtMentionInContent(content, row.mentionWecomUserId);
|
||||
}
|
||||
const ok = await this.wecomPush.sendMarkdownToWebhook(url, content);
|
||||
if (!ok) {
|
||||
throw new BadRequestException('Webhook 发送失败,请检查地址或群机器人是否可用');
|
||||
}
|
||||
if (opts?.markSent !== false) {
|
||||
const sentAt = new Date();
|
||||
await this.prisma.$executeRaw`
|
||||
UPDATE wecom_report_push
|
||||
SET last_sent_period = ${period.periodKey}, last_sent_at = ${sentAt}
|
||||
WHERE kind = ${kind}
|
||||
`;
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
message: `已发送${WECOM_REPORT_KIND_LABELS[kind]}`,
|
||||
periodKey: period.periodKey,
|
||||
};
|
||||
}
|
||||
|
||||
@Cron('* * * * *', { timeZone: 'Asia/Shanghai' })
|
||||
async tickScheduled(): Promise<void> {
|
||||
try {
|
||||
await this.ensureDefaults();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const now = new Date();
|
||||
const rows = await this.findAll();
|
||||
for (const row of rows) {
|
||||
if (!asBool(row.enabled)) continue;
|
||||
if (!isWecomReportKind(row.kind)) continue;
|
||||
const due = wecomReportShouldFire(
|
||||
row.kind,
|
||||
{
|
||||
enabled: asBool(row.enabled),
|
||||
sendHour: row.sendHour,
|
||||
sendMinute: row.sendMinute,
|
||||
sendWeekday: row.sendWeekday,
|
||||
sendMonthDay: row.sendMonthDay,
|
||||
lastSentPeriod: row.lastSentPeriod,
|
||||
},
|
||||
now,
|
||||
);
|
||||
if (!due) continue;
|
||||
try {
|
||||
await this.send(row.kind);
|
||||
this.logger.log(`sent wecom ${row.kind} report period=${wecomReportPeriod(row.kind, now).periodKey}`);
|
||||
} catch (e) {
|
||||
this.logger.warn(
|
||||
`wecom ${row.kind} report send failed: ${e instanceof Error ? e.message : String(e)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async loadStats(start: Date, cutoff: Date): Promise<WecomReportStats> {
|
||||
const userBase = { status: 1, mergedIntoUserId: null } as const;
|
||||
const partnerBase = { isPrimary: 1 } as const;
|
||||
const paid = { payStatus: 'PAID' as const };
|
||||
|
||||
const [
|
||||
usersTotal,
|
||||
usersIncrement,
|
||||
partnersTotal,
|
||||
partnersIncrement,
|
||||
storesTotal,
|
||||
storesIncrement,
|
||||
ordersTotal,
|
||||
ordersIncrement,
|
||||
orderAmountTotal,
|
||||
orderAmountIncrement,
|
||||
redeemsTotal,
|
||||
redeemsIncrement,
|
||||
redeemAmountTotal,
|
||||
redeemAmountIncrement,
|
||||
] = await Promise.all([
|
||||
this.prisma.user.count({ where: { ...userBase, createdAt: { lt: cutoff } } }),
|
||||
this.prisma.user.count({
|
||||
where: { ...userBase, createdAt: { gte: start, lt: cutoff } },
|
||||
}),
|
||||
this.prisma.partnerAccount.count({
|
||||
where: { ...partnerBase, createdAt: { lt: cutoff } },
|
||||
}),
|
||||
this.prisma.partnerAccount.count({
|
||||
where: { ...partnerBase, createdAt: { gte: start, lt: cutoff } },
|
||||
}),
|
||||
this.prisma.store.count({ where: { createdAt: { lt: cutoff } } }),
|
||||
this.prisma.store.count({ where: { createdAt: { gte: start, lt: cutoff } } }),
|
||||
this.prisma.order.count({ where: { createdAt: { lt: cutoff } } }),
|
||||
this.prisma.order.count({ where: { createdAt: { gte: start, lt: cutoff } } }),
|
||||
this.prisma.order.aggregate({
|
||||
_sum: { payAmount: true },
|
||||
where: { ...paid, paidAt: { lt: cutoff } },
|
||||
}),
|
||||
this.prisma.order.aggregate({
|
||||
_sum: { payAmount: true },
|
||||
where: { ...paid, paidAt: { gte: start, lt: cutoff } },
|
||||
}),
|
||||
this.prisma.redeemRecord.count({ where: { createdAt: { lt: cutoff } } }),
|
||||
this.prisma.redeemRecord.count({ where: { createdAt: { gte: start, lt: cutoff } } }),
|
||||
this.prisma.redeemRecord.aggregate({
|
||||
_sum: { amount: true },
|
||||
where: { createdAt: { lt: cutoff } },
|
||||
}),
|
||||
this.prisma.redeemRecord.aggregate({
|
||||
_sum: { amount: true },
|
||||
where: { createdAt: { gte: start, lt: cutoff } },
|
||||
}),
|
||||
]);
|
||||
|
||||
return {
|
||||
usersTotal,
|
||||
usersIncrement,
|
||||
partnersTotal,
|
||||
partnersIncrement,
|
||||
storesTotal,
|
||||
storesIncrement,
|
||||
ordersTotal,
|
||||
ordersIncrement,
|
||||
orderAmountTotal: asNumber(orderAmountTotal._sum.payAmount),
|
||||
orderAmountIncrement: asNumber(orderAmountIncrement._sum.payAmount),
|
||||
redeemsTotal,
|
||||
redeemsIncrement,
|
||||
redeemAmountTotal: asNumber(redeemAmountTotal._sum.amount),
|
||||
redeemAmountIncrement: asNumber(redeemAmountIncrement._sum.amount),
|
||||
};
|
||||
}
|
||||
|
||||
private toDto(row: ReportRow): WecomReportPushDto {
|
||||
return {
|
||||
id: String(row.id),
|
||||
kind: row.kind as WecomReportKind,
|
||||
name: row.name,
|
||||
webhookUrl: row.webhookUrl,
|
||||
webhookUrlMasked: maskWecomWebhookUrl(row.webhookUrl),
|
||||
enabled: asBool(row.enabled),
|
||||
mentionWecomUserId: row.mentionWecomUserId,
|
||||
sendHour: row.sendHour,
|
||||
sendMinute: row.sendMinute,
|
||||
sendWeekday: row.sendWeekday,
|
||||
sendMonthDay: row.sendMonthDay,
|
||||
lastSentPeriod: row.lastSentPeriod,
|
||||
lastSentAt: row.lastSentAt ? row.lastSentAt.toISOString() : null,
|
||||
createdAt: row.createdAt.toISOString(),
|
||||
updatedAt: row.updatedAt.toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -233,9 +233,13 @@ export class AdminOrdersExportDto {
|
||||
columns?: string[];
|
||||
}
|
||||
|
||||
/** 概览页用户/订单 ECharts 聚合筛选 */
|
||||
/** 概览页折线图:只吃全局粒度 / 日期 / 城市 */
|
||||
export class AdminDashboardAnalyticsQueryDto {
|
||||
/** YYYY-MM-DD,默认近 30 天 */
|
||||
@IsOptional()
|
||||
@IsIn(['day', 'week', 'month', 'quarter', 'year'])
|
||||
granularity?: 'day' | 'week' | 'month' | 'quarter' | 'year';
|
||||
|
||||
/** YYYY-MM-DD,默认随粒度 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
dateFrom?: string;
|
||||
@@ -248,16 +252,6 @@ export class AdminDashboardAnalyticsQueryDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
cityId?: string;
|
||||
|
||||
/** 推广码 id;`none` = 无归因 / 订单无推广码 */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
promoCodeId?: string;
|
||||
|
||||
/** 城市合伙人(主账号)id */
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
partnerAccountId?: string;
|
||||
}
|
||||
|
||||
export class AdminStoresQueryDto extends PaginationQueryDto {
|
||||
|
||||
@@ -69,6 +69,8 @@ import { AdminWecomBotsController } from './admin-wecom-bots.controller';
|
||||
import { AdminWecomBotsService } from './admin-wecom-bots.service';
|
||||
import { AdminWecomMessagePushesController } from './admin-wecom-message-pushes.controller';
|
||||
import { AdminWecomMessagePushesService } from './admin-wecom-message-pushes.service';
|
||||
import { AdminWecomReportsController } from './admin-wecom-reports.controller';
|
||||
import { AdminWecomReportsService } from './admin-wecom-reports.service';
|
||||
import { AdminWecomPushTemplatesController } from './admin-wecom-push-templates.controller';
|
||||
import { AdminWecomBotLogsController } from './admin-wecom-bot-logs.controller';
|
||||
import { AdminWecomBotLogsService } from './admin-wecom-bot-logs.service';
|
||||
@@ -128,6 +130,7 @@ import { PartnerActivityPostersController } from './partner-activity-posters.con
|
||||
AdminSystemConfigController,
|
||||
AdminWecomBotsController,
|
||||
AdminWecomMessagePushesController,
|
||||
AdminWecomReportsController,
|
||||
AdminWecomPushTemplatesController,
|
||||
AdminWecomBotLogsController,
|
||||
AdminLlmConfigsController,
|
||||
@@ -166,6 +169,7 @@ import { PartnerActivityPostersController } from './partner-activity-posters.con
|
||||
AdminDeployService,
|
||||
AdminWecomBotsService,
|
||||
AdminWecomMessagePushesService,
|
||||
AdminWecomReportsService,
|
||||
AdminWecomBotLogsService,
|
||||
AdminLlmConfigsService,
|
||||
AdminKnowledgeBasesService,
|
||||
|
||||
Reference in New Issue
Block a user