11import Purchase from '../Models/purchasesModel.js' ;
22import StripePaymentProvider from '../helpers/stripe.js' ;
3+ import { NotFoundError } from '../helpers/errorHandler.js' ;
34const paymentProvider = new StripePaymentProvider ( ) ;
45
56const purchaseService = {
@@ -12,23 +13,42 @@ const purchaseService = {
1213 processPayment,
1314} ;
1415
16+ async function findPurchaseById ( id ) {
17+ const purchase = await Purchase . findById ( id ) ;
18+ if ( purchase ) {
19+ return purchase ;
20+ } else {
21+ throw new NotFoundError ( `Purchase with id ${ id } Not found` ) ;
22+ }
23+ }
24+
1525async function createPurchase ( userId , cartId , amount , shippingAddress ) {
1626 const purchase = new Purchase ( {
1727 userId,
1828 cartId,
1929 amount,
2030 shippingAddress,
2131 } ) ;
22-
32+
2333 return await purchase . save ( ) ;
2434}
2535
2636async function getAllPurchase ( page , size ) {
2737 // get a pagination with purchases instead all purchases
28- const pageNumber = parseInt ( page ) || 1 ;
29- const pageSize = parseInt ( size ) || 10 ;
30- const skipCount = ( pageNumber - 1 ) * pageSize ;
31- return await Purchase . find ( ) . skip ( skipCount ) . limit ( pageSize ) ;
38+ const actualPage = parseInt ( page ) || 1 ;
39+ const pageSize = parseInt ( size ) || 8 ;
40+ const skipCount = ( actualPage - 1 ) * pageSize ;
41+
42+ const totalCount = await Purchase . countDocuments ( ) ;
43+ const totalPages = Math . ceil ( totalCount / pageSize ) ;
44+
45+ const products = await Purchase . aggregate ( [
46+ { $sample : { size : totalCount } } ,
47+ { $skip : skipCount } ,
48+ { $limit : pageSize } ,
49+ ] ) ;
50+
51+ return { products, totalPages } ;
3252}
3353
3454async function getUserPurchase ( id ) {
@@ -60,17 +80,20 @@ async function getMonthly() {
6080}
6181
6282async function cleanPurchase ( id ) {
83+ await findPurchaseById ( id ) ;
6384 return await Purchase . findByIdAndDelete ( id ) ;
6485}
6586
6687async function updatePurchaseState ( id , status ) {
88+ await findPurchaseById ( id ) ;
6789 const newStatus = await Purchase . findOneAndUpdate (
6890 {
69- purchaseId : id ,
91+ _id : id ,
7092 } ,
7193 { shippingStatus : status } ,
7294 { new : true } ,
7395 ) ;
96+ console . log ( newStatus ) ;
7497 return newStatus ;
7598}
7699
0 commit comments