• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

atlp-rwanda / e-commerce-ones-and-zeroes-bn / 7d8be62f-1191-4ca4-84de-5a4c5c76912c

23 Jul 2024 08:47PM UTC coverage: 91.503% (+1.6%) from 89.874%
7d8be62f-1191-4ca4-84de-5a4c5c76912c

push

circleci

web-flow
Merge pull request #76 from atlp-rwanda/bg-fix-crud-seller-collection

[#187355114] bg-fix  seller create collection

293 of 347 branches covered (84.44%)

Branch coverage included in aggregate %.

48 of 50 new or added lines in 2 files covered. (96.0%)

45 existing lines in 5 files now uncovered.

1010 of 1077 relevant lines covered (93.78%)

3.26 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.3
/src/controllers/orderController.ts
1
import { Request, Response } from 'express';
2
import { db } from '../database/models';
1✔
3
import { v4 as uuidv4 } from 'uuid';
1✔
4
import stripe from '../helps/stripeConfig';
1✔
5

6
class OrderController {
7
  static async createOrder(req: Request, res: Response) {
8
    try {
7✔
9
      const { productId, quantity, addressId } = req.body;
7✔
10
      if (!productId || !quantity || quantity <= 0 || !addressId) {
7✔
11
        return res
1✔
12
          .status(400)
13
          .json({ message: 'Missing or Invalid product information' });
14
      }
15
      const address = await db.Address.findByPk(addressId);
6✔
16
      if (!address) {
6✔
17
        return res.status(404).json({ message: 'No such address found' });
1✔
18
      }
19
      const product = await db.Product.findByPk(productId);
5✔
20
      if (!product) {
5✔
21
        return res.status(404).json({ message: 'No such product found' });
1✔
22
      }
23
      if (product.dataValues.quantity < quantity) {
4✔
24
        return res
1✔
25
          .status(403)
26
          .json({ message: 'Insufficient quantity in stock' });
27
      }
28

29
      const paymentIntent = await stripe.paymentIntents.create({
3✔
30
        amount: product.dataValues.price * quantity,
31
        currency: 'rwf',
32
      });
33

34
      const order = await db.Order.create({
1✔
35
        orderId: uuidv4(),
36
        userId: (req as any).user.userId,
37
        cartId: null,
38
        addressId: address.dataValues.addressId,
39
        paymentIntentId: paymentIntent.id,
40
      });
41

42
      const orderProduct = await db.OrderProduct.create({
1✔
43
        orderProductId: uuidv4(),
44
        orderId: order.dataValues.orderId,
45
        productId: product.dataValues.productId,
46
        quantity: quantity,
47
      });
48

49
      return res.status(200).json({ order, paymentIntent, orderProduct });
1✔
50
    } catch (error: any) {
51
      return res.status(500).json({ message: 'Failed to create order' });
2✔
52
    }
53
  }
54

55
  static async getOrder(req: Request, res: Response) {
56
    try {
3✔
57
      const { orderId } = req.params;
3✔
58
      const order: any = await db.Order.findOne({
3✔
59
        where: {
60
          orderId: orderId,
61
        },
62
        include: [
63
          {
64
            model: db.Product,
65
            through: {
66
              model: db.OrderProduct,
67
              attributes: ['quantity'],
68
            },
69
          },
70
        ],
71
      });
72
      if (!order) {
2✔
73
        return res.status(404).json({ message: 'No such order found' });
1✔
74
      }
75
      return res.status(200).json({ order });
1✔
76
    } catch (error: any) {
77
      return res.status(500).json({ message: 'Failed to get orders' });
1✔
78
    }
79
  }
80

81
  static async getAllUserOrders(req: Request, res: Response) {
82
    try {
3✔
83
      const { id } = req.params;
3✔
84
      const page = parseInt(req.query.page as string) || 1;
3!
85
      const pageSize = parseInt(req.query.pageSize as string) || 10; // Get pageSize from query params or default to 10
3!
86
      const offset = (page - 1) * pageSize;
3✔
87

88
      const user = await db.User.findOne({
3✔
89
        where: {
90
          userId: id,
91
        },
92
      });
93

94
      if (!user) {
3✔
95
        return res.status(404).json({ message: 'No such user found' });
1✔
96
      }
97

98
      const orders = await db.Order.findAll({
2✔
99
        where: {
100
          userId: user.userId,
101
        },
102
        offset: offset,
103
        limit: pageSize,
104
        include: [
105
          {
106
            model: db.Product,
107
            through: {
108
              model: db.OrderProduct,
109
              attributes: ['quantity'],
110
            },
111
          },
112
        ],
113
      });
114

115
      const totalOrders = await db.Order.count({
1✔
116
        where: {
117
          userId: id,
118
        },
119
      });
120

121
      const totalPages = Math.ceil(totalOrders / pageSize);
1✔
122

123
      res.status(200).json({
1✔
124
        orders,
125
        pagination: {
126
          currentPage: page,
127
          pageSize: pageSize,
128
          totalPages: totalPages,
129
          totalOrders: totalOrders,
130
        },
131
      });
132
    } catch (err: any) {
133
      return res.status(500).json({ message: 'Failed to get all user orders' });
1✔
134
    }
135
  }
136

137
  static async getAllOrders(req: Request, res: Response) {
138
    try {
2✔
139
      const page = parseInt(req.query.page as string) || 1;
2!
140
      const pageSize = parseInt(req.query.pageSize as string) || 10;
2!
141
      const offset = (page - 1) * pageSize;
2✔
142
      const orders = await db.Order.findAll({
2✔
143
        offset: offset,
144
        limit: pageSize,
145
      });
146
      const totalOrders: number = await db.Order.count();
1✔
147
      res.status(200).json({
1✔
148
        orders,
149
        pagination: {
150
          currentPage: page,
151
          pageSize: pageSize,
152
          totalPages: Math.ceil(totalOrders / pageSize),
153
          totalOrders: totalOrders,
154
        },
155
      });
156
    } catch (err: any) {
157
      return res.status(500).json({ message: 'Failed to get all orders' });
1✔
158
    }
159
  }
160

161
  static async confirmOrderPayment(req: Request, res: Response) {
162
    try {
4✔
163
      const { orderId } = req.params;
4✔
164
      const order: any = await db.Order.findOne({
4✔
165
        where: {
166
          orderId: orderId,
167
        },
168
        include: [
169
          {
170
            model: db.Product,
171
            through: {
172
              model: db.OrderProduct,
173
              attributes: ['quantity'],
174
            },
175
          },
176
        ],
177
      });
178
      if (!order) {
3✔
179
        return res.status(404).json({ message: 'No such order found' });
1✔
180
      }
181
      const paymentIntent = await stripe.paymentIntents.retrieve(
2✔
182
        order.dataValues.paymentIntentId,
183
      );
184
      if (!paymentIntent) {
2✔
185
        return res.status(404).json({ message: 'No such paymentIntent found' });
1✔
186
      }
187
      if (paymentIntent.status !== 'succeeded') {
1!
UNCOV
188
        return res.status(403).json({ message: 'Order was not paid for' });
×
189
      }
190

191
      //check if order is associated with a cart
192
      if (order.dataValues.cartId) {
1✔
193
        //clear the cart after checkout
194
        const cart = await db.Cart.findByPk(order.dataValues.cartId);
1✔
195
        if (!cart) {
1!
UNCOV
196
          return res.status(404).json({ message: 'No such cart found' });
×
197
        }
198
        await db.CartProduct.destroy({
1✔
199
          where: {
200
            cartId: cart.dataValues.cartId,
201
          },
202
        });
203
      }
204
      order.dataValues.Products.forEach((product: any) => {
1✔
205
        product.decrement('quantity', {
1✔
206
          by: product.dataValues.OrderProduct.dataValues.quantity,
207
        });
208
      });
209
      order.update({ paid: true });
1✔
210

211
      return res.status(200).json({ message: 'Order was successfully paid' });
1✔
212
    } catch (error: any) {
213
      return res.status(500).json({ message: 'Failed to confirm payment' });
1✔
214
    }
215
  }
216
}
217

218
export default OrderController;
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc