// define a single task in a file import { Task, api, task } from "actionhero"; import moment from 'moment' export class ExportCron extends Task { constructor() { super(); this.name = "exportCron"; this.description = "I export a specific retail invoice for a shopify order"; this.frequency = 1000 * 10; this.queue = "cron"; this.middleware = []; } async run(data) { const shops = await api.shopSettings.getInstalledShops(); for(var i = 0; i < shops.length; i++){ const { shop } = shops[i]; const auth = await api.shopifyShops.getShop(shop); if(auth){ await this.processShopOrderExports(shop); await this.processShopOrderUpdates(shop); await this.processShopStock(shop); }else{ api.log(`Shop ${shop} installed but missing valid token`,"error"); } } return true; } async processShopOrderExports(shop){ api.log(`${shop}: processing Order Exports`); const LOG_TYPE = "order-export" const where = { type : LOG_TYPE } const logs = await api.exportLogs.cron.list(shop, where, 1); let since = logs.rows.length ? logs.rows[0].createdAt : null; const interval = await api.shopSettings.getValue(shop, "exportInterval"); let diff; if(since){ diff = moment().diff(since, "minutes"); } //overlap interval twice const orderParams = since ? {created_at_min: moment(since).subtract(interval * 2, "minutes").format()} : {} if(!since || diff > interval){ let log = await api.exportLogs.cron.createLog({ type: LOG_TYPE, shop: shop, status: "started" }); const orders = await api.exportOrders.getOrders(shop, orderParams); var exportedOrderCount = 0; for(var i = 0; i < orders.length; i++){ const order = orders[i]; const {tags} = order; if(tags.indexOf("EZRent:exported") < 0){ await task.enqueue( "exportOrder", { order: order, shop: shop, exportType: "reservation"}, "default" ); await task.enqueue( "exportOrder", { order: order, shop: shop, exportType: "invoice"}, "default" ); exportedOrderCount ++; } } log.message = `Exported ${exportedOrderCount} of ${orders.length} orders`; log.save(); } } async processShopOrderUpdates(shop){ api.log(`${shop}: Not processing Order Updates`); } async processShopStock(shop){ api.log(`${shop}: processing Stock`); const files = await api.imports.checkImports(shop); for(var i = 0; i < files.length; i++){ const file = files[i]; // TODO: check if file is stock... if (file.indexOf(".xml") > -1) { await task.enqueue( "importStockFile", { file: file, shop: shop }, "default" ); } } } }