2022-09-30 17:36:10 +08:00
|
|
|
import path from 'path';
|
|
|
|
|
|
|
|
import { InstallOptions, Plugin } from '@nocobase/server';
|
|
|
|
|
|
|
|
export class ShopPlugin extends Plugin {
|
|
|
|
timer = null;
|
|
|
|
orderReceiveExpires = 86400 * 7;
|
|
|
|
|
|
|
|
checkOrder = async () => {
|
|
|
|
const expiredDate = new Date(Date.now() - this.orderReceiveExpires);
|
|
|
|
const deliveryRepo = this.db.getRepository('deliveries');
|
|
|
|
const expiredDeliveries = await deliveryRepo.find({
|
|
|
|
fields: ['id', 'orderId'],
|
|
|
|
filter: {
|
|
|
|
status: 0,
|
|
|
|
createdAt: {
|
2023-01-03 15:17:20 +08:00
|
|
|
$lt: expiredDate,
|
|
|
|
},
|
|
|
|
},
|
2022-09-30 17:36:10 +08:00
|
|
|
});
|
|
|
|
await deliveryRepo.update({
|
|
|
|
filter: {
|
2023-01-03 15:17:20 +08:00
|
|
|
id: expiredDeliveries.map((item) => item.get('id')),
|
2022-09-30 17:36:10 +08:00
|
|
|
},
|
|
|
|
values: {
|
2023-01-03 15:17:20 +08:00
|
|
|
status: 1,
|
|
|
|
},
|
2022-09-30 17:36:10 +08:00
|
|
|
});
|
|
|
|
const orderRepo = this.db.getRepository('orders');
|
|
|
|
const [updated] = await orderRepo.update({
|
|
|
|
filter: {
|
|
|
|
status: 2,
|
2023-01-03 15:17:20 +08:00
|
|
|
id: expiredDeliveries.map((item) => item.get('orderId')),
|
2022-09-30 17:36:10 +08:00
|
|
|
},
|
|
|
|
values: {
|
2023-01-03 15:17:20 +08:00
|
|
|
status: 3,
|
|
|
|
},
|
2022-09-30 17:36:10 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
console.log('%d orders expired', updated);
|
|
|
|
};
|
|
|
|
|
|
|
|
beforeLoad() {
|
|
|
|
// TODO
|
|
|
|
}
|
|
|
|
|
|
|
|
async load() {
|
|
|
|
await this.db.import({
|
|
|
|
directory: path.resolve(__dirname, 'collections'),
|
|
|
|
});
|
|
|
|
|
|
|
|
this.db.on('orders.afterCreate', async (order, options) => {
|
|
|
|
const product = await order.getProduct({
|
2023-01-03 15:17:20 +08:00
|
|
|
transaction: options.transaction,
|
2022-09-30 17:36:10 +08:00
|
|
|
});
|
|
|
|
|
2023-01-03 15:17:20 +08:00
|
|
|
await product.update(
|
|
|
|
{
|
|
|
|
inventory: product.inventory - order.quantity,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
transaction: options.transaction,
|
|
|
|
},
|
|
|
|
);
|
2022-09-30 17:36:10 +08:00
|
|
|
});
|
|
|
|
|
|
|
|
this.app.on('beforeStart', () => {
|
|
|
|
// 每分钟执行一次
|
|
|
|
this.timer = setInterval(this.checkOrder, 1000 * 60);
|
|
|
|
});
|
|
|
|
|
|
|
|
this.app.on('beforeStop', () => {
|
|
|
|
clearInterval(this.timer);
|
|
|
|
this.timer = null;
|
|
|
|
});
|
|
|
|
|
|
|
|
this.app.acl.allow('products', '*');
|
|
|
|
this.app.acl.allow('categories', '*');
|
|
|
|
this.app.acl.allow('orders', '*');
|
|
|
|
}
|
|
|
|
|
|
|
|
async install(options: InstallOptions) {
|
|
|
|
// TODO
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default ShopPlugin;
|