product_adder.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { formscreen } from "./formscreen.js";
  2. import { create_request } from "./create_request.js";
  3. import { bool_response } from "./bool_response.js";
  4. import { product_base } from "./product_base.js";
  5. import { searcher } from "./searcher.js";
  6. export class product_adder extends formscreen {
  7. #name;
  8. #description;
  9. #author;
  10. #barcode;
  11. #stock_count;
  12. #image;
  13. get _name() {
  14. return "Add product";
  15. }
  16. _build_form() {
  17. this.#name = this._create_input(
  18. "name",
  19. "Name:",
  20. "Sample..."
  21. );
  22. this.#description = this._create_input(
  23. "description",
  24. "Description:",
  25. "This is sample product..."
  26. );
  27. this.#author = this._create_input(
  28. "author",
  29. "Author:",
  30. "Jack Black"
  31. );
  32. this.#barcode = this._create_input(
  33. "barcode",
  34. "Barcode (EAN):",
  35. "123456789012...",
  36. (input) => { input.type = "number"; }
  37. );
  38. this.#stock_count = this._create_input(
  39. "stock_count",
  40. "Stock count:",
  41. "10...",
  42. (input) => { input.type = "number"; }
  43. );
  44. this._create_input(
  45. "image",
  46. "Product image:",
  47. "",
  48. (input) => {
  49. this.#image = input;
  50. input.type = "file";
  51. input.accept = "image/*";
  52. }
  53. );
  54. }
  55. async #code_image() {
  56. if (this.#image.files.length === 0) {
  57. throw new Error("Upload image for product.");
  58. }
  59. const file = this.#image.files.item(0);
  60. const buffer = await file.arrayBuffer();
  61. const list = new Uint8Array(buffer);
  62. let content = new String();
  63. list.forEach((code) => {
  64. content += String.fromCharCode(code);
  65. });
  66. return btoa(content);
  67. }
  68. async #submit() {
  69. const product = new product_base();
  70. product.name = this.#name();
  71. product.description = this.#description();
  72. product.author = this.#author();
  73. product.stock_count = this.#stock_count();
  74. product.barcode = this.#barcode();
  75. const image = await this.#code_image();
  76. const request = new create_request(product, image);
  77. const response = await request.connect();
  78. if (!response.result) {
  79. throw new Error(response.cause);
  80. }
  81. }
  82. async _process() {
  83. try {
  84. this._info = "Uploading...";
  85. await this.#submit();
  86. this._success = "Created success!";
  87. searcher.reload();
  88. setTimeout(() => {
  89. this.hide();
  90. }, 500);
  91. } catch (error) {
  92. this._error = new String(error);
  93. }
  94. }
  95. }