Commit 5ac648ae by yexing

月度表优化

parent 23967a5e
3.4.6
\ No newline at end of file
3.4.8
\ No newline at end of file
No preview for this file type
......@@ -19581,72 +19581,6 @@
dayjs.extend(isSameOrBefore);
const CST = "Asia/Shanghai";
class Plan {
constructor(dt, params) {
this.dt = dayjs.tz(dt ?? new Date(), CST);
this.setHandler();
this.table = new Proxy({}, this.handler);
this.params = [];
params?.forEach(param => this._addParam(...param));
}
setHandler() {
this.handler = {
dt: this.dt,
order: [], // 逆序
get(obj, prop) {
if (prop in obj) return obj[prop];
const idx = this.order.find(x => prop - x >= 0);
return obj[idx];
},
set(obj, prop, value) {
const result = Reflect.set(...arguments);
this.order = Object.keys(obj).sort((a, b) => b - a);
let [x1, x2] = value.period, dt = this.dt;
if (this.dt.date() < parseInt(x2) || x2 === 0) {
dt = this.dt.subtract(1, "month");
}
let year = dt.year();
let month = dt.month() + 1;
x2 = x2 === 0 ? dt.daysInMonth() : x2;
month = (month + '').padStart(2, "0");
value.period = [
`${year}-${month}-${x1}`,
`${year}-${month}-${x2}`
];
return result;
}
};
}
get(day = null) {
const it = day ? this.table[day] : this.table[this.dt.date()];
return it?.period;
}
next() {
let dt = this.dt;
const order = this.handler.order;
const idx = (
order.indexOf(this.get().dt.date() + '') - 1 + order.length // 向上
) % order.length;
if (idx == order.length - 1) {
dt = dt.add(1, "month");
}
let year = dt.year();
let month = dt.month();
dt = this.table[order[idx]].dt
.set("year", year)
.set("month", month);
return new Plan(dt, this.params);
}
_addParam(execTime, period) {
// MM-dd HH:mm:ss
const dt = dayjs.tz(new Date(), CST)
.set("date", +execTime.substring(0, 2))
.set("hour", +execTime.substring(3, 5));
this.table[dt.date()] = { period, dt };
this.params.push(arguments);
}
}
const makeLogEntry = (message) => {
return {
time: dayjs.tz(new Date(), CST).format("HH:mm:ss"),
......@@ -19703,46 +19637,6 @@
}
}
const hour = 17;
const p1 = [
[`11 ${hour}:`, ["01", "10"]],
[`21 ${hour}:`, ['11', '20']],
[`01 ${hour}:`, ['21', 0]],
[`05 00:`, ['01', 0]]
];
// const p2 = [
// [`11 ${hour}:`, ["01", "10"]],
// [`21 ${hour}:`, ['11', '20']],
// [`05 00:`, ['01', 0]]
// ];
const TABLE = {
WFS: {
name: "WFS",
uri: "https://seller.walmart.com/aurora/v1/wfs/reports/",
params: p1
},
PAYMENT: {
name: "放款表",
uri: "https://seller.walmart.com/aurora/v1/",
params: p1
},
GQL: {
name: "营销表",
uri: "https://seller.walmart.com/aurora/v2/marketing-self-serve/gql",
params: p1
},
ORDER: {
name: "订单表",
uri: "https://seller.walmart.com/aurora/v1/reports/",
params: p1
},
ADVERT: {
name: "广告表",
uri: "https://advertising.walmart.com/sp/api/",
params: p1
}
};
const checkURL = (u1, u2) => {
if (!u1 || !u2) return false;
return u1.startsWith(new URL(u2).origin) && !u1.includes("signin");
......@@ -19863,35 +19757,5 @@
}
}, 1000);
}
chrome.alarms.onAlarm.addListener((alarm) => {
let [key, fromDate, toDate, when] = alarm.name.split('_');
if (!Object.keys(TABLE).includes(key)) return;
const { uri, params } = TABLE[key];
const plan = new Plan(null, params);
const period = !fromDate || !toDate ? plan.get() : [fromDate, toDate];
if (!when) {
when = plan.next().dt.valueOf();
chrome.alarms.create(alarm.name, { when });
console.log(`[timedTask] uri: ${uri} period: ${period} when: ${when}`);
}
startTask();
sendTabMsg({ type: "run", data: { uri, period } });
});
// 初始化
// initTimedTask();
// chrome.storage.local.get(null, console.log);
// chrome.storage.local.clear();
// chrome.alarms.getAll(console.log);
chrome.alarms.clearAll();
globalThis.initTmpTimedTask = (when) => {
const period = ['2025-02-01', '2025-02-28'];
for (const [key, { uri }] of Object.entries(TABLE)) {
const name = [key, ...period, when].join('_');
chrome.alarms.create(name, { when });
console.log(`[timedTask] uri: ${uri} period: ${period} when: ${when}`);
}
};
// globalThis.initTmpTimedTask(getTmpClock());
// initTmpTimedTask(new Date().getTime() + 10)
})();
......@@ -456,7 +456,7 @@
[`11 ${hour}:`, ["01", "10"]],
[`21 ${hour}:`, ['11', '20']],
[`01 ${hour}:`, ['21', 0]],
[`05 00:`, ['01', 0]]
[`05 00:`, ['01', 0], true]
];
// const p2 = [
// [`11 ${hour}:`, ["01", "10"]],
......@@ -616,7 +616,7 @@
return null;
};
const gqlCallback = async function (response) {
const uri = this.uri, method = "POST", body = this.options.body, headers = this.options.headers, [fromDate, toDate] = this.options.period;
const uri = this.uri, method = "POST", { body, headers, fromDate, toDate } = this.options;
async function getID(json) {
const { campaignReports = null, pagination = null } = json.data.get_coop_campaigns;
if (!campaignReports?.length) {
......@@ -792,7 +792,8 @@
...bodyArgs,
},
// noLowerCase: true,
callback: advertCallback
callback: advertCallback,
isMmonthly: options.isMmonthly,
}
};
......@@ -862,12 +863,11 @@
}
);
};
async function createTasks(uri, period) {
async function createTasks(uri, fromDate, toDate) {
if (!uri.startsWith(location.origin)) {
return [];
}
uri = uri || TABLE.WFS.uri;
let [fromDate, toDate] = period || [fmt0(new Date(), -10), fmt0(new Date(), -1)];
Task.partnerId = sessionStorage.getItem('partnerId');
Task.uri = uri; // 不适用于异步
if (fromDate && toDate) {
......@@ -1010,7 +1010,8 @@
method: "POST",
ext: "json",
body,
period,
fromDate,
toDate,
headers: rrHeaders(),
callback: gqlCallback,
next: true,
......@@ -1041,7 +1042,7 @@
attributionWindow: "days3",
extraFields: ["noDate"],
},
{ initialState }
{ initialState, isMmonthly: true }
),
createAdvertTask(
"Placement Performance",
......@@ -1052,7 +1053,7 @@
attributionWindow: "days3",
extraFields: ["noDate"],
},
{ initialState }
{ initialState, isMmonthly: true }
),
createAdvertTask(
"Item Keyword Performance",
......@@ -1063,7 +1064,7 @@
attributionWindow: "days3",
extraFields: ["noDate"],
},
{ initialState }
{ initialState, isMmonthly: true }
),
createAdvertTask(
"Item Performance",
......@@ -1084,6 +1085,7 @@
{
request: "/v1/snapshot/recommendations",
initialState,
isMmonthly: true
}
),
];
......@@ -1103,7 +1105,7 @@
fromDate,
toDate,
},
{ ext: "json" }
{ ext: "json", isMmonthly: true }
),
new Task(
{
......@@ -1115,7 +1117,7 @@
toDate,
type: "MCS",
},
{ ext: "json" }
{ ext: "json", isMmonthly: true }
),
new TaskGroup(
......@@ -1153,7 +1155,8 @@
{
fromDate,
toDate,
}
},
{ isMmonthly: true }
),
new Task(
{
......@@ -1164,7 +1167,8 @@
fromDate,
toDate,
gtin: "",
}
},
{ isMmonthly: true }
),
new Task(
{
......@@ -1194,7 +1198,8 @@
{
startDate: fromDate,
endDate: toDate,
}
},
{ isMmonthly: true }
),
new Task(
......@@ -1213,7 +1218,7 @@
{
reportType: "multichannel",
},
{ callback: inventoryHealthCallback }
{ callback: inventoryHealthCallback, isMmonthly: true }
),
];
}
......@@ -1280,10 +1285,11 @@
).click();
}
}async function run(options = {}) {
const { uri, period, sn } = options;
const [fromDate, toDate] = period || [fmt0(new Date(), -10), fmt0(new Date(), -1)];
const { uri, plan, sn } = options;
plan.period ||= [fmt0(new Date(), -10), fmt0(new Date(), -1)];
const [fromDate, toDate] = plan.period;
const [key, { name }] = Object.entries(TABLE).find((item) => item[1].uri === uri);
let tasks = await createTasks(uri, period);
let tasks = await createTasks(uri, fromDate, toDate);
tasks = sn ? [tasks.at(sn)] : tasks;
// 在季度周期过滤掉月度任务
// tasks = tasks.filter((x)=>!x.isMonthly);
......@@ -1292,10 +1298,15 @@
for (const task of tasks) {
const pf = `${++idx}/${len}`;
addLog(`${name} 运行中 ${pf}`);
if ((task?.options || task?.task0.options || {}).isMmonthly && !plan.isMmonthly) {
console.log(`${pf} skip1`);
continue;
}
console.log(`${pf} start: ${JSON.stringify(task)}`);
let data = await task.send();
if (data === true || data === false) {
continue;
console.log(`${pf} skip2`);
continue;
}
let fn = task.getFileName();
......
......@@ -6,7 +6,7 @@
[`11 ${hour}:`, ["01", "10"]],
[`21 ${hour}:`, ['11', '20']],
[`01 ${hour}:`, ['21', 0]],
[`05 00:`, ['01', 0]]
[`05 00:`, ['01', 0], true]
];
// const p2 = [
// [`11 ${hour}:`, ["01", "10"]],
......@@ -180,8 +180,7 @@
};
}
get(day = null) {
const it = day ? this.table[day] : this.table[this.dt.date()];
return it?.period;
return (day ? this.table[day] : this.table[this.dt.date()]) ?? {};
}
next() {
let dt = this.dt;
......@@ -199,12 +198,12 @@
.set("month", month);
return new Plan(dt, this.params);
}
_addParam(execTime, period) {
_addParam(execTime, period, isMmonthly = false) {
// MM-dd HH:mm:ss
const dt = dayjs.tz(new Date(), CST)
.set("date", +execTime.substring(0, 2))
.set("hour", +execTime.substring(3, 5));
this.table[dt.date()] = { period, dt };
this.table[dt.date()] = { period, dt, isMmonthly };
this.params.push(arguments);
}
}
......@@ -252,20 +251,20 @@
// const period = [fromInput.value, toInput.value];
// const period = ['2025-01-01', '2025-02-01'];
const period = new Plan(null, params).get();
if (period === undefined) {
const plan = new Plan(null, params).get();
if (plan.period === undefined) {
addLog(`${name} 未到指定时间`, true);
return;
}
// Deprecated
const diff = getTimeDiff(period[1], 1);
const diff = getTimeDiff(plan.period[1], 1);
if (-12 < diff && diff < 0) {
const select = confirm("时间未到, 是否确认继续");
if (!select) return;
}
chrome.storage.local.get(['isRunning'], ({ isRunning }) => {
if (!isRunning) {
chrome.runtime.sendMessage({ type: "run", data: { period, uri } });
chrome.runtime.sendMessage({ type: "run", data: { plan, uri } });
}
});
});
......
{"name":"WalmartExports","description":"导出沃尔玛报表","version":"3.4.6","manifest_version":3,"background":{"service_worker":"./js/background.js"},"permissions":["tabs","activeTab","scripting","notifications","storage","alarms"],"action":{"default_title":"WalmartExports","default_popup":"popup.html","default_icon":{"16":"icon.png","32":"icon.png","48":"icon.png","128":"icon.png"}},"icons":{"16":"icon.png","32":"icon.png","48":"icon.png","128":"icon.png"},"web_accessible_resources":[{"resources":["src/main.js"],"matches":["<all_urls>"]}],"host_permissions":["https://seller.walmart.com/*","https://advertising.walmart.com/*","https://login.account.wal-mart.com/*","https://marketplace.walmartapis.com/*","https://walmart.meinuosha.com/*"],"content_scripts":[{"matches":["https://seller.walmart.com/*","https://advertising.walmart.com/*","https://login.account.wal-mart.com/*","https://marketplace.walmartapis.com/*","https://walmart.meinuosha.com/*"],"js":["./js/main.js"]}]}
\ No newline at end of file
{"name":"WalmartExports","description":"导出沃尔玛报表","version":"3.4.8","manifest_version":3,"background":{"service_worker":"./js/background.js"},"permissions":["tabs","activeTab","scripting","notifications","storage","alarms"],"action":{"default_title":"WalmartExports","default_popup":"popup.html","default_icon":{"16":"icon.png","32":"icon.png","48":"icon.png","128":"icon.png"}},"icons":{"16":"icon.png","32":"icon.png","48":"icon.png","128":"icon.png"},"web_accessible_resources":[{"resources":["src/main.js"],"matches":["<all_urls>"]}],"host_permissions":["https://seller.walmart.com/*","https://advertising.walmart.com/*","https://login.account.wal-mart.com/*","https://marketplace.walmartapis.com/*","https://walmart.meinuosha.com/*"],"content_scripts":[{"matches":["https://seller.walmart.com/*","https://advertising.walmart.com/*","https://login.account.wal-mart.com/*","https://marketplace.walmartapis.com/*","https://walmart.meinuosha.com/*"],"js":["./js/main.js"]}]}
\ No newline at end of file
......@@ -30,7 +30,7 @@ async function run(options = {}) {
for (const task of tasks) {
const pf = `${++idx}/${len}`;
addLog(`${name} 运行中 ${pf}`);
if (task.options.isMmonthly && !plan.isMmonthly) {
if ((task?.options || task?.task0.options || {}).isMmonthly && !plan.isMmonthly) {
console.log(`${pf} skip1`);
continue;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment