From ffd26d62d67edbf7e1e89db6591de4ce9dc54aeb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Qu=E1=BB=91c=20Kh=C3=A1nh?= <khanh@quocs.com>
Date: Thu, 11 Jul 2024 18:42:37 +0700
Subject: [PATCH] feat(api): [Transaction] Paginate transactions by date
 instead of createdAt

---
 apps/api/v1/routes/transactions.ts          |  8 ++++----
 apps/api/v1/services/transaction.service.ts | 11 +++++++----
 2 files changed, 11 insertions(+), 8 deletions(-)

diff --git a/apps/api/v1/routes/transactions.ts b/apps/api/v1/routes/transactions.ts
index 75a24e9e..3fcb2372 100644
--- a/apps/api/v1/routes/transactions.ts
+++ b/apps/api/v1/routes/transactions.ts
@@ -26,10 +26,10 @@ const router = new Hono()
       z.object({
         wallet_id: z.string().optional(),
         budget_id: z.string().optional(),
-        before: z.date().optional(),
-        after: z.date().optional(),
-        first: z.number().optional(),
-        last: z.number().optional(),
+        before: z.date({ coerce: true }).optional(),
+        after: z.date({ coerce: true }).optional(),
+        first: z.number({ coerce: true }).optional(),
+        last: z.number({ coerce: true }).optional(),
       }),
     ),
     async (c) => {
diff --git a/apps/api/v1/services/transaction.service.ts b/apps/api/v1/services/transaction.service.ts
index 165bdb7d..2781b74f 100644
--- a/apps/api/v1/services/transaction.service.ts
+++ b/apps/api/v1/services/transaction.service.ts
@@ -170,7 +170,7 @@ export async function listTransactions({
   const transactions = await prisma.transaction.findMany({
     where: {
       ...query,
-      createdAt: {
+      date: {
         ...(pagination.before && {
           lt: pagination.before,
         }),
@@ -180,9 +180,12 @@ export async function listTransactions({
       },
     },
     orderBy: {
-      createdAt: 'desc',
+      date: 'desc',
     },
     take: pagination.first || pagination.last,
+    include: {
+      category: true,
+    },
   })
 
   const totalCount = await prisma.transaction.count({
@@ -193,10 +196,10 @@ export async function listTransactions({
     hasMore: transactions.length > (pagination.first || pagination.last || 0),
     totalCount,
     ...(pagination.first && {
-      before: transactions[0]?.createdAt,
+      before: transactions[0]?.date,
     }),
     ...(pagination.last && {
-      after: transactions[transactions.length - 1]?.createdAt,
+      after: transactions[transactions.length - 1]?.date,
     }),
   }