70 lines
2.1 KiB
TypeScript
70 lines
2.1 KiB
TypeScript
import { router, protectedProcedure } from '@/src/trpc/trpc-index';
|
|
import { z } from 'zod';
|
|
import { db } from '@/src/db/db_index';
|
|
import { complaints } from '@/src/db/schema';
|
|
import { eq } from 'drizzle-orm';
|
|
import { scaffoldAssetUrl, claimUploadUrl } from '@/src/lib/s3-client';
|
|
|
|
export const complaintRouter = router({
|
|
getAll: protectedProcedure
|
|
.query(async ({ ctx }) => {
|
|
const userId = ctx.user.userId;
|
|
|
|
const userComplaints = await db
|
|
.select({
|
|
id: complaints.id,
|
|
complaintBody: complaints.complaintBody,
|
|
response: complaints.response,
|
|
isResolved: complaints.isResolved,
|
|
createdAt: complaints.createdAt,
|
|
orderId: complaints.orderId,
|
|
images: complaints.images,
|
|
})
|
|
.from(complaints)
|
|
.where(eq(complaints.userId, userId))
|
|
.orderBy(complaints.createdAt);
|
|
|
|
return {
|
|
complaints: userComplaints.map(c => ({
|
|
id: c.id,
|
|
complaintBody: c.complaintBody,
|
|
response: c.response,
|
|
isResolved: c.isResolved,
|
|
createdAt: c.createdAt,
|
|
orderId: c.orderId,
|
|
images: c.images ? scaffoldAssetUrl(c.images as string[]) : [],
|
|
})),
|
|
};
|
|
}),
|
|
|
|
raise: protectedProcedure
|
|
.input(z.object({
|
|
orderId: z.number().optional(),
|
|
complaintBody: z.string().min(1, 'Complaint body is required'),
|
|
imageKeys: z.array(z.string()).optional(),
|
|
}))
|
|
.mutation(async ({ input, ctx }) => {
|
|
const userId = ctx.user.userId;
|
|
const { orderId, complaintBody, imageKeys } = input;
|
|
|
|
await db.insert(complaints).values({
|
|
userId,
|
|
orderId: orderId || null,
|
|
complaintBody: complaintBody.trim(),
|
|
images: imageKeys || [],
|
|
});
|
|
|
|
// Claim upload URLs for images
|
|
if (imageKeys && imageKeys.length > 0) {
|
|
for (const key of imageKeys) {
|
|
try {
|
|
await claimUploadUrl(key);
|
|
} catch (e) {
|
|
console.warn(`Failed to claim upload URL for key: ${key}`, e);
|
|
}
|
|
}
|
|
}
|
|
|
|
return { success: true, message: 'Complaint raised successfully' };
|
|
}),
|
|
});
|