order.controller.js 3.83 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) => {
7
8
9
    const { userId, products, receiverInfo, paymentWay, total } = req.body
    console.log("pay=",paymentWay)
    console.log(receiverInfo.bank , receiverInfo.depositor , receiverInfo.deadline)
Jiwon Yoon's avatar
Jiwon Yoon committed
10
    try {
11
12
        if (!/^[0-9]{2,3}-[0-9]{3,4}-[0-9]{4}/.test(receiverInfo.tel)) {
            return res.status(422).send('유효한 휴대전화번호가 아닙니다. 정확히 입력해주세요.')
13
14
15
16
17
18
19
20
21
22
23
24
25
26
        } 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('결제수단을 선택해주시기 바랍니다.')
27
        }
Jiwon Yoon's avatar
Jiwon Yoon committed
28
29
30
31
32
33
    } catch (error) {
        console.log(error)
        res.status(500).send('Order DB에 저장 실패')
    }
}

34
35
36
const Ordered = async (req, res) => {
    const { db } = req.body
    try {
kusang96's avatar
kusang96 committed
37
        const ordered = await req.body.findOne({}, { _id: 0 }).select(`${db}`)
38
39
        res.json(ordered);
    } catch (error) {
Kim, Subin's avatar
정리    
Kim, Subin committed
40
        console.log(error)
41
42
43
44
        res.status(500).send('카테고리를 불러오지 못했습니다.')
    }
}

Jiwon Yoon's avatar
Jiwon Yoon committed
45
46
const showorder = async (req, res) => {
    try {
kusang96's avatar
kusang96 committed
47
        const order = await Order.find({ userId: req.userId }).sort({ _id: -1 }).limit(1).populate({
Jiwon Yoon's avatar
Jiwon Yoon committed
48
49
50
            path: 'products.productId',
            model: 'Product'
        })
51
        res.status(200).json(order[0])
Jiwon Yoon's avatar
Jiwon Yoon committed
52
53
54
55
56
57
    } catch (error) {
        console.log(error)
        res.status(500).send('쇼핑카트를 불러오지 못했습니다.')
    }
}

58
59
60
61
62
63
64
65
66
67
68
69
70
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
71

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

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