2025-10-09 17:26:34 +08:00
|
|
|
const express = require('express');
|
|
|
|
|
const router = express.Router();
|
|
|
|
|
const { getDB } = require('../database');
|
|
|
|
|
|
|
|
|
|
|
2025-10-11 17:33:00 +08:00
|
|
|
router.get('/', async (req, res) => {
|
2025-10-09 17:26:34 +08:00
|
|
|
try {
|
2025-10-13 17:28:29 +08:00
|
|
|
const useId = req.query.user_id;
|
2025-10-09 17:26:34 +08:00
|
|
|
const db = getDB();
|
|
|
|
|
const query = `
|
2025-10-13 17:28:29 +08:00
|
|
|
SELECT * FROM coupon_products
|
2025-10-09 17:26:34 +08:00
|
|
|
`
|
|
|
|
|
const [coupon] = await db.query(query);
|
|
|
|
|
|
|
|
|
|
if (coupon.length === 0) {
|
2025-10-13 17:28:29 +08:00
|
|
|
res.json({ message: '暂无优惠券' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for(const item of coupon) {
|
|
|
|
|
const query = `
|
|
|
|
|
SELECT * FROM coupon_use WHERE user_id = ? AND coupon_id = ?
|
|
|
|
|
`
|
|
|
|
|
const [couponExist] = await db.query(query, [useId, item.id]);
|
|
|
|
|
if (couponExist.length === 0) {
|
|
|
|
|
item.got = false;
|
|
|
|
|
} else {
|
|
|
|
|
item.got = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-10-09 17:26:34 +08:00
|
|
|
|
|
|
|
|
res.json({coupon, success: true});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
res.status(500).json({ error: '获取优惠券失败' });
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-10-11 17:33:00 +08:00
|
|
|
router.get('/:id', async (req, res) => {
|
2025-10-09 17:26:34 +08:00
|
|
|
try {
|
|
|
|
|
const db = getDB();
|
2025-10-13 17:28:29 +08:00
|
|
|
|
|
|
|
|
const userId = req.params.id;
|
|
|
|
|
const receiveCouponId = req.query.coupon_id;
|
|
|
|
|
|
2025-10-09 17:26:34 +08:00
|
|
|
const query = `
|
2025-10-13 17:28:29 +08:00
|
|
|
SELECT * FROM coupon_use WHERE user_id = ? AND coupon_id = ?
|
2025-10-09 17:26:34 +08:00
|
|
|
`
|
2025-10-13 17:28:29 +08:00
|
|
|
const [couponExist] = await db.query(query, [userId, receiveCouponId]);
|
|
|
|
|
|
|
|
|
|
if (couponExist.length === 0) {
|
|
|
|
|
|
|
|
|
|
const insertQuery = `
|
|
|
|
|
INSERT INTO coupon_use (user_id, coupon_id, get_time) VALUES (?, ?, now())
|
|
|
|
|
`
|
|
|
|
|
await db.query(insertQuery, [userId, receiveCouponId]);
|
|
|
|
|
|
|
|
|
|
const updateQuery = `
|
|
|
|
|
UPDATE coupon_products SET remain = remain - 1 WHERE id = ?
|
|
|
|
|
`
|
|
|
|
|
await db.query(updateQuery, [receiveCouponId]);
|
2025-10-09 17:26:34 +08:00
|
|
|
|
|
|
|
|
} else {
|
2025-10-13 17:28:29 +08:00
|
|
|
return res.status(500).json({ error: '已有该优惠券' });
|
2025-10-09 17:26:34 +08:00
|
|
|
}
|
|
|
|
|
|
2025-10-13 17:28:29 +08:00
|
|
|
res.json({success: true});
|
2025-10-09 17:26:34 +08:00
|
|
|
} catch (error) {
|
2025-10-13 17:28:29 +08:00
|
|
|
console.log(error);
|
2025-10-09 17:26:34 +08:00
|
|
|
res.status(500).json({ error: '获取优惠券失败' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
module.exports = router;
|