import { formscreen } from "./formscreen"; import { database } from "./database.js"; import { autocomplete_database } from "./autocomplete_database.js"; import { import_loop } from "./import_loop.js"; import { searcher } from "./searcher.js"; import { import_log } from "./import_log.js"; import { downloader } from "./downloader.js"; export class import_products extends formscreen { #file; #content; get _name() { return "Import products JSON"; } _build_form() { this._create_input("file", "Database:", "", (input) => { this.#file = input; input.type = "file"; input.accept = "application/json"; }); } async #load_file() { if (this.#file.files.length === 0) { throw new Error("Select JSON products database first."); } const file = this.#file.files.item(0); const text = await file.text(); return JSON.parse(text); } async _process() { try { this._info = "Loading file..."; this.#content = await this.#load_file(); this._info = "Parsing file to dataset..."; const result = new import_log(); const dataset = new database(this.#content) .on_skip((fail) => { this._info = "Skipping " + fail.product.barcode + "..."; result.skip(fail); }) .process() .results(); const loop = new import_loop(dataset) .on_autocomplete((target) => { this._info = "Searching for " + target.barcode + "..."; }) .on_create((target) => { this._info = "Creating " + target.barcode + "..."; }) .on_single_fail((target) => { this._info = "Can not add " + target.product.barcode + "..."; result.fail(target); }) .on_skip((target) => { this._info = "Skipping " + target.product.barcode + "..."; result.skip(target); }) .on_single_success((target) => { this._info = "Created " + target.barcode + " success."; }) .finally(() => { searcher.reload(); const log = new downloader() .content(result.content()) .type("text/plain") .encode("utf-8") .name("import-json.log") .process(); if (result.length === 0) { this._success = "All items imported."; setTimeout(() => { this.hide(); }); } else { this._success = "Not all items imported..."; } }) .process(); } catch (error) { this._error = new String(error); } } }