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

atlp-rwanda / e-comm-team-emma25-bn / 4428001940

pending completion
4428001940

Pull #40

github

GitHub
Merge 950852355 into 353afa31e
Pull Request #40: Ft-addToWishlist-#184359086

28 of 130 branches covered (21.54%)

39 of 39 new or added lines in 6 files covered. (100.0%)

512 of 780 relevant lines covered (65.64%)

1.3 hits per line

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

12.84
/src/controllers/prodController.ts
1
import { Request, Response } from "express";
2
import { MulterError } from "multer";
1✔
3
import { decode } from "../helper/jwtTokenize";
1✔
4
import shortUniqueId from "short-unique-id";
1✔
5
import multipleUploader from "../middlewares/fileUploader";
1✔
6
import Images from "../db/models/Image";
1✔
7
import Product from "../db/models/Product";
1✔
8
import Wishlist from "../db/models/Wishlist";
1✔
9

10
const uids = new shortUniqueId({ length: 12 });
1✔
11
class ProductController {
1✔
12
    static async saveProduct(req: Request, res: Response) {
1✔
13
        const jwt =
×
14
            req.cookies.jwt ||
×
15
            req.body.token ||
16
            req.query.jwt ||
17
            req.cookies.token;
18
        const bToken = req.headers.authorization
×
19
            ? req.headers.authorization.split(" ")[1]
20
            : "";
21

22
        if (jwt || bToken != "") {
×
23
            const userData: any = decode(jwt || bToken);
×
24
            if (userData.role != "seller") {
×
25
                return res.status(403).json({
×
26
                    status: 403,
27
                    message: "You should login as a seller to add a product.",
28
                });
29
            }
30
            multipleUploader(req, res, async function (err) {
×
31
                if (err instanceof MulterError) {
×
32
                    res.status(400).json({ status: 400, message: err.message });
×
33
                } else if (err) {
×
34
                    return res.status(400).json({
×
35
                        status: 400,
36
                        error: "File conflicts",
37
                        message:
38
                            "Please upload only jpg, jpeg, png, webp image files.",
39
                    });
40
                }
41
                if (req.files) {
×
42
                    const ProductID: string = uids();
×
43
                    const ProductName: string = req.body.pname.replace(
×
44
                        req.body.pname[0],
45
                        req.body.pname[0].toUpperCase()
46
                    );
47
                    const ProductPrice: string = req.body.p_price;
×
48
                    const ProductOwner: string = userData.id;
×
49
                    const ProductDesc: string = req.body.desc;
×
50
                    const checkProduct = await Product.findOne({
×
51
                        where: { ProductName },
52
                        include: [Images],
53
                    });
54
                    if (checkProduct == null) {
×
55
                        try {
56
                            const prd = await Product.create({
×
57
                                ProductID,
58
                                ProductName,
59
                                ProductPrice,
60
                                ProductDesc,
61
                                ProductOwner,
62
                            });
63
                            const files = req.files;
×
64
                            const { imgs }: any = files;
×
65
                            const totalFiles = imgs.length;
×
66
                            for (let i = 0; i < totalFiles; i++) {
×
67
                                const img = imgs[i];
×
68
                                const fileType = img.mimetype;
×
69
                                const fullPath =
×
70
                                    req.protocol +
71
                                    "://" +
72
                                    req.hostname +
73
                                    "/" +
74
                                    img.destination +
75
                                    "/" +
76
                                    img.filename;
77
                                await Images.create({
×
78
                                    ImageID: uids(),
79
                                    ImagePath: fullPath,
80
                                    ImageType: fileType,
81
                                    ProductID,
82
                                });
83
                            }
84
                            const uploadedImages = await Images.findAll({
×
85
                                where: { ProductID },
86
                            });
87
                            res.status(201).json({
×
88
                                status: 201,
89
                                message: "Product image and details are saved.",
90
                                productData: prd,
91
                                ImageDetails: uploadedImages,
92
                            });
93
                        } catch (error) {
94
                            res.status(200).json({
×
95
                                status: 200,
96
                                message:
97
                                    "Product is saved with no images or other error",
98
                                error,
99
                            });
100
                        }
101
                    } else {
102
                        res.status(409).json({
×
103
                            status: 409,
104
                            message: "Product already exists",
105
                            suggests: "You can update product instead.",
106
                            existing_product: checkProduct,
107
                        });
108
                    }
109
                }
110
            });
111
        } else {
112
            return res.status(404).json({
×
113
                status: 404,
114
                message: "User token not found! try logging in.",
115
            });
116
        }
117
    }
118

119
    // PRODUCT AVAILABILITY
120
    static async updateProductAvailability(req: Request, res: Response) {
1✔
121
        try {
122
            const ProductID = req.params.product_id;
×
123
            const available = req.body.isAvailable;
×
124
            if (typeof available === "boolean") {
×
125
                res.status(400).json({
×
126
                    statusCode: 400,
127
                    message: "Use true or false for avalilable",
128
                });
129
            }
130
            const bToken = req.headers.authorization
×
131
                ? req.headers.authorization.split(" ")[1]
132
                : "";
133
            const userData: any = decode(bToken);
×
134
            const checkProduct: any = await Product.findOne({
×
135
                where: { ProductID },
136
            });
137
            if (checkProduct && userData) {
×
138
                console.log(checkProduct);
×
139
                console.log(userData);
×
140
                if (checkProduct.ProductOwner == userData.id) {
×
141
                    console.log("YOU OWN THIS PRODUCT");
×
142
                    const updatedProduct = await Product.update(
×
143
                        { available },
144
                        {
145
                            where: {
146
                                ProductID,
147
                            },
148
                        }
149
                    );
150
                    return res.status(201).json({
×
151
                        statusCode: 201,
152
                        message: "product updated successfully",
153
                        data: updatedProduct,
154
                    });
155
                } else {
156
                    return res.status(403).json({
×
157
                        statusCode: 403,
158
                        message:
159
                            "you can not authorised to update other people's products",
160
                    });
161
                }
162
            } else {
163
                return res.status(404).json({
×
164
                    statusCode: 404,
165
                    message: `product with id ${ProductID} does not exist`,
166
                });
167
            }
168
        } catch (error) {
169
            return res.json({
×
170
                statusCode: 400,
171
                message: error,
172
            });
173
        }
174
    }
175

176
    // Adding to cart
177
    static async addToWishlist(req: Request, res: Response) {
1✔
178
        const id: string = req.params.id;
×
179
        const loggedUser = req.user;
×
180
        const user_id = (loggedUser as any).id;
×
181
        // Check product existence
182
        const checkProduct = await Product.findOne({
×
183
            where: { ProductID: id },
184
            include: [Images],
185
        });
186
        if (checkProduct == null) {
×
187
            return res.status(404).json({
×
188
                status: 404,
189
                message: "Product provided does not match with any products.",
190
            });
191
        } else {
192
            // Check if the logged in user have already added this product to his/her wishlist
193
            const checkWish = await Wishlist.findOne({
×
194
                where: { ProductID: id, userId: user_id },
195
            });
196
            if (checkWish != null) {
×
197
                return res.status(409).json({
×
198
                    status: 409,
199
                    message: "The product you chose is already on your wishlist.",
200
                    product_details: checkProduct,
201
                });
202
            } else {
203
                try {
204
                    const product_name = (checkProduct as any).ProductName;
×
205
                    const addProduct = await Wishlist.create({
×
206
                        ProductID: id,
207
                        userId: user_id,
208
                    });
209
                    res.status(202)
×
210
                        .json({
211
                            status: 202,
212
                            message: `${product_name} added to your wish list`,
213
                            recently_added: checkProduct,
214
                        });
215
                } catch (err: any) {
216
                    res.status(400).json({ status: 400, message: err.message });
×
217
                }
218
            }
219
        }
220
    }
221
}
1✔
222

223
export default ProductController;
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

© 2025 Coveralls, Inc