统一前后端代码格式化配置
This commit is contained in:
@@ -39,7 +39,9 @@ type AdminAuditLogListResult = {
|
||||
total: number
|
||||
}
|
||||
|
||||
export async function createAdminAuditLog(input: AdminAuditLogCreateInput): Promise<AdminAuditLogRow | null> {
|
||||
export async function createAdminAuditLog(
|
||||
input: AdminAuditLogCreateInput,
|
||||
): Promise<AdminAuditLogRow | null> {
|
||||
const result = await query<AdminAuditLogRow>(
|
||||
`
|
||||
INSERT INTO admin_audit_logs (
|
||||
@@ -69,12 +71,19 @@ export async function createAdminAuditLog(input: AdminAuditLogCreateInput): Prom
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function getAdminAuditLogById(logId: number | string): Promise<AdminAuditLogRow | null> {
|
||||
const result = await query<AdminAuditLogRow>('SELECT * FROM admin_audit_logs WHERE id = $1 LIMIT 1', [Number(logId)])
|
||||
export async function getAdminAuditLogById(
|
||||
logId: number | string,
|
||||
): Promise<AdminAuditLogRow | null> {
|
||||
const result = await query<AdminAuditLogRow>(
|
||||
'SELECT * FROM admin_audit_logs WHERE id = $1 LIMIT 1',
|
||||
[Number(logId)],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function listAdminAuditLogs(queryInput: AdminAuditLogListInput = {}): Promise<AdminAuditLogListResult> {
|
||||
export async function listAdminAuditLogs(
|
||||
queryInput: AdminAuditLogListInput = {},
|
||||
): Promise<AdminAuditLogListResult> {
|
||||
const conditions: string[] = []
|
||||
const params: unknown[] = []
|
||||
|
||||
@@ -108,7 +117,7 @@ export async function listAdminAuditLogs(queryInput: AdminAuditLogListInput = {}
|
||||
const pageSize = Number(queryInput.pageSize) || 20
|
||||
const offset = (page - 1) * pageSize
|
||||
|
||||
const totalResult = await query<{ [column: string]: unknown, total: number }>(
|
||||
const totalResult = await query<{ [column: string]: unknown; total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM admin_audit_logs ${whereClause}`,
|
||||
params,
|
||||
)
|
||||
|
||||
@@ -20,10 +20,12 @@ type AdminUserCreateInput = {
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
type AdminUserPatch = Partial<Pick<
|
||||
AdminUserRow,
|
||||
'username' | 'password_hash' | 'role' | 'status' | 'session_version' | 'updated_at'
|
||||
>>
|
||||
type AdminUserPatch = Partial<
|
||||
Pick<
|
||||
AdminUserRow,
|
||||
'username' | 'password_hash' | 'role' | 'status' | 'session_version' | 'updated_at'
|
||||
>
|
||||
>
|
||||
|
||||
type AdminUserListInput = {
|
||||
page?: number
|
||||
@@ -44,23 +46,23 @@ const ADMIN_USER_SELECT = `
|
||||
`
|
||||
|
||||
export async function getAdminUserById(userId: number | string): Promise<AdminUserRow | null> {
|
||||
const result = await query<AdminUserRow>(
|
||||
`${ADMIN_USER_SELECT} WHERE au.id = $1 LIMIT 1`,
|
||||
[Number(userId)],
|
||||
)
|
||||
const result = await query<AdminUserRow>(`${ADMIN_USER_SELECT} WHERE au.id = $1 LIMIT 1`, [
|
||||
Number(userId),
|
||||
])
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function getAdminUserByUsername(username: string): Promise<AdminUserRow | null> {
|
||||
const result = await query<AdminUserRow>(
|
||||
`${ADMIN_USER_SELECT} WHERE au.username = $1 LIMIT 1`,
|
||||
[String(username || '').trim().toLowerCase()],
|
||||
)
|
||||
const result = await query<AdminUserRow>(`${ADMIN_USER_SELECT} WHERE au.username = $1 LIMIT 1`, [
|
||||
String(username || '')
|
||||
.trim()
|
||||
.toLowerCase(),
|
||||
])
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function createAdminUser(input: AdminUserCreateInput): Promise<AdminUserRow | null> {
|
||||
const result = await query<{ [column: string]: unknown, id: number }>(
|
||||
const result = await query<{ [column: string]: unknown; id: number }>(
|
||||
`
|
||||
INSERT INTO admin_users (
|
||||
username,
|
||||
@@ -97,7 +99,7 @@ export async function updateAdminUser(
|
||||
}
|
||||
|
||||
const next = { ...current, ...patch }
|
||||
const result = await query<{ [column: string]: unknown, id: number }>(
|
||||
const result = await query<{ [column: string]: unknown; id: number }>(
|
||||
`
|
||||
UPDATE admin_users
|
||||
SET
|
||||
@@ -151,7 +153,7 @@ export async function listAdminUsers({
|
||||
}
|
||||
|
||||
const whereClause = filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : ''
|
||||
const totalResult = await query<{ [column: string]: unknown, total: number }>(
|
||||
const totalResult = await query<{ [column: string]: unknown; total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM admin_users ${whereClause}`,
|
||||
params,
|
||||
)
|
||||
@@ -175,7 +177,7 @@ export async function listAdminUsers({
|
||||
}
|
||||
|
||||
export async function countActiveAdminUsers(): Promise<number> {
|
||||
const result = await query<{ [column: string]: unknown, total: number }>(
|
||||
const result = await query<{ [column: string]: unknown; total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM admin_users WHERE role = 'admin' AND status = 'active'`,
|
||||
)
|
||||
return Number(result.rows[0]?.total || 0)
|
||||
|
||||
@@ -26,12 +26,16 @@ type ClaimTokenCreateInput = {
|
||||
updatedAt: string
|
||||
}
|
||||
|
||||
type ClaimTokenPatch = Partial<Pick<
|
||||
ClaimTokenRow,
|
||||
'status' | 'expired_at' | 'used_at' | 'max_use_count' | 'used_count' | 'updated_at'
|
||||
>>
|
||||
type ClaimTokenPatch = Partial<
|
||||
Pick<
|
||||
ClaimTokenRow,
|
||||
'status' | 'expired_at' | 'used_at' | 'max_use_count' | 'used_count' | 'updated_at'
|
||||
>
|
||||
>
|
||||
|
||||
export async function createClaimToken(input: ClaimTokenCreateInput): Promise<ClaimTokenRow | null> {
|
||||
export async function createClaimToken(
|
||||
input: ClaimTokenCreateInput,
|
||||
): Promise<ClaimTokenRow | null> {
|
||||
const result = await query<ClaimTokenRow>(
|
||||
`
|
||||
INSERT INTO claim_tokens (
|
||||
@@ -74,16 +78,23 @@ export async function createClaimToken(input: ClaimTokenCreateInput): Promise<Cl
|
||||
}
|
||||
|
||||
export async function getClaimTokenById(tokenId: number | string): Promise<ClaimTokenRow | null> {
|
||||
const result = await query<ClaimTokenRow>('SELECT * FROM claim_tokens WHERE id = $1 LIMIT 1', [Number(tokenId)])
|
||||
const result = await query<ClaimTokenRow>('SELECT * FROM claim_tokens WHERE id = $1 LIMIT 1', [
|
||||
Number(tokenId),
|
||||
])
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function findClaimTokenByToken(token: string): Promise<ClaimTokenRow | null> {
|
||||
const result = await query<ClaimTokenRow>('SELECT * FROM claim_tokens WHERE token = $1 LIMIT 1', [String(token || '').trim()])
|
||||
const result = await query<ClaimTokenRow>('SELECT * FROM claim_tokens WHERE token = $1 LIMIT 1', [
|
||||
String(token || '').trim(),
|
||||
])
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function updateClaimToken(tokenId: number | string, patch: ClaimTokenPatch): Promise<ClaimTokenRow | null> {
|
||||
export async function updateClaimToken(
|
||||
tokenId: number | string,
|
||||
patch: ClaimTokenPatch,
|
||||
): Promise<ClaimTokenRow | null> {
|
||||
const current = await getClaimTokenById(tokenId)
|
||||
if (!current) {
|
||||
return null
|
||||
|
||||
@@ -47,7 +47,9 @@ export type FulfillmentProfileRequirementInput = {
|
||||
configJson?: string | Record<string, unknown>
|
||||
}
|
||||
|
||||
export async function getFulfillmentProfileByKey(profileKey: string): Promise<FulfillmentProfileRow | null> {
|
||||
export async function getFulfillmentProfileByKey(
|
||||
profileKey: string,
|
||||
): Promise<FulfillmentProfileRow | null> {
|
||||
const result = await query<FulfillmentProfileRow>(
|
||||
'SELECT * FROM fulfillment_profiles WHERE profile_key = $1 LIMIT 1',
|
||||
[String(profileKey || '').trim()],
|
||||
@@ -104,10 +106,9 @@ export async function replaceFulfillmentProfileRequirements(
|
||||
timestamp: string,
|
||||
): Promise<void> {
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
'DELETE FROM fulfillment_profile_requirements WHERE profile_id = $1',
|
||||
[Number(profileId)],
|
||||
)
|
||||
await client.query('DELETE FROM fulfillment_profile_requirements WHERE profile_id = $1', [
|
||||
Number(profileId),
|
||||
])
|
||||
|
||||
for (const requirement of requirements) {
|
||||
await client.query(
|
||||
|
||||
@@ -10,32 +10,35 @@ test('syncKuaishouCloudTaskStateForTask 将 Date 更新时间规范化为 ISO
|
||||
return { rows: [] }
|
||||
}
|
||||
|
||||
await syncKuaishouCloudTaskStateForTask({
|
||||
taskId: 9,
|
||||
executorKey: 'kuaishou_ct_assisted',
|
||||
contextJson: {
|
||||
kuaishouCloudFulfillment: {
|
||||
ticket: {
|
||||
status: 'verified',
|
||||
code: '597172E91CF18417',
|
||||
},
|
||||
binding: {
|
||||
bindUrl: 'https://example.test/bind',
|
||||
vnPhone: '14062706492',
|
||||
roleName: '测试角色',
|
||||
roleId: '4212063544',
|
||||
resolvedSourceKey: 'account_test',
|
||||
},
|
||||
dispatch: {
|
||||
status: 'pending',
|
||||
},
|
||||
consume: {
|
||||
status: 'pending',
|
||||
await syncKuaishouCloudTaskStateForTask(
|
||||
{
|
||||
taskId: 9,
|
||||
executorKey: 'kuaishou_ct_assisted',
|
||||
contextJson: {
|
||||
kuaishouCloudFulfillment: {
|
||||
ticket: {
|
||||
status: 'verified',
|
||||
code: '597172E91CF18417',
|
||||
},
|
||||
binding: {
|
||||
bindUrl: 'https://example.test/bind',
|
||||
vnPhone: '14062706492',
|
||||
roleName: '测试角色',
|
||||
roleId: '4212063544',
|
||||
resolvedSourceKey: 'account_test',
|
||||
},
|
||||
dispatch: {
|
||||
status: 'pending',
|
||||
},
|
||||
consume: {
|
||||
status: 'pending',
|
||||
},
|
||||
},
|
||||
},
|
||||
updatedAt: new Date('2026-05-29T09:05:46.658Z'),
|
||||
},
|
||||
updatedAt: new Date('2026-05-29T09:05:46.658Z'),
|
||||
}, executor)
|
||||
executor,
|
||||
)
|
||||
|
||||
assert.equal(calls.length, 1)
|
||||
assert.match(calls[0].text, /INSERT INTO kuaishou_cloud_task_states/)
|
||||
|
||||
@@ -64,7 +64,10 @@ test('resolveOrderItemSyncPlan matches by identity before falling back to positi
|
||||
|
||||
const plan = resolveOrderItemSyncPlan(existingItems, nextItems)
|
||||
|
||||
assert.deepEqual(plan.updates.map((item) => item.orderItemId), [22, 21])
|
||||
assert.deepEqual(
|
||||
plan.updates.map((item) => item.orderItemId),
|
||||
[22, 21],
|
||||
)
|
||||
assert.deepEqual(plan.creates, [])
|
||||
assert.deepEqual(plan.deletes, [])
|
||||
})
|
||||
@@ -88,7 +91,10 @@ test('resolveOrderItemSyncPlan keeps surplus existing ids for conditional cleanu
|
||||
|
||||
const plan = resolveOrderItemSyncPlan(existingItems, nextItems)
|
||||
|
||||
assert.deepEqual(plan.updates.map((item) => item.orderItemId), [31])
|
||||
assert.deepEqual(
|
||||
plan.updates.map((item) => item.orderItemId),
|
||||
[31],
|
||||
)
|
||||
assert.deepEqual(plan.creates, [])
|
||||
assert.deepEqual(plan.deletes, [32])
|
||||
})
|
||||
|
||||
@@ -204,6 +204,8 @@ async function listOrderItemsByOrderIdWithExecutor(
|
||||
}
|
||||
|
||||
export async function getOrderItemById(orderItemId: number | string): Promise<OrderItemRow | null> {
|
||||
const result = await query<OrderItemRow>('SELECT * FROM order_items WHERE id = $1 LIMIT 1', [Number(orderItemId)])
|
||||
const result = await query<OrderItemRow>('SELECT * FROM order_items WHERE id = $1 LIMIT 1', [
|
||||
Number(orderItemId),
|
||||
])
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
@@ -29,12 +29,7 @@ export async function createTaskEvent(
|
||||
) VALUES ($1, $2, $3::jsonb, $4)
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
Number(taskId),
|
||||
String(eventType || '').trim(),
|
||||
JSON.stringify(payload || {}),
|
||||
createdAt,
|
||||
],
|
||||
[Number(taskId), String(eventType || '').trim(), JSON.stringify(payload || {}), createdAt],
|
||||
)
|
||||
|
||||
return result.rows[0] || null
|
||||
|
||||
@@ -9,10 +9,7 @@ import type {
|
||||
TaskRuntimeContextPatch,
|
||||
TaskUpdatePatch,
|
||||
} from '../types/repository/inputs.js'
|
||||
import type {
|
||||
TaskListQueryResult,
|
||||
TaskRow,
|
||||
} from '../types/repository/rows.js'
|
||||
import type { TaskListQueryResult, TaskRow } from '../types/repository/rows.js'
|
||||
|
||||
type TaskQueryExecutor = (text: string, params?: unknown[]) => Promise<{ rows: unknown[] }>
|
||||
const KUAISHOU_FEIFEI_EXECUTOR_KEY = 'kuaishou_feifei'
|
||||
@@ -150,21 +147,32 @@ export async function createTask(input: TaskCreateInput): Promise<TaskRow | null
|
||||
|
||||
const taskId = Number(taskResult.rows[0]?.id || 0)
|
||||
if (input.runtimeContext) {
|
||||
await upsertTaskRuntimeContextWithClient(client, taskId, input.runtimeContext, input.createdAt)
|
||||
await upsertTaskRuntimeContextWithClient(
|
||||
client,
|
||||
taskId,
|
||||
input.runtimeContext,
|
||||
input.createdAt,
|
||||
)
|
||||
}
|
||||
|
||||
await syncKuaishouCloudTaskStateForTask({
|
||||
taskId,
|
||||
executorKey: input.executorKey,
|
||||
contextJson: input.contextJson || '{}',
|
||||
updatedAt: input.updatedAt,
|
||||
}, client.query.bind(client) as TaskQueryExecutor)
|
||||
await syncKuaishouCloudTaskStateForTask(
|
||||
{
|
||||
taskId,
|
||||
executorKey: input.executorKey,
|
||||
contextJson: input.contextJson || '{}',
|
||||
updatedAt: input.updatedAt,
|
||||
},
|
||||
client.query.bind(client) as TaskQueryExecutor,
|
||||
)
|
||||
|
||||
return getTaskByIdWithExecutor(client.query.bind(client) as TaskQueryExecutor, taskId)
|
||||
})
|
||||
}
|
||||
|
||||
export async function updateTask(taskId: number | string, patch: TaskUpdatePatch): Promise<TaskRow | null> {
|
||||
export async function updateTask(
|
||||
taskId: number | string,
|
||||
patch: TaskUpdatePatch,
|
||||
): Promise<TaskRow | null> {
|
||||
const current = await getTaskById(taskId)
|
||||
if (!current) {
|
||||
return null
|
||||
@@ -218,26 +226,38 @@ export async function updateTask(taskId: number | string, patch: TaskUpdatePatch
|
||||
|
||||
if (containsRuntimeContextPatch(patch)) {
|
||||
const runtimeContextPatch: TaskRuntimeContextPatch = {}
|
||||
if (patch.runtime_session_id !== undefined) runtimeContextPatch.runtimeSessionId = patch.runtime_session_id
|
||||
if (patch.runtime_session_id !== undefined)
|
||||
runtimeContextPatch.runtimeSessionId = patch.runtime_session_id
|
||||
if (patch.login_type !== undefined) runtimeContextPatch.loginType = patch.login_type
|
||||
if (patch.nickname !== undefined) runtimeContextPatch.nickname = patch.nickname
|
||||
if (patch.role_id !== undefined) runtimeContextPatch.roleId = patch.role_id
|
||||
if (patch.role_name !== undefined) runtimeContextPatch.roleName = patch.role_name
|
||||
if (patch.area !== undefined) runtimeContextPatch.area = patch.area
|
||||
if (patch.partition_name !== undefined) runtimeContextPatch.partitionName = patch.partition_name
|
||||
if (patch.screenshot_path !== undefined) runtimeContextPatch.screenshotPath = patch.screenshot_path
|
||||
if (patch.artifacts_json !== undefined) runtimeContextPatch.artifactsJson = patch.artifacts_json
|
||||
if (patch.partition_name !== undefined)
|
||||
runtimeContextPatch.partitionName = patch.partition_name
|
||||
if (patch.screenshot_path !== undefined)
|
||||
runtimeContextPatch.screenshotPath = patch.screenshot_path
|
||||
if (patch.artifacts_json !== undefined)
|
||||
runtimeContextPatch.artifactsJson = patch.artifacts_json
|
||||
if (patch.state_json !== undefined) runtimeContextPatch.stateJson = patch.state_json
|
||||
|
||||
await upsertTaskRuntimeContextWithClient(client, Number(taskId), runtimeContextPatch, patch.updated_at || current.updated_at)
|
||||
await upsertTaskRuntimeContextWithClient(
|
||||
client,
|
||||
Number(taskId),
|
||||
runtimeContextPatch,
|
||||
patch.updated_at || current.updated_at,
|
||||
)
|
||||
}
|
||||
|
||||
await syncKuaishouCloudTaskStateForTask({
|
||||
taskId,
|
||||
executorKey: next.executor_key,
|
||||
contextJson: next.context_json,
|
||||
updatedAt: next.updated_at,
|
||||
}, client.query.bind(client) as TaskQueryExecutor)
|
||||
await syncKuaishouCloudTaskStateForTask(
|
||||
{
|
||||
taskId,
|
||||
executorKey: next.executor_key,
|
||||
contextJson: next.context_json,
|
||||
updatedAt: next.updated_at,
|
||||
},
|
||||
client.query.bind(client) as TaskQueryExecutor,
|
||||
)
|
||||
|
||||
return getTaskByIdWithExecutor(client.query.bind(client) as TaskQueryExecutor, taskId)
|
||||
})
|
||||
@@ -296,12 +316,15 @@ export async function updateTaskStatusIfCurrent(
|
||||
return null
|
||||
}
|
||||
|
||||
await syncKuaishouCloudTaskStateForTask({
|
||||
taskId: updated.id,
|
||||
executorKey: updated.executor_key,
|
||||
contextJson: updated.context_json,
|
||||
updatedAt: updated.updated_at,
|
||||
}, client.query.bind(client) as TaskQueryExecutor)
|
||||
await syncKuaishouCloudTaskStateForTask(
|
||||
{
|
||||
taskId: updated.id,
|
||||
executorKey: updated.executor_key,
|
||||
contextJson: updated.context_json,
|
||||
updatedAt: updated.updated_at,
|
||||
},
|
||||
client.query.bind(client) as TaskQueryExecutor,
|
||||
)
|
||||
|
||||
return getTaskByIdWithExecutor(client.query.bind(client) as TaskQueryExecutor, taskId)
|
||||
})
|
||||
@@ -311,7 +334,9 @@ export async function getTaskById(taskId: number | string): Promise<TaskRow | nu
|
||||
return getTaskByIdWithExecutor(query, taskId)
|
||||
}
|
||||
|
||||
export async function findTaskByClaimTokenId(claimTokenId: number | string): Promise<TaskRow | null> {
|
||||
export async function findTaskByClaimTokenId(
|
||||
claimTokenId: number | string,
|
||||
): Promise<TaskRow | null> {
|
||||
const result = await query<TaskRow>(
|
||||
`${buildTaskSelect()}
|
||||
JOIN claim_tokens ctf ON ctf.task_id = ft.id
|
||||
@@ -441,7 +466,7 @@ export async function listTasks({
|
||||
}
|
||||
|
||||
const whereClause = filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : ''
|
||||
const totalResult = await query<{ [column: string]: unknown, total: number }>(
|
||||
const totalResult = await query<{ [column: string]: unknown; total: number }>(
|
||||
`
|
||||
SELECT COUNT(*)::int AS total
|
||||
FROM fulfillment_tasks ft
|
||||
@@ -525,8 +550,12 @@ async function upsertTaskRuntimeContextWithClient(
|
||||
next.area,
|
||||
next.partition_name,
|
||||
next.screenshot_path,
|
||||
typeof next.artifacts_json === 'string' ? next.artifacts_json : JSON.stringify(next.artifacts_json || {}),
|
||||
typeof next.state_json === 'string' ? next.state_json : JSON.stringify(next.state_json || {}),
|
||||
typeof next.artifacts_json === 'string'
|
||||
? next.artifacts_json
|
||||
: JSON.stringify(next.artifacts_json || {}),
|
||||
typeof next.state_json === 'string'
|
||||
? next.state_json
|
||||
: JSON.stringify(next.state_json || {}),
|
||||
timestamp,
|
||||
timestamp,
|
||||
],
|
||||
@@ -560,7 +589,9 @@ async function upsertTaskRuntimeContextWithClient(
|
||||
next.area,
|
||||
next.partition_name,
|
||||
next.screenshot_path,
|
||||
typeof next.artifacts_json === 'string' ? next.artifacts_json : JSON.stringify(next.artifacts_json || {}),
|
||||
typeof next.artifacts_json === 'string'
|
||||
? next.artifacts_json
|
||||
: JSON.stringify(next.artifacts_json || {}),
|
||||
typeof next.state_json === 'string' ? next.state_json : JSON.stringify(next.state_json || {}),
|
||||
timestamp,
|
||||
Number(taskId),
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { PoolClient } from 'pg'
|
||||
|
||||
import type { WorkerWalletRow } from './types.js'
|
||||
|
||||
|
||||
export async function ensureWorkerWalletWithClient(
|
||||
client: PoolClient,
|
||||
workerId: number,
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
|
||||
|
||||
export type WorkerLevelRow = {
|
||||
id: number
|
||||
level_key: string
|
||||
|
||||
@@ -1,10 +1,25 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { ensureWorkerWalletWithClient, getWorkerWalletWithClient, toJsonString, toPositiveInteger } from './shared.js'
|
||||
import type { CreateWorkOrderInput, GrabWorkOrderResult, ListInput, ProblemWorkOrderResolutionAction, ProductRuleListInput, WorkCategoryRow, WorkerDepositUnfreezeRow, WorkOrderRow, WorkOrderShareRow, WorkProductRuleRow } from './types.js'
|
||||
import {
|
||||
ensureWorkerWalletWithClient,
|
||||
getWorkerWalletWithClient,
|
||||
toJsonString,
|
||||
toPositiveInteger,
|
||||
} from './shared.js'
|
||||
import type {
|
||||
CreateWorkOrderInput,
|
||||
GrabWorkOrderResult,
|
||||
ListInput,
|
||||
ProblemWorkOrderResolutionAction,
|
||||
ProductRuleListInput,
|
||||
WorkCategoryRow,
|
||||
WorkerDepositUnfreezeRow,
|
||||
WorkOrderRow,
|
||||
WorkOrderShareRow,
|
||||
WorkProductRuleRow,
|
||||
} from './types.js'
|
||||
import type { PoolClient } from 'pg'
|
||||
import { maybeUpgradeWorkerLevelWithClient } from './worker-repo.js'
|
||||
|
||||
|
||||
const WORK_ORDER_SELECT = `
|
||||
SELECT
|
||||
wo.*,
|
||||
@@ -248,7 +263,10 @@ export async function submitWorkOrderShareAcceptance(input: {
|
||||
workerId: number
|
||||
acceptanceJson: string
|
||||
now: string
|
||||
}): Promise<{ share: WorkOrderShareRow | null; failureReason: 'share_not_found' | 'share_status_invalid' | null }> {
|
||||
}): Promise<{
|
||||
share: WorkOrderShareRow | null
|
||||
failureReason: 'share_not_found' | 'share_status_invalid' | null
|
||||
}> {
|
||||
return withTransaction(async (client) => {
|
||||
const lockResult = await client.query<{ id: number }>(
|
||||
`
|
||||
@@ -436,7 +454,9 @@ export async function getWorkCategoryByKey(categoryKey: string): Promise<WorkCat
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function getWorkCategoryById(categoryId: number | string): Promise<WorkCategoryRow | null> {
|
||||
export async function getWorkCategoryById(
|
||||
categoryId: number | string,
|
||||
): Promise<WorkCategoryRow | null> {
|
||||
const result = await query<WorkCategoryRow>(
|
||||
'SELECT * FROM work_categories WHERE id = $1 LIMIT 1',
|
||||
[Number(categoryId)],
|
||||
@@ -747,8 +767,7 @@ export async function listWorkOrders({
|
||||
pinnedFirst = false,
|
||||
sort = 'id_desc',
|
||||
}: ListInput = {}): Promise<{ items: WorkOrderRow[]; total: number }> {
|
||||
const effectiveStatuses =
|
||||
statuses.length > 0 ? statuses : status.trim() ? [status.trim()] : []
|
||||
const effectiveStatuses = statuses.length > 0 ? statuses : status.trim() ? [status.trim()] : []
|
||||
const { whereClause, params } = buildWorkOrderWhere({
|
||||
statuses: effectiveStatuses,
|
||||
keyword,
|
||||
@@ -787,9 +806,7 @@ export async function listWorkOrders({
|
||||
) DESC NULLS LAST, wo.id DESC`
|
||||
})()
|
||||
: 'wo.id DESC'
|
||||
const effectiveOrderBy = pinnedFirst
|
||||
? `wo.pinned_at DESC NULLS LAST, ${orderBy}`
|
||||
: orderBy
|
||||
const effectiveOrderBy = pinnedFirst ? `wo.pinned_at DESC NULLS LAST, ${orderBy}` : orderBy
|
||||
params.push(pageSize, offset)
|
||||
const itemsResult = await query<WorkOrderRow>(
|
||||
`${WORK_ORDER_SELECT}
|
||||
@@ -911,14 +928,8 @@ export async function updateWorkOrderBasic(
|
||||
String((patch.productName ?? current.product_name) || '').trim(),
|
||||
patch.categoryId === undefined ? current.category_id : patch.categoryId,
|
||||
toPositiveInteger(patch.rewardAmount ?? current.reward_amount, 0),
|
||||
toPositiveInteger(
|
||||
patch.requiredDepositAmount ?? current.required_deposit_amount,
|
||||
0,
|
||||
),
|
||||
toPositiveInteger(
|
||||
patch.depositThresholdAmount ?? current.deposit_threshold_amount,
|
||||
0,
|
||||
),
|
||||
toPositiveInteger(patch.requiredDepositAmount ?? current.required_deposit_amount, 0),
|
||||
toPositiveInteger(patch.depositThresholdAmount ?? current.deposit_threshold_amount, 0),
|
||||
toJsonString(patch.requirementJson ?? current.requirement_json),
|
||||
toPositiveInteger(patch.timeoutMinutes ?? current.timeout_minutes, 0),
|
||||
String((patch.timeoutPolicy ?? current.timeout_policy) || 'reopen').trim(),
|
||||
@@ -1196,10 +1207,7 @@ export async function cancelWorkerWorkOrder(input: {
|
||||
|
||||
if (releaseAmount > 0) {
|
||||
const nextAvailable = Number(wallet?.available_amount || 0) + releaseAmount
|
||||
const nextFrozen = Math.max(
|
||||
0,
|
||||
Number(wallet?.frozen_deposit_amount || 0) - releaseAmount,
|
||||
)
|
||||
const nextFrozen = Math.max(0, Number(wallet?.frozen_deposit_amount || 0) - releaseAmount)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE worker_wallets
|
||||
@@ -1237,10 +1245,7 @@ export async function cancelWorkerWorkOrder(input: {
|
||||
})
|
||||
}
|
||||
|
||||
export async function unassignWorkOrder(input: {
|
||||
workOrderId: number
|
||||
now: string
|
||||
}): Promise<{
|
||||
export async function unassignWorkOrder(input: { workOrderId: number; now: string }): Promise<{
|
||||
order: WorkOrderRow | null
|
||||
failureReason: 'work_order_not_in_progress' | 'work_order_no_worker' | null
|
||||
}> {
|
||||
@@ -1286,10 +1291,7 @@ export async function unassignWorkOrder(input: {
|
||||
|
||||
if (releaseAmount > 0) {
|
||||
const nextAvailable = Number(wallet?.available_amount || 0) + releaseAmount
|
||||
const nextFrozen = Math.max(
|
||||
0,
|
||||
Number(wallet?.frozen_deposit_amount || 0) - releaseAmount,
|
||||
)
|
||||
const nextFrozen = Math.max(0, Number(wallet?.frozen_deposit_amount || 0) - releaseAmount)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE worker_wallets
|
||||
@@ -1378,10 +1380,7 @@ export async function returnAssignedWorkOrderToHall(input: {
|
||||
|
||||
if (releaseAmount > 0) {
|
||||
const nextAvailable = Number(wallet?.available_amount || 0) + releaseAmount
|
||||
const nextFrozen = Math.max(
|
||||
0,
|
||||
Number(wallet?.frozen_deposit_amount || 0) - releaseAmount,
|
||||
)
|
||||
const nextFrozen = Math.max(0, Number(wallet?.frozen_deposit_amount || 0) - releaseAmount)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE worker_wallets
|
||||
@@ -1474,10 +1473,7 @@ export async function cancelAssignedWorkOrder(input: {
|
||||
|
||||
if (releaseAmount > 0) {
|
||||
const nextAvailable = Number(wallet?.available_amount || 0) + releaseAmount
|
||||
const nextFrozen = Math.max(
|
||||
0,
|
||||
Number(wallet?.frozen_deposit_amount || 0) - releaseAmount,
|
||||
)
|
||||
const nextFrozen = Math.max(0, Number(wallet?.frozen_deposit_amount || 0) - releaseAmount)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE worker_wallets
|
||||
@@ -1608,10 +1604,7 @@ export async function acceptWorkOrderAndSettle(input: {
|
||||
Number(wallet?.available_amount || 0) +
|
||||
shareReward +
|
||||
(shouldDelayUnfreeze ? 0 : releaseAmount)
|
||||
const nextFrozen = Math.max(
|
||||
0,
|
||||
Number(wallet?.frozen_deposit_amount || 0) - releaseAmount,
|
||||
)
|
||||
const nextFrozen = Math.max(0, Number(wallet?.frozen_deposit_amount || 0) - releaseAmount)
|
||||
|
||||
await client.query(
|
||||
`
|
||||
@@ -1829,7 +1822,10 @@ export async function acceptWorkOrderAndSettle(input: {
|
||||
await maybeUpgradeWorkerLevelWithClient(client, workerId, input.now)
|
||||
}
|
||||
|
||||
return { order: await getWorkOrderByIdWithClient(client, input.workOrderId), failureReason: null }
|
||||
return {
|
||||
order: await getWorkOrderByIdWithClient(client, input.workOrderId),
|
||||
failureReason: null,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2263,7 +2259,10 @@ export async function listDueDepositUnfreezes({
|
||||
export async function releaseDepositUnfreeze({
|
||||
unfreezeId,
|
||||
now,
|
||||
}: { unfreezeId: number; now: string }): Promise<WorkerDepositUnfreezeRow | null> {
|
||||
}: {
|
||||
unfreezeId: number
|
||||
now: string
|
||||
}): Promise<WorkerDepositUnfreezeRow | null> {
|
||||
return withTransaction(async (client) => {
|
||||
const currentResult = await client.query<WorkerDepositUnfreezeRow>(
|
||||
`
|
||||
@@ -2295,10 +2294,7 @@ export async function releaseDepositUnfreeze({
|
||||
|
||||
if (amount > 0) {
|
||||
const nextAvailable = Number(wallet?.available_amount || 0) + amount
|
||||
const nextPending = Math.max(
|
||||
0,
|
||||
Number(wallet?.pending_unfreeze_amount || 0) - amount,
|
||||
)
|
||||
const nextPending = Math.max(0, Number(wallet?.pending_unfreeze_amount || 0) - amount)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE worker_wallets
|
||||
@@ -2337,7 +2333,13 @@ export async function releaseDepositUnfreeze({
|
||||
|
||||
async function enqueueDepositUnfreezeWithClient(
|
||||
client: PoolClient,
|
||||
input: { workerId: number; workOrderId: number; amount: number; unfreezeDays: number; now: string },
|
||||
input: {
|
||||
workerId: number
|
||||
workOrderId: number
|
||||
amount: number
|
||||
unfreezeDays: number
|
||||
now: string
|
||||
},
|
||||
) {
|
||||
if (input.amount <= 0) return
|
||||
const unfreezeAt = new Date(
|
||||
@@ -2375,7 +2377,9 @@ export async function countWorkerActiveOrders(workerId: number | string): Promis
|
||||
return Number(result.rows[0]?.total || 0)
|
||||
}
|
||||
|
||||
export async function countTimeoutEventsByWorkerIds(workerIds: number[]): Promise<Map<number, number>> {
|
||||
export async function countTimeoutEventsByWorkerIds(
|
||||
workerIds: number[],
|
||||
): Promise<Map<number, number>> {
|
||||
const counts = new Map<number, number>()
|
||||
const uniqueIds = [...new Set(workerIds.map((id) => Number(id)).filter((id) => id > 0))]
|
||||
if (uniqueIds.length === 0) return counts
|
||||
@@ -2481,7 +2485,10 @@ async function getOutstandingDepositAmountWithClient(
|
||||
return resolveOutstandingDepositAmount(result.rows[0])
|
||||
}
|
||||
|
||||
async function countWorkerActiveOrdersWithClient(client: PoolClient, workerId: number): Promise<number> {
|
||||
async function countWorkerActiveOrdersWithClient(
|
||||
client: PoolClient,
|
||||
workerId: number,
|
||||
): Promise<number> {
|
||||
const result = await client.query<{ total: number }>(
|
||||
`
|
||||
SELECT (
|
||||
@@ -2542,11 +2549,7 @@ function buildWorkOrderWhere({
|
||||
const filters: string[] = []
|
||||
const params: unknown[] = []
|
||||
const normalizedStatuses = [
|
||||
...new Set(
|
||||
statuses
|
||||
.map((item) => String(item || '').trim())
|
||||
.filter(Boolean),
|
||||
),
|
||||
...new Set(statuses.map((item) => String(item || '').trim()).filter(Boolean)),
|
||||
]
|
||||
if (normalizedStatuses.length > 0) {
|
||||
params.push(normalizedStatuses)
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { ensureWorkerWalletWithClient, getWorkerWalletWithClient } from './shared.js'
|
||||
import type { CreateWorkerInput, FinanceRequestListInput, ListInput, WalletLedgerListInput, WorkerFinanceRequestRow, WorkerLevelRow, WorkerUserRow, WorkerWalletLedgerRow, WorkerWalletRow } from './types.js'
|
||||
import type {
|
||||
CreateWorkerInput,
|
||||
FinanceRequestListInput,
|
||||
ListInput,
|
||||
WalletLedgerListInput,
|
||||
WorkerFinanceRequestRow,
|
||||
WorkerLevelRow,
|
||||
WorkerUserRow,
|
||||
WorkerWalletLedgerRow,
|
||||
WorkerWalletRow,
|
||||
} from './types.js'
|
||||
import type { PoolClient } from 'pg'
|
||||
|
||||
|
||||
const WORKER_USER_SELECT = `
|
||||
SELECT
|
||||
wu.*,
|
||||
@@ -119,10 +128,9 @@ export async function getWorkerUserByUsername(username: string): Promise<WorkerU
|
||||
}
|
||||
|
||||
export async function getWorkerUserByPhone(phone: string): Promise<WorkerUserRow | null> {
|
||||
const result = await query<WorkerUserRow>(
|
||||
`${WORKER_USER_SELECT} WHERE wu.phone = $1 LIMIT 1`,
|
||||
[String(phone || '').trim()],
|
||||
)
|
||||
const result = await query<WorkerUserRow>(`${WORKER_USER_SELECT} WHERE wu.phone = $1 LIMIT 1`, [
|
||||
String(phone || '').trim(),
|
||||
])
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
@@ -136,12 +144,14 @@ export async function getWorkerUserByDisplayName(
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export async function getWorkerUserByInviteCode(
|
||||
inviteCode: string,
|
||||
): Promise<WorkerUserRow | null> {
|
||||
export async function getWorkerUserByInviteCode(inviteCode: string): Promise<WorkerUserRow | null> {
|
||||
const result = await query<WorkerUserRow>(
|
||||
`${WORKER_USER_SELECT} WHERE wu.invite_code = $1 LIMIT 1`,
|
||||
[String(inviteCode || '').trim().toUpperCase()],
|
||||
[
|
||||
String(inviteCode || '')
|
||||
.trim()
|
||||
.toUpperCase(),
|
||||
],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
@@ -827,23 +837,18 @@ export async function maybeUpgradeWorkerLevelWithClient(
|
||||
return null
|
||||
}
|
||||
|
||||
await client.query(
|
||||
'UPDATE worker_users SET level_id = $1, updated_at = $2 WHERE id = $3',
|
||||
[nextLevelId, now, workerId],
|
||||
)
|
||||
await client.query('UPDATE worker_users SET level_id = $1, updated_at = $2 WHERE id = $3', [
|
||||
nextLevelId,
|
||||
now,
|
||||
workerId,
|
||||
])
|
||||
await client.query(
|
||||
`
|
||||
INSERT INTO worker_level_logs (
|
||||
worker_id, from_level_id, to_level_id, reason, payload_json, created_at
|
||||
) VALUES ($1, $2, $3, 'auto', $4::jsonb, $5)
|
||||
`,
|
||||
[
|
||||
workerId,
|
||||
currentRow.level_id || null,
|
||||
nextLevelId,
|
||||
JSON.stringify({ acceptedCount }),
|
||||
now,
|
||||
],
|
||||
[workerId, currentRow.level_id || null, nextLevelId, JSON.stringify({ acceptedCount }), now],
|
||||
)
|
||||
return getWorkerUserByIdWithClient(client, workerId)
|
||||
}
|
||||
@@ -903,10 +908,7 @@ function buildWorkerUserWhere({
|
||||
}
|
||||
}
|
||||
|
||||
function buildWorkerWalletLedgerWhere({
|
||||
workerId = 0,
|
||||
ledgerType = '',
|
||||
}: WalletLedgerListInput) {
|
||||
function buildWorkerWalletLedgerWhere({ workerId = 0, ledgerType = '' }: WalletLedgerListInput) {
|
||||
const filters: string[] = []
|
||||
const params: unknown[] = []
|
||||
if (workerId) {
|
||||
|
||||
Reference in New Issue
Block a user