forked from wangziqi/gongxue-base
feat: add point activities and exchange
This commit is contained in:
@@ -2,7 +2,7 @@ import type pg from 'pg';
|
||||
|
||||
type JsonMap = Record<string, unknown>;
|
||||
|
||||
export type BadgeTrigger = 'check_in' | 'score' | 'feedback_resolved';
|
||||
export type BadgeTrigger = 'check_in' | 'score' | 'feedback_resolved' | 'activity_reward';
|
||||
|
||||
export interface BadgeMetricEvidence {
|
||||
checkInStreak?: number;
|
||||
@@ -55,6 +55,7 @@ const TRIGGER_UNLOCK_TYPES: Record<BadgeTrigger, string[]> = {
|
||||
check_in: ['check_in'],
|
||||
score: ['score'],
|
||||
feedback_resolved: ['feedback_resolved'],
|
||||
activity_reward: ['activity_reward'],
|
||||
};
|
||||
|
||||
const FIELD_ALIASES: Record<string, string[]> = {
|
||||
@@ -63,6 +64,7 @@ const FIELD_ALIASES: Record<string, string[]> = {
|
||||
score: ['score', 'user.score', 'profile.score'],
|
||||
feedback_resolved: ['feedbackResolvedCount', 'feedback.resolvedCount', 'reports.resolvedCount'],
|
||||
reward_points: ['rewardPoints', 'feedback.rewardPoints'],
|
||||
activity_reward: ['activityRewardCount', 'activity.rewardCount', 'tasks.claimCount'],
|
||||
};
|
||||
|
||||
function numberValue(value: unknown) {
|
||||
@@ -84,6 +86,7 @@ function metricValueForField(field: string | null, evidence: BadgeMetricEvidence
|
||||
if (trigger === 'check_in') return numberValue(evidence.checkInStreak);
|
||||
if (trigger === 'score') return numberValue(evidence.score);
|
||||
if (trigger === 'feedback_resolved') return numberValue(evidence.feedbackResolvedCount);
|
||||
if (trigger === 'activity_reward') return numberValue(evidence.activityRewardCount);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -94,6 +97,7 @@ function metricValueForField(field: string | null, evidence: BadgeMetricEvidence
|
||||
if (canonical === 'score') return numberValue(evidence.score);
|
||||
if (canonical === 'feedback_resolved') return numberValue(evidence.feedbackResolvedCount);
|
||||
if (canonical === 'reward_points') return numberValue(evidence.rewardPoints);
|
||||
if (canonical === 'activity_reward') return numberValue(evidence.activityRewardCount);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,12 +9,22 @@ import {
|
||||
submitFeedbackRoute,
|
||||
updateProfileMeRoute,
|
||||
} from './routes.js';
|
||||
import {
|
||||
activityTasksRoute,
|
||||
claimActivityTaskRoute,
|
||||
exchangeItemsRoute,
|
||||
redeemExchangeItemRoute,
|
||||
} from './points.js';
|
||||
|
||||
export const profileRoutes: RouteDefinition[] = [
|
||||
['GET', '/api/profile/me', profileMeRoute],
|
||||
['PATCH', '/api/profile/me', updateProfileMeRoute],
|
||||
['POST', '/api/profile/check-in', checkInRoute],
|
||||
['GET', '/api/profile/score-events', scoreEventsRoute],
|
||||
['GET', '/api/profile/activity-tasks', activityTasksRoute],
|
||||
['POST', '/api/profile/activity-tasks/claim', claimActivityTaskRoute],
|
||||
['GET', '/api/profile/exchange-items', exchangeItemsRoute],
|
||||
['POST', '/api/profile/exchange-items/redeem', redeemExchangeItemRoute],
|
||||
['GET', '/api/profile/badges', profileBadgesRoute],
|
||||
['GET', '/api/profile/feedbacks', feedbacksRoute],
|
||||
['POST', '/api/profile/feedbacks', submitFeedbackRoute],
|
||||
|
||||
789
apps/api/src/features/profile/points.ts
Normal file
789
apps/api/src/features/profile/points.ts
Normal file
@@ -0,0 +1,789 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type pg from 'pg';
|
||||
import { HttpError, type RequestContext } from '../../core/http.js';
|
||||
import { intParam, readJsonBody, stringParam, tenantIdFrom, userIdFrom } from '../../core/request.js';
|
||||
import { query, transaction } from '../../core/db.js';
|
||||
import { autoGrantBadges } from './badges.js';
|
||||
|
||||
type JsonMap = Record<string, unknown>;
|
||||
|
||||
const TASK_TYPES = [
|
||||
'daily_check_in',
|
||||
'feedback_submit',
|
||||
'feedback_resolved',
|
||||
'practice_complete',
|
||||
'vocabulary_review',
|
||||
'mock_exam_submit',
|
||||
'manual',
|
||||
];
|
||||
const PERIOD_TYPES = ['once', 'daily', 'weekly', 'monthly', 'unlimited'];
|
||||
const STUDENT_CLAIMABLE_TASK_TYPES = new Set(['manual', 'practice_complete', 'vocabulary_review', 'mock_exam_submit']);
|
||||
|
||||
function nullableString(value: unknown) {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function objectValue(value: unknown): JsonMap {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value as JsonMap : {};
|
||||
}
|
||||
|
||||
function optionalUuidString(value: unknown, key: string) {
|
||||
const candidate = nullableString(value);
|
||||
if (!candidate) return null;
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(candidate)) {
|
||||
throw new HttpError(400, `${key} must be a UUID`, 'INVALID_UUID');
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function shanghaiDateParts(date = new Date()) {
|
||||
const formatter = new Intl.DateTimeFormat('en-US', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
});
|
||||
return Object.fromEntries(formatter.formatToParts(date).map(part => [part.type, part.value])) as {
|
||||
year: string;
|
||||
month: string;
|
||||
day: string;
|
||||
};
|
||||
}
|
||||
|
||||
function shanghaiDateKey(date = new Date()) {
|
||||
const parts = shanghaiDateParts(date);
|
||||
return `${parts.year}-${parts.month}-${parts.day}`;
|
||||
}
|
||||
|
||||
function shanghaiWeekKey(date = new Date()) {
|
||||
const current = new Date(`${shanghaiDateKey(date)}T00:00:00.000Z`);
|
||||
const day = current.getUTCDay() || 7;
|
||||
current.setUTCDate(current.getUTCDate() + 4 - day);
|
||||
const yearStart = new Date(Date.UTC(current.getUTCFullYear(), 0, 1));
|
||||
const week = Math.ceil((((current.getTime() - yearStart.getTime()) / 86_400_000) + 1) / 7);
|
||||
return `${current.getUTCFullYear()}-W${String(week).padStart(2, '0')}`;
|
||||
}
|
||||
|
||||
function safeIdempotencyText(value: unknown) {
|
||||
const candidate = nullableString(value);
|
||||
if (!candidate) return null;
|
||||
if (!/^[a-zA-Z0-9:_-]{8,120}$/.test(candidate)) {
|
||||
throw new HttpError(400, 'idempotencyKey contains unsupported characters', 'INVALID_IDEMPOTENCY_KEY');
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function periodKey(periodType: string, taskId: string, idempotencyKey: string | null = null) {
|
||||
if (periodType === 'daily') return shanghaiDateKey();
|
||||
if (periodType === 'weekly') return shanghaiWeekKey();
|
||||
if (periodType === 'monthly') {
|
||||
const parts = shanghaiDateParts();
|
||||
return `${parts.year}-${parts.month}`;
|
||||
}
|
||||
if (periodType === 'unlimited') return `claim:${idempotencyKey || randomUUID()}`;
|
||||
return `once:${taskId}`;
|
||||
}
|
||||
|
||||
function normalizeTaskType(value: unknown) {
|
||||
const candidate = nullableString(value) || 'manual';
|
||||
if (!TASK_TYPES.includes(candidate)) throw new HttpError(400, `Invalid taskType: ${candidate}`, 'INVALID_TASK_TYPE');
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function normalizePeriodType(value: unknown) {
|
||||
const candidate = nullableString(value) || 'once';
|
||||
if (!PERIOD_TYPES.includes(candidate)) throw new HttpError(400, `Invalid periodType: ${candidate}`, 'INVALID_PERIOD_TYPE');
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function assertActiveWindow(row: { status: string; validFrom: string | null; validTo: string | null }, type: 'task' | 'item') {
|
||||
if (row.status !== 'active') {
|
||||
throw new HttpError(409, `${type} is not active`, type === 'task' ? 'POINT_TASK_INACTIVE' : 'POINT_EXCHANGE_ITEM_INACTIVE');
|
||||
}
|
||||
const now = Date.now();
|
||||
if (row.validFrom && now < new Date(row.validFrom).getTime()) {
|
||||
throw new HttpError(409, `${type} is not available yet`, type === 'task' ? 'POINT_TASK_NOT_STARTED' : 'POINT_EXCHANGE_ITEM_NOT_STARTED');
|
||||
}
|
||||
if (row.validTo && now > new Date(row.validTo).getTime()) {
|
||||
throw new HttpError(409, `${type} is expired`, type === 'task' ? 'POINT_TASK_EXPIRED' : 'POINT_EXCHANGE_ITEM_EXPIRED');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTaskForClaim(client: pg.PoolClient, tenantId: string, body: JsonMap) {
|
||||
const taskId = optionalUuidString(body.taskId, 'taskId');
|
||||
const code = nullableString(body.code);
|
||||
if (!taskId && !code) throw new HttpError(400, 'taskId or code is required', 'POINT_TASK_REQUIRED');
|
||||
|
||||
const result = await client.query<{
|
||||
id: string;
|
||||
code: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
taskType: string;
|
||||
rewardPoints: number;
|
||||
claimLimitPerUser: number;
|
||||
periodType: string;
|
||||
validFrom: string | null;
|
||||
validTo: string | null;
|
||||
status: string;
|
||||
metadata: JsonMap;
|
||||
}>(
|
||||
`
|
||||
select id, code::text, title, description, task_type as "taskType",
|
||||
reward_points as "rewardPoints", claim_limit_per_user as "claimLimitPerUser",
|
||||
period_type as "periodType", valid_from as "validFrom", valid_to as "validTo",
|
||||
status, metadata
|
||||
from public.point_activity_tasks
|
||||
where tenant_id = $1
|
||||
and (($2::uuid is not null and id = $2::uuid) or ($3::text is not null and code = $3))
|
||||
limit 1
|
||||
for update
|
||||
`,
|
||||
[tenantId, taskId, code],
|
||||
);
|
||||
const task = result.rows[0];
|
||||
if (!task) throw new HttpError(404, 'Point activity task not found', 'POINT_TASK_NOT_FOUND');
|
||||
assertActiveWindow(task, 'task');
|
||||
return task;
|
||||
}
|
||||
|
||||
async function loadExchangeItemForRedeem(client: pg.PoolClient, tenantId: string, body: JsonMap) {
|
||||
const itemId = optionalUuidString(body.itemId, 'itemId');
|
||||
const code = nullableString(body.code);
|
||||
if (!itemId && !code) throw new HttpError(400, 'itemId or code is required', 'POINT_EXCHANGE_ITEM_REQUIRED');
|
||||
|
||||
const result = await client.query<{
|
||||
id: string;
|
||||
code: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
costPoints: number;
|
||||
itemType: string;
|
||||
couponId: string | null;
|
||||
assetId: string | null;
|
||||
stockTotal: number | null;
|
||||
stockUsed: number;
|
||||
perUserLimit: number;
|
||||
validFrom: string | null;
|
||||
validTo: string | null;
|
||||
status: string;
|
||||
metadata: JsonMap;
|
||||
}>(
|
||||
`
|
||||
select id, code::text, title, description, cost_points as "costPoints",
|
||||
item_type as "itemType", coupon_id as "couponId", asset_id as "assetId",
|
||||
stock_total as "stockTotal", stock_used as "stockUsed",
|
||||
per_user_limit as "perUserLimit", valid_from as "validFrom", valid_to as "validTo",
|
||||
status, metadata
|
||||
from public.point_exchange_items
|
||||
where tenant_id = $1
|
||||
and (($2::uuid is not null and id = $2::uuid) or ($3::text is not null and code = $3))
|
||||
limit 1
|
||||
for update
|
||||
`,
|
||||
[tenantId, itemId, code],
|
||||
);
|
||||
const item = result.rows[0];
|
||||
if (!item) throw new HttpError(404, 'Point exchange item not found', 'POINT_EXCHANGE_ITEM_NOT_FOUND');
|
||||
assertActiveWindow(item, 'item');
|
||||
return item;
|
||||
}
|
||||
|
||||
async function userScoreForUpdate(client: pg.PoolClient, userId: string) {
|
||||
const result = await client.query<{ score: number }>(
|
||||
`
|
||||
select score
|
||||
from public.platform_users
|
||||
where id = $1
|
||||
limit 1
|
||||
for update
|
||||
`,
|
||||
[userId],
|
||||
);
|
||||
const row = result.rows[0];
|
||||
if (!row) throw new HttpError(404, 'User not found', 'USER_NOT_FOUND');
|
||||
return Number(row.score || 0);
|
||||
}
|
||||
|
||||
async function assertTaskEvidence(
|
||||
client: pg.PoolClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
taskType: string;
|
||||
sourceId: string | null;
|
||||
},
|
||||
) {
|
||||
if (input.taskType === 'manual') return;
|
||||
if (!input.sourceId) {
|
||||
throw new HttpError(400, 'sourceId is required for this activity task', 'POINT_TASK_SOURCE_REQUIRED');
|
||||
}
|
||||
|
||||
if (input.taskType === 'practice_complete' || input.taskType === 'mock_exam_submit') {
|
||||
const result = await client.query(
|
||||
`
|
||||
select id
|
||||
from public.practice_session_reports
|
||||
where tenant_id = $1
|
||||
and user_id = $2
|
||||
and (id = $3::uuid or practice_session_id = $3::uuid)
|
||||
and ($4::text <> 'mock_exam_submit' or mode = 'mock_exam')
|
||||
limit 1
|
||||
`,
|
||||
[input.tenantId, input.userId, input.sourceId, input.taskType],
|
||||
);
|
||||
if (!result.rows[0]) {
|
||||
throw new HttpError(404, 'Practice evidence not found for this student', 'POINT_TASK_SOURCE_NOT_FOUND');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.taskType === 'vocabulary_review') {
|
||||
const result = await client.query(
|
||||
`
|
||||
select id
|
||||
from public.user_word_progress
|
||||
where tenant_id = $1
|
||||
and user_id = $2
|
||||
and id = $3::uuid
|
||||
and last_review_date is not null
|
||||
limit 1
|
||||
`,
|
||||
[input.tenantId, input.userId, input.sourceId],
|
||||
);
|
||||
if (!result.rows[0]) {
|
||||
throw new HttpError(404, 'Vocabulary review evidence not found for this student', 'POINT_TASK_SOURCE_NOT_FOUND');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function createCouponRedemptionForExchange(
|
||||
client: pg.PoolClient,
|
||||
input: {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
couponId: string;
|
||||
orderId: string;
|
||||
metadata: JsonMap;
|
||||
},
|
||||
) {
|
||||
const couponResult = await client.query<{
|
||||
id: string;
|
||||
code: string;
|
||||
status: string;
|
||||
planId: string | null;
|
||||
validFrom: string | null;
|
||||
validTo: string | null;
|
||||
maxUses: number | null;
|
||||
usedCount: number;
|
||||
source: string | null;
|
||||
remark: string | null;
|
||||
}>(
|
||||
`
|
||||
select id, code::text, status, plan_id as "planId",
|
||||
valid_from as "validFrom", valid_to as "validTo",
|
||||
max_uses as "maxUses", used_count as "usedCount", source, remark
|
||||
from public.coupons
|
||||
where tenant_id = $1 and id = $2
|
||||
limit 1
|
||||
for update
|
||||
`,
|
||||
[input.tenantId, input.couponId],
|
||||
);
|
||||
const coupon = couponResult.rows[0];
|
||||
if (!coupon) throw new HttpError(404, 'Coupon not found for exchange item', 'POINT_EXCHANGE_COUPON_NOT_FOUND');
|
||||
assertActiveWindow({
|
||||
status: coupon.status,
|
||||
validFrom: coupon.validFrom,
|
||||
validTo: coupon.validTo,
|
||||
}, 'item');
|
||||
if (coupon.maxUses !== null && coupon.maxUses > 0 && coupon.usedCount >= coupon.maxUses) {
|
||||
throw new HttpError(409, 'Coupon stock is exhausted', 'POINT_EXCHANGE_COUPON_EXHAUSTED');
|
||||
}
|
||||
|
||||
const redemption = await client.query<{
|
||||
id: string;
|
||||
couponId: string;
|
||||
couponCode: string;
|
||||
status: string;
|
||||
claimedAt: string | null;
|
||||
}>(
|
||||
`
|
||||
insert into public.coupon_redemptions (
|
||||
tenant_id, coupon_id, coupon_code, user_id, plan_id, order_id, status,
|
||||
discount_applied_cents, source, remark, claimed_at
|
||||
)
|
||||
values ($1, $2, $3, $4, $5::uuid, null, 'claimed', 0, 'points_exchange', $6, now())
|
||||
returning id, coupon_id as "couponId", coupon_code as "couponCode", status, claimed_at as "claimedAt"
|
||||
`,
|
||||
[
|
||||
input.tenantId,
|
||||
coupon.id,
|
||||
coupon.code,
|
||||
input.userId,
|
||||
coupon.planId,
|
||||
`积分兑换订单 ${input.orderId}`,
|
||||
],
|
||||
);
|
||||
|
||||
return redemption.rows[0];
|
||||
}
|
||||
|
||||
export async function activityTasksRoute(ctx: RequestContext) {
|
||||
const tenantId = await tenantIdFrom(ctx);
|
||||
const userId = await userIdFrom(ctx);
|
||||
const limit = intParam(ctx, 'limit', 100, 300);
|
||||
const taskType = stringParam(ctx, 'taskType');
|
||||
const params: unknown[] = [tenantId, userId];
|
||||
const filters = [
|
||||
't.tenant_id = $1',
|
||||
"t.status = 'active'",
|
||||
'(t.valid_from is null or t.valid_from <= now())',
|
||||
'(t.valid_to is null or t.valid_to >= now())',
|
||||
];
|
||||
if (taskType) {
|
||||
normalizeTaskType(taskType);
|
||||
params.push(taskType);
|
||||
filters.push(`t.task_type = $${params.length}`);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
const items = await query(
|
||||
`
|
||||
select t.id, t.code::text, t.title, t.description, t.task_type as "taskType",
|
||||
t.reward_points as "rewardPoints", t.claim_limit_per_user as "claimLimitPerUser",
|
||||
t.period_type as "periodType", t.valid_from as "validFrom", t.valid_to as "validTo",
|
||||
t.status, t.sort_order as "order", t.metadata,
|
||||
coalesce(c.claim_count, 0)::int as "claimCount",
|
||||
coalesce(c.current_period_claim_count, 0)::int as "currentPeriodClaimCount",
|
||||
c.last_claimed_at as "lastClaimedAt",
|
||||
c.current_period_claim_id as "currentPeriodClaimId",
|
||||
(c.current_period_claim_id is not null) as "claimedInCurrentPeriod",
|
||||
case
|
||||
when t.period_type in ('daily', 'weekly', 'monthly') then
|
||||
case when coalesce(c.current_period_claim_count, 0) > 0 then 0 else 1 end
|
||||
else greatest(t.claim_limit_per_user - coalesce(c.claim_count, 0), 0)
|
||||
end::int as "remainingClaims"
|
||||
from public.point_activity_tasks t
|
||||
left join lateral (
|
||||
select count(*)::int as claim_count,
|
||||
count(*) filter (
|
||||
where period_key = case
|
||||
when t.period_type = 'daily' then to_char((now() at time zone 'Asia/Shanghai')::date, 'YYYY-MM-DD')
|
||||
when t.period_type = 'weekly' then to_char((now() at time zone 'Asia/Shanghai')::date, 'IYYY-"W"IW')
|
||||
when t.period_type = 'monthly' then to_char((now() at time zone 'Asia/Shanghai')::date, 'YYYY-MM')
|
||||
when t.period_type = 'unlimited' then ''
|
||||
else 'once:' || t.id::text
|
||||
end
|
||||
)::int as current_period_claim_count,
|
||||
max(claimed_at) as last_claimed_at,
|
||||
(array_agg(id order by claimed_at desc) filter (
|
||||
where period_key = case
|
||||
when t.period_type = 'daily' then to_char((now() at time zone 'Asia/Shanghai')::date, 'YYYY-MM-DD')
|
||||
when t.period_type = 'weekly' then to_char((now() at time zone 'Asia/Shanghai')::date, 'IYYY-"W"IW')
|
||||
when t.period_type = 'monthly' then to_char((now() at time zone 'Asia/Shanghai')::date, 'YYYY-MM')
|
||||
when t.period_type = 'unlimited' then ''
|
||||
else 'once:' || t.id::text
|
||||
end
|
||||
))[1] as current_period_claim_id
|
||||
from public.user_point_activity_claims c
|
||||
where c.tenant_id = t.tenant_id
|
||||
and c.task_id = t.id
|
||||
and c.user_id = $2
|
||||
and c.status = 'claimed'
|
||||
) c on true
|
||||
where ${filters.join(' and ')}
|
||||
order by t.sort_order asc, t.created_at desc
|
||||
limit $${params.length}
|
||||
`,
|
||||
params,
|
||||
);
|
||||
|
||||
return { items };
|
||||
}
|
||||
|
||||
export async function claimActivityTaskRoute(ctx: RequestContext) {
|
||||
const body = await readJsonBody(ctx);
|
||||
const tenantId = await tenantIdFrom(ctx);
|
||||
const userId = await userIdFrom(ctx, body);
|
||||
const sourceType = nullableString(body.sourceType);
|
||||
const sourceId = optionalUuidString(body.sourceId, 'sourceId');
|
||||
|
||||
const item = await transaction(async client => {
|
||||
const task = await loadTaskForClaim(client, tenantId, body);
|
||||
if (!STUDENT_CLAIMABLE_TASK_TYPES.has(task.taskType)) {
|
||||
throw new HttpError(403, 'This activity task is granted by system workflow only', 'POINT_TASK_SYSTEM_GRANTED_ONLY');
|
||||
}
|
||||
await assertTaskEvidence(client, {
|
||||
tenantId,
|
||||
userId,
|
||||
taskType: task.taskType,
|
||||
sourceId,
|
||||
});
|
||||
const requestIdempotencyKey = safeIdempotencyText(body.idempotencyKey);
|
||||
const currentPeriodKey = periodKey(task.periodType, task.id, requestIdempotencyKey);
|
||||
|
||||
const periodClaims = await client.query<{ count: string }>(
|
||||
`
|
||||
select count(*)::text as count
|
||||
from public.user_point_activity_claims
|
||||
where tenant_id = $1 and user_id = $2 and task_id = $3 and status = 'claimed'
|
||||
and (
|
||||
$5::text <> 'period'
|
||||
or period_key = $4
|
||||
)
|
||||
`,
|
||||
[tenantId, userId, task.id, currentPeriodKey, ['daily', 'weekly', 'monthly'].includes(task.periodType) ? 'period' : 'total'],
|
||||
);
|
||||
const currentLimitCount = Number(periodClaims.rows[0]?.count || 0);
|
||||
const effectiveLimit = ['daily', 'weekly', 'monthly'].includes(task.periodType) ? 1 : task.claimLimitPerUser;
|
||||
if (currentLimitCount >= effectiveLimit) {
|
||||
throw new HttpError(409, 'Activity task claim limit reached', 'POINT_TASK_CLAIM_LIMIT_REACHED');
|
||||
}
|
||||
|
||||
const totalClaims = await client.query<{ count: string }>(
|
||||
`
|
||||
select count(*)::text as count
|
||||
from public.user_point_activity_claims
|
||||
where tenant_id = $1 and user_id = $2 and task_id = $3 and status = 'claimed'
|
||||
`,
|
||||
[tenantId, userId, task.id],
|
||||
);
|
||||
const claimCount = Number(totalClaims.rows[0]?.count || 0);
|
||||
|
||||
const scoreBefore = await userScoreForUpdate(client, userId);
|
||||
const scoreAfter = scoreBefore + task.rewardPoints;
|
||||
const idempotencyKey = `activity:${task.id}:user:${userId}:period:${currentPeriodKey}`;
|
||||
|
||||
const ledger = await client.query<{
|
||||
id: string;
|
||||
eventType: string;
|
||||
points: number;
|
||||
balanceAfter: number;
|
||||
createdAt: string;
|
||||
}>(
|
||||
`
|
||||
insert into public.user_score_events (
|
||||
tenant_id, user_id, event_type, points, balance_after,
|
||||
source_type, source_id, idempotency_key, metadata
|
||||
)
|
||||
values ($1, $2, 'activity_reward', $3, $4, 'point_activity_tasks', $5, $6, $7::jsonb)
|
||||
on conflict (tenant_id, idempotency_key) do nothing
|
||||
returning id, event_type as "eventType", points, balance_after as "balanceAfter", created_at as "createdAt"
|
||||
`,
|
||||
[
|
||||
tenantId,
|
||||
userId,
|
||||
task.rewardPoints,
|
||||
scoreAfter,
|
||||
task.id,
|
||||
idempotencyKey,
|
||||
JSON.stringify({
|
||||
taskId: task.id,
|
||||
code: task.code,
|
||||
taskType: task.taskType,
|
||||
periodKey: currentPeriodKey,
|
||||
sourceType,
|
||||
sourceId,
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
if (!ledger.rows[0]) {
|
||||
throw new HttpError(409, 'Activity task already claimed in this period', 'POINT_TASK_ALREADY_CLAIMED');
|
||||
}
|
||||
|
||||
const claim = await client.query(
|
||||
`
|
||||
insert into public.user_point_activity_claims (
|
||||
tenant_id, user_id, task_id, period_key, score_event_id,
|
||||
source_type, source_id, metadata
|
||||
)
|
||||
values ($1, $2, $3, $4, $5, $6, $7::uuid, $8::jsonb)
|
||||
returning id, task_id as "taskId", period_key as "periodKey",
|
||||
score_event_id as "scoreEventId", source_type as "sourceType",
|
||||
source_id as "sourceId", status, metadata, claimed_at as "claimedAt"
|
||||
`,
|
||||
[
|
||||
tenantId,
|
||||
userId,
|
||||
task.id,
|
||||
currentPeriodKey,
|
||||
ledger.rows[0].id,
|
||||
sourceType,
|
||||
sourceId,
|
||||
JSON.stringify(objectValue(body.metadata)),
|
||||
],
|
||||
);
|
||||
|
||||
const updatedUser = await client.query<{ score: number }>(
|
||||
`
|
||||
update public.platform_users
|
||||
set score = score + $2,
|
||||
updated_at = now()
|
||||
where id = $1
|
||||
returning score
|
||||
`,
|
||||
[userId, task.rewardPoints],
|
||||
);
|
||||
|
||||
const nextScore = Number(updatedUser.rows[0]?.score || scoreAfter);
|
||||
const nextClaimCount = claimCount + 1;
|
||||
const autoBadges = [
|
||||
...(await autoGrantBadges(client, {
|
||||
tenantId,
|
||||
userId,
|
||||
trigger: 'activity_reward',
|
||||
evidence: {
|
||||
activityRewardCount: nextClaimCount,
|
||||
rewardPoints: task.rewardPoints,
|
||||
score: nextScore,
|
||||
taskType: task.taskType,
|
||||
taskCode: task.code,
|
||||
},
|
||||
})),
|
||||
...(await autoGrantBadges(client, {
|
||||
tenantId,
|
||||
userId,
|
||||
trigger: 'score',
|
||||
evidence: {
|
||||
source: 'activity_reward',
|
||||
activityRewardCount: nextClaimCount,
|
||||
rewardPoints: task.rewardPoints,
|
||||
score: nextScore,
|
||||
},
|
||||
})),
|
||||
];
|
||||
|
||||
return {
|
||||
task,
|
||||
claim: claim.rows[0],
|
||||
ledger: {
|
||||
...ledger.rows[0],
|
||||
balanceAfter: nextScore,
|
||||
},
|
||||
pointsAdded: task.rewardPoints,
|
||||
score: nextScore,
|
||||
claimCount: nextClaimCount,
|
||||
autoBadges,
|
||||
};
|
||||
});
|
||||
|
||||
return { item };
|
||||
}
|
||||
|
||||
export async function exchangeItemsRoute(ctx: RequestContext) {
|
||||
const tenantId = await tenantIdFrom(ctx);
|
||||
const userId = await userIdFrom(ctx);
|
||||
const limit = intParam(ctx, 'limit', 100, 300);
|
||||
const params: unknown[] = [tenantId, userId, limit];
|
||||
|
||||
const items = await query(
|
||||
`
|
||||
select i.id, i.code::text, i.title, i.description, i.cost_points as "costPoints",
|
||||
i.item_type as "itemType", i.coupon_id as "couponId", i.asset_id as "assetId",
|
||||
i.stock_total as "stockTotal", i.stock_used as "stockUsed",
|
||||
case when i.stock_total is null then null else greatest(i.stock_total - i.stock_used, 0) end as "stockRemaining",
|
||||
i.per_user_limit as "perUserLimit", i.valid_from as "validFrom", i.valid_to as "validTo",
|
||||
i.status, i.sort_order as "order", i.metadata,
|
||||
coalesce(o.order_count, 0)::int as "redeemedCount",
|
||||
o.last_exchanged_at as "lastExchangedAt",
|
||||
greatest(i.per_user_limit - coalesce(o.order_count, 0), 0)::int as "remainingUserRedemptions"
|
||||
from public.point_exchange_items i
|
||||
left join lateral (
|
||||
select count(*)::int as order_count, max(exchanged_at) as last_exchanged_at
|
||||
from public.user_point_exchange_orders o
|
||||
where o.tenant_id = i.tenant_id
|
||||
and o.item_id = i.id
|
||||
and o.user_id = $2
|
||||
and o.status <> 'cancelled'
|
||||
) o on true
|
||||
where i.tenant_id = $1
|
||||
and i.status = 'active'
|
||||
and (i.valid_from is null or i.valid_from <= now())
|
||||
and (i.valid_to is null or i.valid_to >= now())
|
||||
order by i.sort_order asc, i.created_at desc
|
||||
limit $3
|
||||
`,
|
||||
params,
|
||||
);
|
||||
|
||||
return { items };
|
||||
}
|
||||
|
||||
export async function redeemExchangeItemRoute(ctx: RequestContext) {
|
||||
const body = await readJsonBody(ctx);
|
||||
const tenantId = await tenantIdFrom(ctx);
|
||||
const userId = await userIdFrom(ctx, body);
|
||||
const idempotencyKey = safeIdempotencyText(body.idempotencyKey) || `exchange:${randomUUID()}`;
|
||||
|
||||
const item = await transaction(async client => {
|
||||
const existing = await client.query(
|
||||
`
|
||||
select o.id, o.item_id as "itemId", o.status, o.cost_points as "costPoints",
|
||||
o.score_event_id as "scoreEventId", o.coupon_redemption_id as "couponRedemptionId",
|
||||
o.asset_id as "assetId", o.metadata, o.exchanged_at as "exchangedAt"
|
||||
from public.user_point_exchange_orders o
|
||||
where o.tenant_id = $1 and o.user_id = $2 and o.idempotency_key = $3
|
||||
limit 1
|
||||
`,
|
||||
[tenantId, userId, idempotencyKey],
|
||||
);
|
||||
if (existing.rows[0]) return { order: existing.rows[0], idempotent: true };
|
||||
|
||||
const exchangeItem = await loadExchangeItemForRedeem(client, tenantId, body);
|
||||
const userOrders = await client.query<{ count: string }>(
|
||||
`
|
||||
select count(*)::text as count
|
||||
from public.user_point_exchange_orders
|
||||
where tenant_id = $1 and user_id = $2 and item_id = $3 and status <> 'cancelled'
|
||||
`,
|
||||
[tenantId, userId, exchangeItem.id],
|
||||
);
|
||||
const redeemedCount = Number(userOrders.rows[0]?.count || 0);
|
||||
if (redeemedCount >= exchangeItem.perUserLimit) {
|
||||
throw new HttpError(409, 'Point exchange user limit reached', 'POINT_EXCHANGE_USER_LIMIT_REACHED');
|
||||
}
|
||||
if (exchangeItem.stockTotal !== null && exchangeItem.stockUsed >= exchangeItem.stockTotal) {
|
||||
throw new HttpError(409, 'Point exchange item is out of stock', 'POINT_EXCHANGE_OUT_OF_STOCK');
|
||||
}
|
||||
|
||||
const scoreBefore = await userScoreForUpdate(client, userId);
|
||||
if (scoreBefore < exchangeItem.costPoints) {
|
||||
throw new HttpError(409, 'Insufficient score balance', 'POINT_EXCHANGE_INSUFFICIENT_SCORE');
|
||||
}
|
||||
const scoreAfter = scoreBefore - exchangeItem.costPoints;
|
||||
|
||||
const ledger = await client.query<{
|
||||
id: string;
|
||||
eventType: string;
|
||||
points: number;
|
||||
balanceAfter: number;
|
||||
createdAt: string;
|
||||
}>(
|
||||
`
|
||||
insert into public.user_score_events (
|
||||
tenant_id, user_id, event_type, points, balance_after,
|
||||
source_type, source_id, idempotency_key, metadata
|
||||
)
|
||||
values ($1, $2, 'redeem_cost', $3, $4, 'point_exchange_items', $5, $6, $7::jsonb)
|
||||
returning id, event_type as "eventType", points, balance_after as "balanceAfter", created_at as "createdAt"
|
||||
`,
|
||||
[
|
||||
tenantId,
|
||||
userId,
|
||||
-exchangeItem.costPoints,
|
||||
scoreAfter,
|
||||
exchangeItem.id,
|
||||
`redeem:${idempotencyKey}`,
|
||||
JSON.stringify({
|
||||
itemId: exchangeItem.id,
|
||||
code: exchangeItem.code,
|
||||
itemType: exchangeItem.itemType,
|
||||
}),
|
||||
],
|
||||
);
|
||||
|
||||
const order = await client.query<{
|
||||
id: string;
|
||||
itemId: string;
|
||||
status: string;
|
||||
costPoints: number;
|
||||
scoreEventId: string;
|
||||
couponRedemptionId: string | null;
|
||||
assetId: string | null;
|
||||
metadata: JsonMap;
|
||||
exchangedAt: string;
|
||||
}>(
|
||||
`
|
||||
insert into public.user_point_exchange_orders (
|
||||
tenant_id, user_id, item_id, status, cost_points, score_event_id,
|
||||
asset_id, idempotency_key, metadata
|
||||
)
|
||||
values ($1, $2, $3, $4, $5, $6, $7::uuid, $8, $9::jsonb)
|
||||
returning id, item_id as "itemId", status, cost_points as "costPoints",
|
||||
score_event_id as "scoreEventId", coupon_redemption_id as "couponRedemptionId",
|
||||
asset_id as "assetId", metadata, exchanged_at as "exchangedAt"
|
||||
`,
|
||||
[
|
||||
tenantId,
|
||||
userId,
|
||||
exchangeItem.id,
|
||||
exchangeItem.itemType === 'manual' || exchangeItem.itemType === 'custom' ? 'pending_fulfillment' : 'completed',
|
||||
exchangeItem.costPoints,
|
||||
ledger.rows[0].id,
|
||||
exchangeItem.assetId,
|
||||
idempotencyKey,
|
||||
JSON.stringify(objectValue(body.metadata)),
|
||||
],
|
||||
);
|
||||
|
||||
let couponRedemption = null;
|
||||
if (exchangeItem.itemType === 'coupon') {
|
||||
if (!exchangeItem.couponId) throw new HttpError(409, 'Coupon exchange item is missing couponId', 'POINT_EXCHANGE_COUPON_MISSING');
|
||||
couponRedemption = await createCouponRedemptionForExchange(client, {
|
||||
tenantId,
|
||||
userId,
|
||||
couponId: exchangeItem.couponId,
|
||||
orderId: order.rows[0].id,
|
||||
metadata: objectValue(body.metadata),
|
||||
});
|
||||
await client.query(
|
||||
`
|
||||
update public.user_point_exchange_orders
|
||||
set coupon_redemption_id = $3,
|
||||
status = 'completed',
|
||||
updated_at = now()
|
||||
where tenant_id = $1 and id = $2
|
||||
`,
|
||||
[tenantId, order.rows[0].id, couponRedemption.id],
|
||||
);
|
||||
order.rows[0].couponRedemptionId = couponRedemption.id;
|
||||
order.rows[0].status = 'completed';
|
||||
}
|
||||
|
||||
if (exchangeItem.stockTotal !== null) {
|
||||
const stockUpdate = await client.query(
|
||||
`
|
||||
update public.point_exchange_items
|
||||
set stock_used = stock_used + 1,
|
||||
updated_at = now()
|
||||
where tenant_id = $1
|
||||
and id = $2
|
||||
and stock_total is not null
|
||||
and stock_used < stock_total
|
||||
`,
|
||||
[tenantId, exchangeItem.id],
|
||||
);
|
||||
if (stockUpdate.rowCount !== 1) {
|
||||
throw new HttpError(409, 'Point exchange item is out of stock', 'POINT_EXCHANGE_OUT_OF_STOCK');
|
||||
}
|
||||
}
|
||||
|
||||
const updatedUser = await client.query<{ score: number }>(
|
||||
`
|
||||
update public.platform_users
|
||||
set score = score - $2,
|
||||
updated_at = now()
|
||||
where id = $1
|
||||
returning score
|
||||
`,
|
||||
[userId, exchangeItem.costPoints],
|
||||
);
|
||||
|
||||
return {
|
||||
item: exchangeItem,
|
||||
order: order.rows[0],
|
||||
couponRedemption,
|
||||
ledger: {
|
||||
...ledger.rows[0],
|
||||
balanceAfter: Number(updatedUser.rows[0]?.score || scoreAfter),
|
||||
},
|
||||
pointsSpent: exchangeItem.costPoints,
|
||||
score: Number(updatedUser.rows[0]?.score || scoreAfter),
|
||||
idempotent: false,
|
||||
};
|
||||
});
|
||||
|
||||
return { item };
|
||||
}
|
||||
@@ -103,6 +103,8 @@ export function tenantPermissionCatalog() {
|
||||
{ key: 'tenant:secrets:write', label: '密钥轮换' },
|
||||
{ key: 'marketing:read', label: '活动内容查看' },
|
||||
{ key: 'marketing:write', label: '活动内容管理' },
|
||||
{ key: 'marketing:points:read', label: '积分任务/兑换查看' },
|
||||
{ key: 'marketing:points:write', label: '积分任务/兑换管理' },
|
||||
{ key: 'badges:read', label: '勋章查看' },
|
||||
{ key: 'badges:write', label: '勋章管理' },
|
||||
{ key: 'badges:grant', label: '勋章发放' },
|
||||
|
||||
@@ -25,6 +25,14 @@ import {
|
||||
updateTenantFeedbackStatusRoute,
|
||||
upsertTenantExamDateRoute,
|
||||
} from './operations.js';
|
||||
import {
|
||||
pointActivityClaimsRoute,
|
||||
pointActivityTasksRoute,
|
||||
pointExchangeItemsRoute,
|
||||
pointExchangeOrdersRoute,
|
||||
upsertPointActivityTaskRoute,
|
||||
upsertPointExchangeItemRoute,
|
||||
} from './points.js';
|
||||
import {
|
||||
activationCodesRoute,
|
||||
announcementsAdminRoute,
|
||||
@@ -131,6 +139,12 @@ export const tenantAdminRoutes: RouteDefinition[] = [
|
||||
['PUT', '/api/tenant-admin/coupons', upsertCouponRoute],
|
||||
['GET', '/api/tenant-admin/coupons/redemptions', couponRedemptionsRoute],
|
||||
['GET', '/api/tenant-admin/coupons/report', couponReportRoute],
|
||||
['GET', '/api/tenant-admin/point-activity-tasks', pointActivityTasksRoute],
|
||||
['PUT', '/api/tenant-admin/point-activity-tasks', upsertPointActivityTaskRoute],
|
||||
['GET', '/api/tenant-admin/point-activity-claims', pointActivityClaimsRoute],
|
||||
['GET', '/api/tenant-admin/point-exchange-items', pointExchangeItemsRoute],
|
||||
['PUT', '/api/tenant-admin/point-exchange-items', upsertPointExchangeItemRoute],
|
||||
['GET', '/api/tenant-admin/point-exchange-orders', pointExchangeOrdersRoute],
|
||||
['GET', '/api/tenant-admin/members', tenantMembersRoute],
|
||||
['PUT', '/api/tenant-admin/members', upsertTenantMemberRoute],
|
||||
['POST', '/api/tenant-admin/members/disable', disableTenantMemberRoute],
|
||||
|
||||
453
apps/api/src/features/tenant-admin/points.ts
Normal file
453
apps/api/src/features/tenant-admin/points.ts
Normal file
@@ -0,0 +1,453 @@
|
||||
import { HttpError, type RequestContext } from '../../core/http.js';
|
||||
import { intParam, readJsonBody, requiredString, stringParam } from '../../core/request.js';
|
||||
import { query, transaction } from '../../core/db.js';
|
||||
import {
|
||||
hasTenantPermission,
|
||||
requireTenantAdmin,
|
||||
requireTenantPermission,
|
||||
type TenantAdminAuth,
|
||||
} from './auth.js';
|
||||
|
||||
type JsonBody = Record<string, unknown>;
|
||||
|
||||
const TASK_TYPES = [
|
||||
'daily_check_in',
|
||||
'feedback_submit',
|
||||
'feedback_resolved',
|
||||
'practice_complete',
|
||||
'vocabulary_review',
|
||||
'mock_exam_submit',
|
||||
'manual',
|
||||
];
|
||||
const PERIOD_TYPES = ['once', 'daily', 'weekly', 'monthly', 'unlimited'];
|
||||
const TASK_STATUSES = ['active', 'disabled', 'archived'];
|
||||
const EXCHANGE_ITEM_TYPES = ['coupon', 'manual', 'asset', 'custom'];
|
||||
const EXCHANGE_ITEM_STATUSES = ['active', 'disabled', 'archived'];
|
||||
const EXCHANGE_ORDER_STATUSES = ['completed', 'pending_fulfillment', 'cancelled'];
|
||||
|
||||
function nullableString(value: unknown) {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function objectValue(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
function intValue(value: unknown, fallback: number) {
|
||||
const parsed = Number(value ?? fallback);
|
||||
return Number.isFinite(parsed) ? Math.trunc(parsed) : fallback;
|
||||
}
|
||||
|
||||
function optionalChoice(value: unknown, allowed: string[], fallback: string) {
|
||||
const candidate = nullableString(value) || fallback;
|
||||
if (!allowed.includes(candidate)) {
|
||||
throw new HttpError(400, `Invalid value: ${candidate}`, 'INVALID_FIELD_VALUE');
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function optionalUuidString(value: unknown, key: string) {
|
||||
const candidate = nullableString(value);
|
||||
if (!candidate) return null;
|
||||
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(candidate)) {
|
||||
throw new HttpError(400, `${key} must be a UUID`, 'INVALID_UUID');
|
||||
}
|
||||
return candidate;
|
||||
}
|
||||
|
||||
function codeValue(body: JsonBody) {
|
||||
return requiredString(body, 'code').trim().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
function optionalDateTimeText(value: unknown, key: string) {
|
||||
const candidate = nullableString(value);
|
||||
if (!candidate) return null;
|
||||
const time = new Date(candidate).getTime();
|
||||
if (!Number.isFinite(time)) throw new HttpError(400, `${key} must be a valid datetime`, 'INVALID_DATETIME');
|
||||
return candidate;
|
||||
}
|
||||
|
||||
async function recordAudit(
|
||||
client: { query: (sql: string, params?: unknown[]) => Promise<unknown> },
|
||||
auth: TenantAdminAuth,
|
||||
action: string,
|
||||
targetType: string,
|
||||
targetId: string | null,
|
||||
details: Record<string, unknown> = {},
|
||||
) {
|
||||
await client.query(
|
||||
`
|
||||
insert into public.audit_logs (tenant_id, actor_user_id, action, target_type, target_id, details)
|
||||
values ($1, $2, $3, $4, $5, $6::jsonb)
|
||||
`,
|
||||
[auth.tenantId, auth.userId, action, targetType, targetId, JSON.stringify(details)],
|
||||
);
|
||||
}
|
||||
|
||||
function requirePointMarketingPermission(auth: TenantAdminAuth, permission: 'read' | 'write') {
|
||||
const specific = `marketing:points:${permission}`;
|
||||
if (hasTenantPermission(auth, specific) || hasTenantPermission(auth, `marketing:${permission}`)) return;
|
||||
requireTenantPermission(auth, specific);
|
||||
}
|
||||
|
||||
export async function pointActivityTasksRoute(ctx: RequestContext) {
|
||||
const auth = await requireTenantAdmin(ctx);
|
||||
requirePointMarketingPermission(auth, 'read');
|
||||
const limit = intParam(ctx, 'limit', 100, 500);
|
||||
const status = stringParam(ctx, 'status');
|
||||
const taskType = stringParam(ctx, 'taskType');
|
||||
const params: unknown[] = [auth.tenantId];
|
||||
const filters = ['t.tenant_id = $1'];
|
||||
if (status) {
|
||||
if (!TASK_STATUSES.includes(status)) throw new HttpError(400, 'status is invalid', 'INVALID_STATUS');
|
||||
params.push(status);
|
||||
filters.push(`t.status = $${params.length}`);
|
||||
}
|
||||
if (taskType) {
|
||||
if (!TASK_TYPES.includes(taskType)) throw new HttpError(400, 'taskType is invalid', 'INVALID_TASK_TYPE');
|
||||
params.push(taskType);
|
||||
filters.push(`t.task_type = $${params.length}`);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
const items = await query(
|
||||
`
|
||||
select t.id, t.legacy_id as "legacyId", t.code::text, t.title, t.description,
|
||||
t.task_type as "taskType", t.reward_points as "rewardPoints",
|
||||
t.claim_limit_per_user as "claimLimitPerUser", t.period_type as "periodType",
|
||||
t.valid_from as "validFrom", t.valid_to as "validTo", t.status,
|
||||
t.sort_order as "order", t.metadata, t.created_by as "createdBy",
|
||||
count(c.id)::int as "claimCount",
|
||||
count(distinct c.user_id)::int as "claimUserCount",
|
||||
t.created_at as "createdAt", t.updated_at as "updatedAt"
|
||||
from public.point_activity_tasks t
|
||||
left join public.user_point_activity_claims c
|
||||
on c.tenant_id = t.tenant_id
|
||||
and c.task_id = t.id
|
||||
and c.status = 'claimed'
|
||||
where ${filters.join(' and ')}
|
||||
group by t.id
|
||||
order by t.sort_order asc, t.created_at desc
|
||||
limit $${params.length}
|
||||
`,
|
||||
params,
|
||||
);
|
||||
return { items };
|
||||
}
|
||||
|
||||
export async function upsertPointActivityTaskRoute(ctx: RequestContext) {
|
||||
const auth = await requireTenantAdmin(ctx);
|
||||
requirePointMarketingPermission(auth, 'write');
|
||||
const body = await readJsonBody(ctx);
|
||||
const taskType = optionalChoice(body.taskType, TASK_TYPES, 'manual');
|
||||
const periodType = optionalChoice(body.periodType, PERIOD_TYPES, taskType === 'daily_check_in' ? 'daily' : 'once');
|
||||
const status = optionalChoice(body.status, TASK_STATUSES, 'active');
|
||||
const rewardPoints = Math.max(1, Math.min(100000, intValue(body.rewardPoints, 1)));
|
||||
const claimLimitPerUser = Math.max(1, Math.min(100000, intValue(body.claimLimitPerUser, 1)));
|
||||
const code = codeValue(body);
|
||||
|
||||
const item = await transaction(async client => {
|
||||
const result = await client.query(
|
||||
`
|
||||
insert into public.point_activity_tasks (
|
||||
id, tenant_id, legacy_id, code, title, description, task_type,
|
||||
reward_points, claim_limit_per_user, period_type, valid_from, valid_to,
|
||||
status, sort_order, metadata, created_by
|
||||
)
|
||||
values (
|
||||
coalesce($2::uuid, gen_random_uuid()), $1, $3, $4, $5, $6, $7,
|
||||
$8, $9, $10, $11::timestamptz, $12::timestamptz,
|
||||
$13, $14, $15::jsonb, $16
|
||||
)
|
||||
on conflict (tenant_id, code)
|
||||
do update set legacy_id = coalesce(excluded.legacy_id, public.point_activity_tasks.legacy_id),
|
||||
title = excluded.title,
|
||||
description = excluded.description,
|
||||
task_type = excluded.task_type,
|
||||
reward_points = excluded.reward_points,
|
||||
claim_limit_per_user = excluded.claim_limit_per_user,
|
||||
period_type = excluded.period_type,
|
||||
valid_from = excluded.valid_from,
|
||||
valid_to = excluded.valid_to,
|
||||
status = excluded.status,
|
||||
sort_order = excluded.sort_order,
|
||||
metadata = excluded.metadata,
|
||||
updated_at = now()
|
||||
returning id, legacy_id as "legacyId", code::text, title, description,
|
||||
task_type as "taskType", reward_points as "rewardPoints",
|
||||
claim_limit_per_user as "claimLimitPerUser", period_type as "periodType",
|
||||
valid_from as "validFrom", valid_to as "validTo", status,
|
||||
sort_order as "order", metadata, created_by as "createdBy",
|
||||
created_at as "createdAt", updated_at as "updatedAt"
|
||||
`,
|
||||
[
|
||||
auth.tenantId,
|
||||
optionalUuidString(body.id, 'id'),
|
||||
nullableString(body.legacyId),
|
||||
code,
|
||||
requiredString(body, 'title'),
|
||||
nullableString(body.description),
|
||||
taskType,
|
||||
rewardPoints,
|
||||
claimLimitPerUser,
|
||||
periodType,
|
||||
optionalDateTimeText(body.validFrom, 'validFrom'),
|
||||
optionalDateTimeText(body.validTo, 'validTo'),
|
||||
status,
|
||||
intValue(body.order ?? body.sortOrder, 0),
|
||||
JSON.stringify(objectValue(body.metadata)),
|
||||
auth.userId,
|
||||
],
|
||||
);
|
||||
await recordAudit(client, auth, 'tenant.point_activity_task.upserted', 'point_activity_tasks', result.rows[0].id, {
|
||||
code,
|
||||
taskType,
|
||||
rewardPoints,
|
||||
status,
|
||||
});
|
||||
return result.rows[0];
|
||||
});
|
||||
|
||||
return { item };
|
||||
}
|
||||
|
||||
export async function pointActivityClaimsRoute(ctx: RequestContext) {
|
||||
const auth = await requireTenantAdmin(ctx);
|
||||
requirePointMarketingPermission(auth, 'read');
|
||||
const limit = intParam(ctx, 'limit', 100, 500);
|
||||
const taskId = optionalUuidString(stringParam(ctx, 'taskId'), 'taskId');
|
||||
const userId = optionalUuidString(stringParam(ctx, 'userId'), 'userId');
|
||||
const params: unknown[] = [auth.tenantId];
|
||||
const filters = ['c.tenant_id = $1'];
|
||||
if (taskId) {
|
||||
params.push(taskId);
|
||||
filters.push(`c.task_id = $${params.length}::uuid`);
|
||||
}
|
||||
if (userId) {
|
||||
params.push(userId);
|
||||
filters.push(`c.user_id = $${params.length}::uuid`);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
const items = await query(
|
||||
`
|
||||
select c.id, c.user_id as "userId", u.name as "userName", u.phone as "userPhone",
|
||||
c.task_id as "taskId", t.code::text as "taskCode", t.title as "taskTitle",
|
||||
t.reward_points as "rewardPoints", c.period_key as "periodKey",
|
||||
c.score_event_id as "scoreEventId", c.source_type as "sourceType",
|
||||
c.source_id as "sourceId", c.status, c.metadata, c.claimed_at as "claimedAt",
|
||||
c.created_at as "createdAt", c.updated_at as "updatedAt"
|
||||
from public.user_point_activity_claims c
|
||||
join public.point_activity_tasks t on t.tenant_id = c.tenant_id and t.id = c.task_id
|
||||
left join public.platform_users u on u.id = c.user_id
|
||||
where ${filters.join(' and ')}
|
||||
order by c.claimed_at desc
|
||||
limit $${params.length}
|
||||
`,
|
||||
params,
|
||||
);
|
||||
return { items };
|
||||
}
|
||||
|
||||
export async function pointExchangeItemsRoute(ctx: RequestContext) {
|
||||
const auth = await requireTenantAdmin(ctx);
|
||||
requirePointMarketingPermission(auth, 'read');
|
||||
const limit = intParam(ctx, 'limit', 100, 500);
|
||||
const status = stringParam(ctx, 'status');
|
||||
const itemType = stringParam(ctx, 'itemType');
|
||||
const params: unknown[] = [auth.tenantId];
|
||||
const filters = ['i.tenant_id = $1'];
|
||||
if (status) {
|
||||
if (!EXCHANGE_ITEM_STATUSES.includes(status)) throw new HttpError(400, 'status is invalid', 'INVALID_STATUS');
|
||||
params.push(status);
|
||||
filters.push(`i.status = $${params.length}`);
|
||||
}
|
||||
if (itemType) {
|
||||
if (!EXCHANGE_ITEM_TYPES.includes(itemType)) throw new HttpError(400, 'itemType is invalid', 'INVALID_EXCHANGE_ITEM_TYPE');
|
||||
params.push(itemType);
|
||||
filters.push(`i.item_type = $${params.length}`);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
const items = await query(
|
||||
`
|
||||
select i.id, i.legacy_id as "legacyId", i.code::text, i.title, i.description,
|
||||
i.cost_points as "costPoints", i.item_type as "itemType",
|
||||
i.coupon_id as "couponId", c.code::text as "couponCode",
|
||||
i.asset_id as "assetId", i.stock_total as "stockTotal",
|
||||
i.stock_used as "stockUsed",
|
||||
case when i.stock_total is null then null else greatest(i.stock_total - i.stock_used, 0) end as "stockRemaining",
|
||||
i.per_user_limit as "perUserLimit", i.valid_from as "validFrom",
|
||||
i.valid_to as "validTo", i.status, i.sort_order as "order",
|
||||
i.metadata, i.created_by as "createdBy",
|
||||
count(o.id)::int as "orderCount",
|
||||
i.created_at as "createdAt", i.updated_at as "updatedAt"
|
||||
from public.point_exchange_items i
|
||||
left join public.coupons c on c.tenant_id = i.tenant_id and c.id = i.coupon_id
|
||||
left join public.user_point_exchange_orders o
|
||||
on o.tenant_id = i.tenant_id
|
||||
and o.item_id = i.id
|
||||
and o.status <> 'cancelled'
|
||||
where ${filters.join(' and ')}
|
||||
group by i.id, c.code
|
||||
order by i.sort_order asc, i.created_at desc
|
||||
limit $${params.length}
|
||||
`,
|
||||
params,
|
||||
);
|
||||
return { items };
|
||||
}
|
||||
|
||||
export async function upsertPointExchangeItemRoute(ctx: RequestContext) {
|
||||
const auth = await requireTenantAdmin(ctx);
|
||||
requirePointMarketingPermission(auth, 'write');
|
||||
const body = await readJsonBody(ctx);
|
||||
const code = codeValue(body);
|
||||
const itemType = optionalChoice(body.itemType, EXCHANGE_ITEM_TYPES, 'manual');
|
||||
const status = optionalChoice(body.status, EXCHANGE_ITEM_STATUSES, 'active');
|
||||
const couponId = optionalUuidString(body.couponId, 'couponId');
|
||||
const assetId = optionalUuidString(body.assetId, 'assetId');
|
||||
const stockTotal = body.stockTotal === undefined || body.stockTotal === null || body.stockTotal === ''
|
||||
? null
|
||||
: Math.max(0, intValue(body.stockTotal, 0));
|
||||
const costPoints = Math.max(1, Math.min(10000000, intValue(body.costPoints, 1)));
|
||||
const perUserLimit = Math.max(1, Math.min(100000, intValue(body.perUserLimit, 1)));
|
||||
|
||||
if (itemType === 'coupon' && !couponId) {
|
||||
throw new HttpError(400, 'couponId is required for coupon exchange item', 'POINT_EXCHANGE_COUPON_REQUIRED');
|
||||
}
|
||||
if (itemType === 'asset' && !assetId) {
|
||||
throw new HttpError(400, 'assetId is required for asset exchange item', 'POINT_EXCHANGE_ASSET_REQUIRED');
|
||||
}
|
||||
|
||||
const item = await transaction(async client => {
|
||||
if (couponId) {
|
||||
const coupon = await client.query(
|
||||
'select id from public.coupons where tenant_id = $1 and id = $2 limit 1',
|
||||
[auth.tenantId, couponId],
|
||||
);
|
||||
if (!coupon.rows[0]) throw new HttpError(404, 'Coupon not found for this tenant', 'COUPON_NOT_FOUND');
|
||||
}
|
||||
if (assetId) {
|
||||
const asset = await client.query(
|
||||
'select id from public.content_assets where tenant_id = $1 and id = $2 limit 1',
|
||||
[auth.tenantId, assetId],
|
||||
);
|
||||
if (!asset.rows[0]) throw new HttpError(404, 'Asset not found for this tenant', 'ASSET_NOT_FOUND');
|
||||
}
|
||||
|
||||
const result = await client.query(
|
||||
`
|
||||
insert into public.point_exchange_items (
|
||||
id, tenant_id, legacy_id, code, title, description, cost_points,
|
||||
item_type, coupon_id, asset_id, stock_total, per_user_limit,
|
||||
valid_from, valid_to, status, sort_order, metadata, created_by
|
||||
)
|
||||
values (
|
||||
coalesce($2::uuid, gen_random_uuid()), $1, $3, $4, $5, $6, $7,
|
||||
$8, $9::uuid, $10::uuid, $11, $12,
|
||||
$13::timestamptz, $14::timestamptz, $15, $16, $17::jsonb, $18
|
||||
)
|
||||
on conflict (tenant_id, code)
|
||||
do update set legacy_id = coalesce(excluded.legacy_id, public.point_exchange_items.legacy_id),
|
||||
title = excluded.title,
|
||||
description = excluded.description,
|
||||
cost_points = excluded.cost_points,
|
||||
item_type = excluded.item_type,
|
||||
coupon_id = excluded.coupon_id,
|
||||
asset_id = excluded.asset_id,
|
||||
stock_total = excluded.stock_total,
|
||||
per_user_limit = excluded.per_user_limit,
|
||||
valid_from = excluded.valid_from,
|
||||
valid_to = excluded.valid_to,
|
||||
status = excluded.status,
|
||||
sort_order = excluded.sort_order,
|
||||
metadata = excluded.metadata,
|
||||
updated_at = now()
|
||||
returning id, legacy_id as "legacyId", code::text, title, description,
|
||||
cost_points as "costPoints", item_type as "itemType",
|
||||
coupon_id as "couponId", asset_id as "assetId",
|
||||
stock_total as "stockTotal", stock_used as "stockUsed",
|
||||
per_user_limit as "perUserLimit", valid_from as "validFrom",
|
||||
valid_to as "validTo", status, sort_order as "order",
|
||||
metadata, created_by as "createdBy", created_at as "createdAt",
|
||||
updated_at as "updatedAt"
|
||||
`,
|
||||
[
|
||||
auth.tenantId,
|
||||
optionalUuidString(body.id, 'id'),
|
||||
nullableString(body.legacyId),
|
||||
code,
|
||||
requiredString(body, 'title'),
|
||||
nullableString(body.description),
|
||||
costPoints,
|
||||
itemType,
|
||||
couponId,
|
||||
assetId,
|
||||
stockTotal,
|
||||
perUserLimit,
|
||||
optionalDateTimeText(body.validFrom, 'validFrom'),
|
||||
optionalDateTimeText(body.validTo, 'validTo'),
|
||||
status,
|
||||
intValue(body.order ?? body.sortOrder, 0),
|
||||
JSON.stringify(objectValue(body.metadata)),
|
||||
auth.userId,
|
||||
],
|
||||
);
|
||||
await recordAudit(client, auth, 'tenant.point_exchange_item.upserted', 'point_exchange_items', result.rows[0].id, {
|
||||
code,
|
||||
itemType,
|
||||
costPoints,
|
||||
status,
|
||||
});
|
||||
return result.rows[0];
|
||||
});
|
||||
|
||||
return { item };
|
||||
}
|
||||
|
||||
export async function pointExchangeOrdersRoute(ctx: RequestContext) {
|
||||
const auth = await requireTenantAdmin(ctx);
|
||||
requirePointMarketingPermission(auth, 'read');
|
||||
const limit = intParam(ctx, 'limit', 100, 500);
|
||||
const itemId = optionalUuidString(stringParam(ctx, 'itemId'), 'itemId');
|
||||
const userId = optionalUuidString(stringParam(ctx, 'userId'), 'userId');
|
||||
const status = stringParam(ctx, 'status');
|
||||
const params: unknown[] = [auth.tenantId];
|
||||
const filters = ['o.tenant_id = $1'];
|
||||
if (itemId) {
|
||||
params.push(itemId);
|
||||
filters.push(`o.item_id = $${params.length}::uuid`);
|
||||
}
|
||||
if (userId) {
|
||||
params.push(userId);
|
||||
filters.push(`o.user_id = $${params.length}::uuid`);
|
||||
}
|
||||
if (status) {
|
||||
if (!EXCHANGE_ORDER_STATUSES.includes(status)) throw new HttpError(400, 'status is invalid', 'INVALID_STATUS');
|
||||
params.push(status);
|
||||
filters.push(`o.status = $${params.length}`);
|
||||
}
|
||||
params.push(limit);
|
||||
|
||||
const items = await query(
|
||||
`
|
||||
select o.id, o.user_id as "userId", u.name as "userName", u.phone as "userPhone",
|
||||
o.item_id as "itemId", i.code::text as "itemCode", i.title as "itemTitle",
|
||||
i.item_type as "itemType", o.status, o.cost_points as "costPoints",
|
||||
o.score_event_id as "scoreEventId", o.coupon_redemption_id as "couponRedemptionId",
|
||||
cr.coupon_code as "couponCode", o.asset_id as "assetId",
|
||||
o.metadata, o.exchanged_at as "exchangedAt",
|
||||
o.created_at as "createdAt", o.updated_at as "updatedAt"
|
||||
from public.user_point_exchange_orders o
|
||||
join public.point_exchange_items i on i.tenant_id = o.tenant_id and i.id = o.item_id
|
||||
left join public.platform_users u on u.id = o.user_id
|
||||
left join public.coupon_redemptions cr on cr.tenant_id = o.tenant_id and cr.id = o.coupon_redemption_id
|
||||
where ${filters.join(' and ')}
|
||||
order by o.exchanged_at desc
|
||||
limit $${params.length}
|
||||
`,
|
||||
params,
|
||||
);
|
||||
return { items };
|
||||
}
|
||||
@@ -24,7 +24,7 @@ const TENANT_MEMBER_ROLES = ['tenant_owner', 'tenant_admin', 'tenant_operator',
|
||||
const TENANT_MEMBER_STATUSES = ['active', 'invited', 'disabled'];
|
||||
const ROLE_TEMPLATE_STATUSES = ['active', 'disabled', 'archived'];
|
||||
const BADGE_CATEGORIES = ['learning', 'practice', 'vocabulary', 'mock_exam', 'activity', 'feedback', 'sales', 'system', 'custom'];
|
||||
const BADGE_UNLOCK_TYPES = ['manual', 'auto', 'score', 'check_in', 'practice_count', 'vocabulary_mastered', 'mock_exam_score', 'feedback_resolved', 'custom'];
|
||||
const BADGE_UNLOCK_TYPES = ['manual', 'auto', 'score', 'check_in', 'practice_count', 'vocabulary_mastered', 'mock_exam_score', 'feedback_resolved', 'activity_reward', 'custom'];
|
||||
const BADGE_OPERATORS = ['gte', 'lte', 'eq', 'gt', 'lt'];
|
||||
const THEME_MODES = ['light', 'dark', 'auto'];
|
||||
const THEME_DENSITIES = ['compact', 'comfortable', 'dense'];
|
||||
|
||||
@@ -21,6 +21,51 @@ export interface StudentProfile {
|
||||
recentPractices?: unknown[];
|
||||
}
|
||||
|
||||
export interface PointActivityTask {
|
||||
id: string;
|
||||
code?: string;
|
||||
title?: string;
|
||||
description?: string | null;
|
||||
taskType?: string;
|
||||
rewardPoints?: number;
|
||||
claimLimitPerUser?: number;
|
||||
periodType?: 'once' | 'daily' | 'weekly' | 'monthly' | 'unlimited';
|
||||
validFrom?: string | null;
|
||||
validTo?: string | null;
|
||||
status?: string;
|
||||
order?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
claimCount?: number;
|
||||
currentPeriodClaimCount?: number;
|
||||
currentPeriodClaimId?: string | null;
|
||||
claimedInCurrentPeriod?: boolean;
|
||||
remainingClaims?: number;
|
||||
lastClaimedAt?: string | null;
|
||||
}
|
||||
|
||||
export interface PointExchangeItem {
|
||||
id: string;
|
||||
code?: string;
|
||||
title?: string;
|
||||
description?: string | null;
|
||||
costPoints?: number;
|
||||
itemType?: 'coupon' | 'manual' | 'asset' | 'custom';
|
||||
couponId?: string | null;
|
||||
assetId?: string | null;
|
||||
stockTotal?: number | null;
|
||||
stockUsed?: number;
|
||||
stockRemaining?: number | null;
|
||||
perUserLimit?: number;
|
||||
validFrom?: string | null;
|
||||
validTo?: string | null;
|
||||
status?: string;
|
||||
order?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
redeemedCount?: number;
|
||||
remainingUserRedemptions?: number;
|
||||
lastExchangedAt?: string | null;
|
||||
}
|
||||
|
||||
export async function loadProfile() {
|
||||
return apiRequest<{ item?: StudentProfile }>('/api/profile/me');
|
||||
}
|
||||
@@ -42,6 +87,46 @@ export async function checkIn() {
|
||||
return apiRequest<{ item?: Record<string, unknown> }>('/api/profile/check-in', { method: 'POST' });
|
||||
}
|
||||
|
||||
export async function loadScoreEvents(limit = 50) {
|
||||
return apiRequest<{ items?: Record<string, unknown>[] }>('/api/profile/score-events', { query: { limit } });
|
||||
}
|
||||
|
||||
export async function loadActivityTasks(query: { taskType?: string; limit?: number } = {}) {
|
||||
return apiRequest<{ items?: PointActivityTask[] }>('/api/profile/activity-tasks', {
|
||||
query: { ...query, limit: query.limit || 100 },
|
||||
});
|
||||
}
|
||||
|
||||
export async function claimActivityTask(input: {
|
||||
taskId?: string;
|
||||
code?: string;
|
||||
sourceType?: string;
|
||||
sourceId?: string;
|
||||
idempotencyKey?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
}) {
|
||||
return apiRequest<{ item?: Record<string, unknown> }>('/api/profile/activity-tasks/claim', {
|
||||
method: 'POST',
|
||||
body: input,
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadExchangeItems(limit = 100) {
|
||||
return apiRequest<{ items?: PointExchangeItem[] }>('/api/profile/exchange-items', { query: { limit } });
|
||||
}
|
||||
|
||||
export async function redeemExchangeItem(input: {
|
||||
itemId?: string;
|
||||
code?: string;
|
||||
idempotencyKey?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
}) {
|
||||
return apiRequest<{ item?: Record<string, unknown> }>('/api/profile/exchange-items/redeem', {
|
||||
method: 'POST',
|
||||
body: input,
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadBadges() {
|
||||
return apiRequest<{ items?: Record<string, unknown>[] }>('/api/profile/badges');
|
||||
}
|
||||
|
||||
@@ -474,6 +474,88 @@ export interface CouponReport {
|
||||
daily?: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
export interface PointActivityTaskItem {
|
||||
id: string;
|
||||
legacyId?: string | null;
|
||||
code?: string;
|
||||
title?: string;
|
||||
description?: string | null;
|
||||
taskType?: 'daily_check_in' | 'feedback_submit' | 'feedback_resolved' | 'practice_complete' | 'vocabulary_review' | 'mock_exam_submit' | 'manual';
|
||||
rewardPoints?: number;
|
||||
claimLimitPerUser?: number;
|
||||
periodType?: 'once' | 'daily' | 'weekly' | 'monthly' | 'unlimited';
|
||||
validFrom?: string | null;
|
||||
validTo?: string | null;
|
||||
status?: 'active' | 'disabled' | 'archived';
|
||||
order?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
claimCount?: number;
|
||||
claimUserCount?: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface PointActivityTaskInput {
|
||||
id?: string;
|
||||
legacyId?: string | null;
|
||||
code: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
taskType?: PointActivityTaskItem['taskType'];
|
||||
rewardPoints: number;
|
||||
claimLimitPerUser?: number;
|
||||
periodType?: PointActivityTaskItem['periodType'];
|
||||
validFrom?: string | null;
|
||||
validTo?: string | null;
|
||||
status?: PointActivityTaskItem['status'];
|
||||
order?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PointExchangeItem {
|
||||
id: string;
|
||||
legacyId?: string | null;
|
||||
code?: string;
|
||||
title?: string;
|
||||
description?: string | null;
|
||||
costPoints?: number;
|
||||
itemType?: 'coupon' | 'manual' | 'asset' | 'custom';
|
||||
couponId?: string | null;
|
||||
couponCode?: string | null;
|
||||
assetId?: string | null;
|
||||
stockTotal?: number | null;
|
||||
stockUsed?: number;
|
||||
stockRemaining?: number | null;
|
||||
perUserLimit?: number;
|
||||
validFrom?: string | null;
|
||||
validTo?: string | null;
|
||||
status?: 'active' | 'disabled' | 'archived';
|
||||
order?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
orderCount?: number;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface PointExchangeItemInput {
|
||||
id?: string;
|
||||
legacyId?: string | null;
|
||||
code: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
costPoints: number;
|
||||
itemType?: PointExchangeItem['itemType'];
|
||||
couponId?: string | null;
|
||||
assetId?: string | null;
|
||||
stockTotal?: number | null;
|
||||
perUserLimit?: number;
|
||||
validFrom?: string | null;
|
||||
validTo?: string | null;
|
||||
status?: PointExchangeItem['status'];
|
||||
order?: number;
|
||||
metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CodeBatchItem {
|
||||
id: string;
|
||||
name?: string | null;
|
||||
@@ -1083,6 +1165,49 @@ export async function loadCouponReport(query: {
|
||||
return apiRequest<{ item?: CouponReport }>('/api/tenant-admin/coupons/report', { query });
|
||||
}
|
||||
|
||||
export async function loadPointActivityTasks(query: { status?: string; taskType?: string; limit?: number } = {}) {
|
||||
return apiRequest<{ items?: PointActivityTaskItem[] }>('/api/tenant-admin/point-activity-tasks', {
|
||||
query: { ...query, limit: query.limit || 100 },
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertPointActivityTask(input: PointActivityTaskInput) {
|
||||
return apiRequest<{ item?: PointActivityTaskItem }>('/api/tenant-admin/point-activity-tasks', {
|
||||
method: 'PUT',
|
||||
body: input,
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadPointActivityClaims(query: { taskId?: string; userId?: string; limit?: number } = {}) {
|
||||
return apiRequest<{ items?: Record<string, unknown>[] }>('/api/tenant-admin/point-activity-claims', {
|
||||
query: { ...query, limit: query.limit || 100 },
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadPointExchangeItems(query: { status?: string; itemType?: string; limit?: number } = {}) {
|
||||
return apiRequest<{ items?: PointExchangeItem[] }>('/api/tenant-admin/point-exchange-items', {
|
||||
query: { ...query, limit: query.limit || 100 },
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertPointExchangeItem(input: PointExchangeItemInput) {
|
||||
return apiRequest<{ item?: PointExchangeItem }>('/api/tenant-admin/point-exchange-items', {
|
||||
method: 'PUT',
|
||||
body: input,
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadPointExchangeOrders(query: {
|
||||
itemId?: string;
|
||||
userId?: string;
|
||||
status?: 'completed' | 'pending_fulfillment' | 'cancelled';
|
||||
limit?: number;
|
||||
} = {}) {
|
||||
return apiRequest<{ items?: Record<string, unknown>[] }>('/api/tenant-admin/point-exchange-orders', {
|
||||
query: { ...query, limit: query.limit || 100 },
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadCodeBatches() {
|
||||
return apiRequest<{ items?: CodeBatchItem[] }>('/api/tenant-admin/code-batches');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user