Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
231 lines
11 KiB
TypeScript
231 lines
11 KiB
TypeScript
import { ORDER_TYPE_LABEL, ORDER_TYPE_TONE, orderTypeOf, type CategoryTone, type OrderType } from "@/app/lib/services/adminWebOrders";
|
|
import { apiGet } from "@/app/lib/clientApi";
|
|
import type { WebOrderPage } from "@/app/lib/types";
|
|
import type { Translate } from "@/app/lib/i18n/t";
|
|
import { getKycCounts } from "./adminKyc";
|
|
import { listRefunds } from "./adminRefunds";
|
|
import { listWarrantyClaims } from "./adminWarranty";
|
|
import { listReviews } from "./adminProductReviews";
|
|
import { getPendingWithdrawals } from "./adminWithdrawals";
|
|
import { listWebOrders } from "./adminWebOrders";
|
|
|
|
// Client wrappers for the live Dashboard / Reports BFF routes (add-admin-dashboard-live-data). Periods are inclusive
|
|
// `yyyy-MM-dd` Malaysia dates (see lib/malaysiaPeriod); an empty/absent bound means unbounded.
|
|
|
|
/** `date` is an ISO Malaysia date; `byRank` holds OTTER, SQUIRREL and GIRAFFE. */
|
|
export interface DayRankCounts { date: string; byRank: Record<string, number> }
|
|
export interface MemberSummary {
|
|
total: number;
|
|
active: number;
|
|
/** New members in the period (the name predates periods). */
|
|
newThisMonth: number;
|
|
byRank: Record<string, number>;
|
|
byStatus: Record<string, number>;
|
|
newPerDay: DayRankCounts[];
|
|
}
|
|
export interface DayRevenue { date: string; revenue: number; orders: number }
|
|
export interface ChannelRevenue { channel: string; platform?: string | null; revenue: number; orders: number }
|
|
export interface SalesSummary {
|
|
daily: DayRevenue[];
|
|
byChannel: ChannelRevenue[];
|
|
periodRevenue: number;
|
|
periodOrders: number;
|
|
}
|
|
export interface RewardTypeTotal { rewardCode: string; walletType: string; total: number; count: number }
|
|
export interface TopEarner { memberCode: string; name: string | null; total: number }
|
|
/** The KPI figures of the equal-length period ending the day before `from` (BABYBOO-25). */
|
|
export interface PreviousPeriod {
|
|
from: string;
|
|
to: string;
|
|
members: MemberSummary;
|
|
sales: SalesSummary;
|
|
rewardTotals: RewardTypeTotal[];
|
|
}
|
|
export interface DashboardData {
|
|
from: string;
|
|
to: string;
|
|
members: MemberSummary;
|
|
sales: SalesSummary;
|
|
rewardTotals: RewardTypeTotal[];
|
|
/** Apple credits only. */
|
|
topEarners: TopEarner[];
|
|
previous: PreviousPeriod;
|
|
}
|
|
|
|
export interface RewardCreditRow {
|
|
date: string;
|
|
memberCode: string;
|
|
memberName: string | null;
|
|
rewardCode: string;
|
|
walletType: string;
|
|
amount: number;
|
|
sourceMemberCode: string | null;
|
|
}
|
|
/** `refunds`: approved refund amount per listed order uuid; `periodRevenue` is already net of refunds. */
|
|
export interface SalesReport { orders: WebOrderPage; refunds?: Record<string, number>; periodRevenue: number; periodOrders: number }
|
|
export interface RewardsReport {
|
|
credits: { content: RewardCreditRow[]; number: number; size: number; totalElements: number; totalPages: number };
|
|
totals: RewardTypeTotal[];
|
|
}
|
|
|
|
export interface PeriodParams { from?: string; to?: string; country?: string }
|
|
export interface SalesReportParams extends PeriodParams { page: number; size: number; sortBy?: string; sortDir?: "asc" | "desc" }
|
|
export interface RewardsReportParams extends SalesReportParams { rewardCode?: string }
|
|
|
|
const REWARD_LABELS: Record<string, string> = {
|
|
SELF_ACORN: "DashRewardSelfAcorn",
|
|
REPEAT_ACORN_1000: "DashRewardRepeatAcorn1000",
|
|
REPEAT_ACORN_2000: "DashRewardRepeatAcorn2000",
|
|
REPEAT_ACORN_3000: "DashRewardRepeatAcorn3000",
|
|
SPONSOR_ACORN: "DashRewardSponsorAcorn",
|
|
SPONSOR_APPLE: "DashRewardSponsorApple",
|
|
PROMOTION_APPLE: "DashRewardPromotionApple",
|
|
PROMOTION_ACORN: "DashRewardPromotionAcorn",
|
|
};
|
|
|
|
|
|
export type ChannelType = OrderType | "OTHER";
|
|
const ROWS: { type: ChannelType; always: boolean }[] = [
|
|
{ type: "WEB", always: true },
|
|
{ type: "COUNTER", always: false },
|
|
{ type: "EVENT", always: true },
|
|
{ type: "OUTLET", always: true },
|
|
{ type: "OTHER", always: false },
|
|
];
|
|
|
|
/** Revenue by channel as the Sales listing's order types (channel + source platform). */
|
|
export const channelRows = (byChannel: ChannelRevenue[]) =>
|
|
ROWS.map(({ type, always }) => {
|
|
const mine = byChannel.filter(c => (orderTypeOf(c.channel, c.platform) ?? "OTHER") === type);
|
|
return {
|
|
type,
|
|
always,
|
|
labelCode: type === "OTHER" ? "DashChannelOther" : ORDER_TYPE_LABEL[type],
|
|
tone: type === "OTHER" ? "neutral" as CategoryTone : ORDER_TYPE_TONE[type],
|
|
revenue: mine.reduce((n, c) => n + c.revenue, 0),
|
|
orders: mine.reduce((n, c) => n + c.orders, 0),
|
|
};
|
|
})
|
|
.filter(r => r.always || r.revenue > 0 || r.orders > 0)
|
|
.map(({ always: _always, ...r }) => r);
|
|
|
|
/** A category tone as a chart colour (each ≥ 3:1 on a card, verified by check-contrast.py). */
|
|
export const CATEGORY_TONE_COLOR: Record<CategoryTone, string> = {
|
|
contrast: "var(--contrast)",
|
|
violet: "var(--chart-4)",
|
|
teal: "var(--chart-2)",
|
|
neutral: "var(--muted-foreground)",
|
|
};
|
|
/** SELF_ACORN etc. -> the translated reward name; an unknown code is shown as-is. */
|
|
export const rewardLabel = (code: string, t: Translate) => (REWARD_LABELS[code] ? t(REWARD_LABELS[code]) : code);
|
|
export const REWARD_CODES = Object.keys(REWARD_LABELS);
|
|
|
|
function query(entries: [string, string | number | undefined][]): string {
|
|
const qs = new URLSearchParams();
|
|
for (const [key, value] of entries) if (value !== undefined && value !== "") qs.set(key, String(value));
|
|
const text = qs.toString();
|
|
return text ? `?${text}` : "";
|
|
}
|
|
|
|
/** Record-list URLs behind each dashboard figure, for the computed period `from`..`to`. */
|
|
export const dashboardLinks = (from: string, to: string) => {
|
|
const rewards = `/reports?tab=rewards&rewards.preset=custom&rewards.from=${from}&rewards.to=${to}`;
|
|
const sales = `/reports?sales.preset=custom&sales.from=${from}&sales.to=${to}`;
|
|
return {
|
|
revenue: sales,
|
|
orders: sales,
|
|
apples: rewards,
|
|
acorns: rewards,
|
|
newMembers: `/members?joinDateFrom=${from}&joinDateTo=${to}`,
|
|
channel: (type: string) => `/orders/web?type=${encodeURIComponent(type)}&status=Y&from=${from}&to=${to}`,
|
|
rank: (rank: string) => `/members?rank=${encodeURIComponent(rank)}`,
|
|
status: (status: string) => `/members?status=${encodeURIComponent(status)}`,
|
|
reward: (code: string) => `${rewards}&rewards.reward=${encodeURIComponent(code)}`,
|
|
};
|
|
};
|
|
|
|
/** GET /api/admin/dashboard — live member, sales and reward figures. */
|
|
export const getDashboard = (period: PeriodParams = {}) =>
|
|
apiGet<DashboardData>(`/api/admin/dashboard${query([["from", period.from], ["to", period.to], ["country", period.country]])}`);
|
|
|
|
/** One tender's total: a payment method (named via tenderLabels) or, for wallet sales, the payment type alone. */
|
|
export interface EventTenderTotal { paymentMethodId: number | null; paymentType: string; amount: number }
|
|
export interface EventSalesTotals { orders: number; revenue: number; byTender: EventTenderTotal[] }
|
|
/** GET /api/admin/dashboard/event — settled EVENT sales of one event, before refunds; "today" is Malaysia time. */
|
|
export interface EventDashboardData {
|
|
operator: string;
|
|
mine: EventSalesTotals;
|
|
today: EventSalesTotals;
|
|
toDate: EventSalesTotals;
|
|
pendingOrders: number;
|
|
tenderLabels: Record<string, string>;
|
|
}
|
|
|
|
export const getEventDashboard = (eventId: string) =>
|
|
apiGet<EventDashboardData>(`/api/admin/dashboard/event?eventId=${encodeURIComponent(eventId)}`);
|
|
|
|
/** GET /api/admin/reports/sales — settled orders of the period (paged) plus the period total. */
|
|
export const getSalesReport = (p: SalesReportParams) =>
|
|
apiGet<SalesReport>(
|
|
`/api/admin/reports/sales${query([["page", p.page], ["size", p.size], ["from", p.from], ["to", p.to], ["country", p.country], ["sortBy", p.sortBy], ["sortDir", p.sortBy && p.sortDir]])}`,
|
|
);
|
|
|
|
/** One Sales by item row: a settled order line expanded to one component SKU (add-sku-supplier). */
|
|
export interface SalesItemRow {
|
|
lineId: number;
|
|
transactionDateTime: string | null;
|
|
documentNo: string | null;
|
|
saleChannel: string | null;
|
|
sourcePlatform: string | null;
|
|
productCode: string | null;
|
|
productName: string | null;
|
|
skuVariationCode: string | null;
|
|
supplierId: number | null;
|
|
supplierCode: string | null;
|
|
supplierName: string | null;
|
|
qty: number;
|
|
amount: number;
|
|
bundle: boolean;
|
|
}
|
|
export interface SalesItemsReport { content: SalesItemRow[]; totalElements: number }
|
|
export interface SalesItemsReportParams extends SalesReportParams { supplierId?: string }
|
|
|
|
/** GET /api/admin/reports/sales-items — settled order lines per component SKU, optional supplier (add-sku-supplier). */
|
|
export const getSalesItemsReport = (p: SalesItemsReportParams) =>
|
|
apiGet<SalesItemsReport>(
|
|
`/api/admin/reports/sales-items${query([
|
|
["page", p.page], ["size", p.size], ["from", p.from], ["to", p.to], ["supplierId", p.supplierId], ["country", p.country],
|
|
["sortBy", p.sortBy], ["sortDir", p.sortBy && p.sortDir],
|
|
])}`,
|
|
);
|
|
|
|
/** GET /api/admin/reports/rewards — reward credits of the period (paged, optional type) plus per-type totals. */
|
|
export const getRewardsReport = (p: RewardsReportParams) =>
|
|
apiGet<RewardsReport>(
|
|
`/api/admin/reports/rewards${query([
|
|
["page", p.page], ["size", p.size], ["from", p.from], ["to", p.to], ["rewardCode", p.rewardCode], ["sortBy", p.sortBy], ["sortDir", p.sortBy && p.sortDir],
|
|
])}`,
|
|
);
|
|
|
|
export interface ActionItem { key: string; href: string; labelCode: string; count: number }
|
|
|
|
/** Source per "Needs attention" item, in display order; `route` is also the access check (query excluded). */
|
|
const ACTION_SOURCES: { key: string; route: string; href: string; labelCode: string; count: () => Promise<number> }[] = [
|
|
{ key: "kyc", route: "/members/knowYourCustomer", href: "/members/knowYourCustomer", labelCode: "DashActKyc", count: () => getKycCounts().then(c => c.P) },
|
|
{ key: "refunds", route: "/orders/refunds", href: "/orders/refunds", labelCode: "DashActRefunds", count: () => listRefunds({ status: "P", size: 1 }).then(p => p.pendingCount) },
|
|
{ key: "warranty", route: "/orders/warranty-claims", href: "/orders/warranty-claims", labelCode: "DashActWarranty", count: () => listWarrantyClaims({ status: "P", size: 1 }).then(p => p.totalElements) },
|
|
{ key: "reviews", route: "/product-reviews", href: "/product-reviews", labelCode: "DashActReviews", count: () => listReviews({ status: "P", size: 1 }).then(p => p.totalElements) },
|
|
{ key: "withdrawals", route: "/wallet/withdrawals", href: "/wallet/withdrawals", labelCode: "DashActWithdrawals", count: () => getPendingWithdrawals(1, 1).then(p => p.totalElements) },
|
|
{ key: "staleOrders", route: "/orders/web", href: "/orders/web?status=STALE", labelCode: "DashActStaleOrders", count: () => listWebOrders({ stalePending: true, page: 0, size: 1 }).then(p => p.totalElements) },
|
|
];
|
|
|
|
/** Pending counts for the routes `can` allows; a failed source is left out so one outage never hides the rest. */
|
|
export async function getActionCounts(can: (route: string) => boolean): Promise<ActionItem[]> {
|
|
const allowed = ACTION_SOURCES.filter(s => can(s.route));
|
|
const results = await Promise.allSettled(allowed.map(s => s.count()));
|
|
return allowed.flatMap(({ key, href, labelCode }, i) => {
|
|
const r = results[i];
|
|
return r.status === "fulfilled" ? [{ key, href, labelCode, count: r.value }] : [];
|
|
});
|
|
}
|