order.controller.js 4.67 KB
Newer Older
kusang96's avatar
card    
kusang96 committed
1
import mongoose from 'mongoose';
Jiwon Yoon's avatar
Jiwon Yoon committed
2
import Order from "../schemas/Order.js";
3
import User from "../schemas/User.js";
Jiwon Yoon's avatar
Jiwon Yoon committed
4
import Product from "../schemas/Product.js";
Jiwon Yoon's avatar
Jiwon Yoon committed
5
6

const addorder = async (req, res) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
7
8
9
10
    const { userId, products, receiverInfo, completeState, paymentInfo, total } = req.body
    console.log("paymentInfo=", paymentInfo)
    console.log("receiverInfo=", receiverInfo)
    // console.log(receiverInfo.bank, receiverInfo.depositor, receiverInfo.deadline)
Jiwon Yoon's avatar
Jiwon Yoon committed
11
    try {
Jiwon Yoon's avatar
Jiwon Yoon committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
        // if (!/^[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}/.test(receiverInfo.tel)) {
        //     return res.status(422).send('유효한 휴대전화번호가 아닙니다. 정확히 입력해주세요.')
        // } else if (paymentWay) {
        //     if (paymentWay == 'Remittance') {
        //         if (!(receiverInfo.bank && receiverInfo.depositor && receiverInfo.deadline)) {
        //             return res.status(422).send('선택하신 결제 수단에 관한 모든 정보를 입력해주시기 바랍니다.')
        //         }
        //         const paymentInfo = { bank: receiverInfo.bank, depositor: receiverInfo.depositor, deadline: receiverInfo.deadline }
        //         const newOrder = await new Order({ userId, products, receiverInfo, paymentWay, paymentInfo, total }).save()
        //         res.status(200).send('Order DB에 저장 완료')
        //     } else {
        //         const newOrder = await new Order({ userId, products, receiverInfo, paymentWay, total }).save()
        //         res.status(200).send('Order DB에 저장 완료')
        //     }
        // } else {
        //     return res.status(422).send('결제수단을 선택해주시기 바랍니다.')
        // }
29
30
        if (!/^[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}/.test(receiverInfo.tel)) {
            return res.status(422).send('유효한 휴대전화번호가 아닙니다. 정확히 입력해주세요.')
Jiwon Yoon's avatar
Jiwon Yoon committed
31
32
33
34
        } else if (completeState === "kakaopay") {
            const paymentInfo = { bank: "kakaopay", depositor: "none", deadline: "none" }
            const newOrder = await new Order({ userId, products, completeState, receiverInfo, paymentInfo, total }).save()
            res.status(200).send('Order DB에 저장 완료')
35
        } else {
Jiwon Yoon's avatar
Jiwon Yoon committed
36
37
            const newOrder = await new Order({ userId, products,completeState, receiverInfo, paymentInfo, total }).save()
            res.status(200).send('Order DB에 저장 완료')
38
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
39
40
41
42
43
44
    } catch (error) {
        console.log(error)
        res.status(500).send('Order DB에 저장 실패')
    }
}

45
46
47
const Ordered = async (req, res) => {
    const { db } = req.body
    try {
kusang96's avatar
kusang96 committed
48
        const ordered = await req.body.findOne({}, { _id: 0 }).select(`${db}`)
49
50
        res.json(ordered);
    } catch (error) {
Kim, Subin's avatar
정리    
Kim, Subin committed
51
        console.log(error)
52
53
54
55
        res.status(500).send('카테고리를 불러오지 못했습니다.')
    }
}

Jiwon Yoon's avatar
Jiwon Yoon committed
56
57
const showorder = async (req, res) => {
    try {
kusang96's avatar
kusang96 committed
58
        const order = await Order.find({ userId: req.userId }).sort({ _id: -1 }).limit(1).populate({
Jiwon Yoon's avatar
Jiwon Yoon committed
59
60
61
            path: 'products.productId',
            model: 'Product'
        })
62
        res.status(200).json(order[0])
Jiwon Yoon's avatar
Jiwon Yoon committed
63
64
65
66
67
68
    } catch (error) {
        console.log(error)
        res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
    }
}

69
70
71
72
73
74
75
76
77
78
79
80
81
const orderById = async (req, res, next, id) => {
    try {
        const user = await User.findById(id)
        if (!user) {
            res.status(404).send('사용자를 찾을 수 없습니다')
        }
        req.userId = user
        next()
    } catch (error) {
        console.log(error);
        res.status(500).send('사용자 아이디 검색 실패')
    }
}
Jiwon Yoon's avatar
Jiwon Yoon committed
82

kusang96's avatar
card    
kusang96 committed
83
const recommendPro = async (req, res) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
84
    const productId = req.query.products
이재연's avatar
aaaa    
이재연 committed
85
86
    try {
        const recommend = await Order.aggregate([
kusang96's avatar
card    
kusang96 committed
87
88
            {
                $match: {
Jiwon Yoon's avatar
Jiwon Yoon committed
89
                    'products.productId': mongoose.Types.ObjectId(productId)
kusang96's avatar
card    
kusang96 committed
90
91
                }
            },
Jiwon Yoon's avatar
Jiwon Yoon committed
92
            { $unwind: "$products" },
이재연's avatar
aaaa    
이재연 committed
93
            {
kusang96's avatar
card    
kusang96 committed
94
                $group: {
Jiwon Yoon's avatar
Jiwon Yoon committed
95
96
                    _id: "$products.productId",
                    count: { $sum: 1 }
이재연's avatar
aaaa    
이재연 committed
97
                }
98
99
100
101
102
103
104
105
106
107
108
            },
            { $sort: { count: -1 } },
            { $limit: 5 },
            {
                $lookup:
                {
                    from: "products",
                    localField: "_id",
                    foreignField: "_id",
                    as: "product"
                }
이재연's avatar
aaaa    
이재연 committed
109
110
            }
        ])
Jiwon Yoon's avatar
Jiwon Yoon committed
111
        const filteredRecommend = recommend.filter((el) => String(el._id) !== String(productId))
112
        res.json(filteredRecommend)
이재연's avatar
aaaa    
이재연 committed
113
    } catch (error) {
Kim, Subin's avatar
정리    
Kim, Subin committed
114
115
        console.log(error)
        res.status(404).send('추천 상품이 없습니다.')
이재연's avatar
aaaa    
이재연 committed
116
117
118
    }
}

kusang96's avatar
card    
kusang96 committed
119
export default { addorder, showorder, orderById, Ordered, recommendPro }