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 {
|
|
|
|
|
const db = getDB();
|
|
|
|
|
const query = `
|
|
|
|
|
SELECT * FROM coupon_products where remain > 0
|
|
|
|
|
`
|
|
|
|
|
const [coupon] = await db.query(query);
|
|
|
|
|
|
|
|
|
|
if (coupon.length === 0) {
|
|
|
|
|
res.json({ error: '暂无优惠券' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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 userId = req.params.id;
|
2025-10-11 17:33:00 +08:00
|
|
|
const couponId = req.body.coupon_id;
|
2025-10-09 17:26:34 +08:00
|
|
|
const db = getDB();
|
|
|
|
|
const query = `
|
|
|
|
|
SELECT * FROM coupon_products where remain > 0
|
|
|
|
|
`
|
|
|
|
|
const [coupon] = await db.query(query);
|
|
|
|
|
|
|
|
|
|
if (coupon.length === 0) {
|
|
|
|
|
return res.status(404).json({ error: '暂无优惠券' });
|
|
|
|
|
} else {
|
|
|
|
|
const query = [`
|
2025-10-11 17:33:00 +08:00
|
|
|
select * from coupon_use where user_id = ?
|
2025-10-09 17:26:34 +08:00
|
|
|
`,`
|
2025-10-11 17:33:00 +08:00
|
|
|
update coupon_products set remain = remain - 1 where id = ?
|
|
|
|
|
`,`
|
|
|
|
|
insert into coupon_use (user_id, coupon_id, get_time) values (?, ?, now())
|
2025-10-09 17:26:34 +08:00
|
|
|
`]
|
2025-10-11 17:33:00 +08:00
|
|
|
const [checkUser] = await db.query(query[0], [userId]);
|
|
|
|
|
console.log("12345",checkUser)
|
|
|
|
|
for (const item of checkUser) {
|
|
|
|
|
if (item.coupon_id === coupon[0].id && item.use_time === null) {
|
|
|
|
|
return res.status(400).json({ error: '优惠券已领取' });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
await db.query(query[1], [coupon[0].id]);
|
|
|
|
|
await db.query(query[2], [userId, coupon[0].id]);
|
2025-10-09 17:26:34 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
res.json({coupon, success: true});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
res.status(500).json({ error: '获取优惠券失败' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
module.exports = router;
|