Last active
September 1, 2024 13:12
-
-
Save wmakeev/250e90dc8a1e30d8978793583e079edb to your computer and use it in GitHub Desktop.
[МойСклад - Букмарклеты] #moysklad #bookmarklet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Создание внутренних заказов для пополнения остатков магазинов по проданным | |
* за последние 7 дней товарам | |
*/ | |
(async () => { | |
// Функция для отображения ошибки | |
const error = (msg) => { | |
alert(msg); | |
throw new Error(msg); | |
}; | |
try { | |
const [{ default: Moysklad }, { default: dayjs }] = await Promise.all([ | |
// Загружаем библиотеку для работы с МойСклад | |
// https://github.com/wmakeev/moysklad | |
import("https://esm.sh/[email protected]"), | |
// Загружаем библиотеку для работы с датами | |
// https://day.js.org | |
import("https://esm.sh/[email protected]"), | |
]); | |
const ms = Moysklad(); | |
/** Дата 7 дней назад */ | |
const dateFrom = new dayjs().add(-7, "days").toDate(); | |
/** Список продаж */ | |
let demands = []; | |
/** Ссылка для получения продаж */ | |
let nextHref = ms.buildUrl("entity/retaildemand", { | |
filter: { | |
applicable: true, | |
moment: { | |
$gte: dateFrom, | |
}, | |
}, | |
expand: "positions,retailStore", | |
limit: 100, | |
}); | |
while (nextHref) { | |
// Получаем продажи за последние 7 дней | |
const coll = await ms.GET(nextHref); | |
nextHref = coll.meta.nextHref; | |
demands = [...demands, ...coll.rows]; | |
} | |
// Если продажи не получены | |
if (!demands.length) { | |
throw new Error("Нет продаж"); | |
} | |
/** Продажи сгруппированные по организации */ | |
const positionsByOrgAndStore = new Map(); | |
// Группируем продажи | |
for (const demand of demands) { | |
const key = [ | |
demand.retailStore.organization.meta.href, | |
demand.retailStore.store.meta.href, | |
].join(); | |
const items = positionsByOrgAndStore.get(key); | |
if (items) { | |
items.push(...demand.positions.rows); | |
} else { | |
positionsByOrgAndStore.set(key, demand.positions.rows); | |
} | |
} | |
const newInternalOrders = []; | |
// Создаем внутренние заказы для каждой организации | |
for (const [key, positions] of positionsByOrgAndStore.entries()) { | |
const [orgHref, storeHref] = key.split(","); | |
const quantityByAssortmentMap = new Map(); | |
positions.forEach((pos) => { | |
const assortmentHref = pos.assortment.meta.href; | |
const quantity = | |
pos.quantity + (quantityByAssortmentMap.get(assortmentHref) ?? 0); | |
quantityByAssortmentMap.set(assortmentHref, quantity); | |
}); | |
const newInternalOrder = { | |
description: "Пополнение остатков магазина", | |
store: { | |
meta: { | |
type: "store", | |
href: storeHref, | |
}, | |
}, | |
organization: { | |
meta: { | |
type: "organization", | |
href: orgHref, | |
}, | |
}, | |
positions: [...quantityByAssortmentMap.entries()].map( | |
([href, quantity]) => ({ | |
assortment: { | |
meta: { | |
type: ms.parseUrl(href).path.at(-2), | |
href, | |
}, | |
}, | |
quantity, | |
}) | |
), | |
}; | |
newInternalOrders.push(newInternalOrder); | |
} | |
console.log(newInternalOrders); | |
// Создаем внутренние заказы в МойСклад | |
const results = await ms.POST("entity/internalorder", newInternalOrders); | |
alert(`Внутренние заказы созданы - ${results.length}`); | |
} catch (err) { | |
error(err); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment