import_products.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { formscreen } from "./formscreen";
  2. import { database } from "./database.js";
  3. import { autocomplete_database } from "./autocomplete_database.js";
  4. import { import_loop } from "./import_loop.js";
  5. import { searcher } from "./searcher.js";
  6. import { import_log } from "./import_log.js";
  7. import { downloader } from "./downloader.js";
  8. export class import_products extends formscreen {
  9. #file;
  10. #content;
  11. get _name() {
  12. return "Import products JSON";
  13. }
  14. _build_form() {
  15. this._create_input("file", "Database:", "", (input) => {
  16. this.#file = input;
  17. input.type = "file";
  18. input.accept = "application/json";
  19. });
  20. }
  21. async #load_file() {
  22. if (this.#file.files.length === 0) {
  23. throw new Error("Select JSON products database first.");
  24. }
  25. const file = this.#file.files.item(0);
  26. const text = await file.text();
  27. return JSON.parse(text);
  28. }
  29. async _process() {
  30. try {
  31. this._info = "Loading file...";
  32. this.#content = await this.#load_file();
  33. this._info = "Parsing file to dataset...";
  34. const result = new import_log();
  35. const dataset = new database(this.#content)
  36. .on_skip((fail) => {
  37. this._info = "Skipping " + fail.product.barcode + "...";
  38. result.skip(fail);
  39. })
  40. .process()
  41. .results();
  42. const loop = new import_loop(dataset)
  43. .on_autocomplete((target) => {
  44. this._info = "Searching for " + target.barcode + "...";
  45. })
  46. .on_create((target) => {
  47. this._info = "Creating " + target.barcode + "...";
  48. })
  49. .on_single_fail((target) => {
  50. this._info = "Can not add " + target.product.barcode + "...";
  51. result.fail(target);
  52. })
  53. .on_skip((target) => {
  54. this._info = "Skipping " + target.product.barcode + "...";
  55. result.skip(target);
  56. })
  57. .on_single_success((target) => {
  58. this._info = "Created " + target.barcode + " success.";
  59. })
  60. .finally(() => {
  61. searcher.reload();
  62. const log = new downloader()
  63. .content(result.content())
  64. .type("text/plain")
  65. .encode("utf-8")
  66. .name("import-json.log")
  67. .process();
  68. if (result.length === 0) {
  69. this._success = "All items imported.";
  70. setTimeout(() => {
  71. this.hide();
  72. });
  73. } else {
  74. this._success = "Not all items imported...";
  75. }
  76. })
  77. .process();
  78. } catch (error) {
  79. this._error = new String(error);
  80. }
  81. }
  82. }