@infrab4a/connect 1.0.0-beta.9 → 1.0.1-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/bundles/infrab4a-connect.umd.js +1297 -321
  2. package/bundles/infrab4a-connect.umd.js.map +1 -1
  3. package/domain/catalog/models/category.d.ts +2 -2
  4. package/domain/catalog/models/index.d.ts +3 -2
  5. package/domain/catalog/models/kit-product.d.ts +12 -0
  6. package/domain/catalog/models/product.d.ts +6 -2
  7. package/domain/catalog/models/types/product-review.type.d.ts +10 -8
  8. package/domain/catalog/models/variant.d.ts +3 -1
  9. package/domain/catalog/repositories/product.repository.d.ts +9 -2
  10. package/domain/generic/model/base.model.d.ts +1 -1
  11. package/domain/generic/model/types/base-model-builder.type.d.ts +1 -1
  12. package/domain/generic/model/types/non-function-property-name.type.d.ts +1 -1
  13. package/domain/generic/repository/create.repository.d.ts +2 -2
  14. package/domain/generic/repository/delete.repository.d.ts +3 -1
  15. package/domain/generic/repository/find.repository.d.ts +2 -1
  16. package/domain/generic/repository/types/repository-find-filters.type.d.ts +4 -4
  17. package/domain/generic/repository/types/repository-update-params.type.d.ts +4 -4
  18. package/domain/users/errors/unauthorized.error.d.ts +2 -1
  19. package/domain/users/errors/user-already-registered.error.d.ts +2 -1
  20. package/domain/users/errors/weak-password.error.d.ts +2 -1
  21. package/domain/users/models/user.d.ts +2 -0
  22. package/errors/duplicated-results.error.d.ts +2 -1
  23. package/errors/invalid-argument.error.d.ts +2 -1
  24. package/errors/not-found.error.d.ts +2 -1
  25. package/errors/required-argument.error.d.ts +2 -1
  26. package/esm2015/domain/catalog/models/category.js +1 -1
  27. package/esm2015/domain/catalog/models/index.js +4 -3
  28. package/esm2015/domain/catalog/models/kit-product.js +18 -0
  29. package/esm2015/domain/catalog/models/product.js +8 -1
  30. package/esm2015/domain/catalog/models/types/product-review.type.js +1 -1
  31. package/esm2015/domain/catalog/models/variant.js +1 -1
  32. package/esm2015/domain/catalog/repositories/product.repository.js +1 -1
  33. package/esm2015/domain/generic/model/base.model.js +4 -4
  34. package/esm2015/domain/generic/model/types/base-model-builder.type.js +1 -1
  35. package/esm2015/domain/generic/model/types/non-function-property-name.type.js +1 -1
  36. package/esm2015/domain/generic/repository/create.repository.js +1 -1
  37. package/esm2015/domain/generic/repository/delete.repository.js +1 -1
  38. package/esm2015/domain/generic/repository/find.repository.js +1 -1
  39. package/esm2015/domain/generic/repository/types/repository-find-filters.type.js +1 -1
  40. package/esm2015/domain/generic/repository/types/repository-update-params.type.js +1 -1
  41. package/esm2015/domain/users/errors/unauthorized.error.js +3 -2
  42. package/esm2015/domain/users/errors/user-already-registered.error.js +3 -2
  43. package/esm2015/domain/users/errors/weak-password.error.js +3 -2
  44. package/esm2015/domain/users/models/user.js +1 -1
  45. package/esm2015/errors/duplicated-results.error.js +3 -2
  46. package/esm2015/errors/invalid-argument.error.js +3 -2
  47. package/esm2015/errors/not-found.error.js +3 -2
  48. package/esm2015/errors/required-argument.error.js +3 -2
  49. package/esm2015/infra/elasticsearch/adapters/axios.adapter.js +36 -1
  50. package/esm2015/infra/elasticsearch/adapters/elastic-search.adapter.js +1 -1
  51. package/esm2015/infra/elasticsearch/indexes/products-index.js +35 -1
  52. package/esm2015/infra/firebase/auth/authentication-firebase-auth.service.js +2 -2
  53. package/esm2015/infra/firebase/auth/register-firebase-auth.service.js +1 -1
  54. package/esm2015/infra/firebase/firestore/mixins/with-find-firestore.mixin.js +11 -5
  55. package/esm2015/infra/firebase/firestore/mixins/with-firestore.mixin.js +2 -3
  56. package/esm2015/infra/firebase/firestore/mixins/with-helpers.mixin.js +1 -1
  57. package/esm2015/infra/firebase/firestore/repositories/catalog/category-firestore.repository.js +4 -2
  58. package/esm2015/infra/firebase/firestore/repositories/catalog/product-firestore.repository.js +32 -5
  59. package/esm2015/infra/hasura-graphql/index.js +3 -2
  60. package/esm2015/infra/hasura-graphql/mixins/helpers/attribute-option.helper.js +18 -2
  61. package/esm2015/infra/hasura-graphql/mixins/helpers/filter-option.helper.js +20 -0
  62. package/esm2015/infra/hasura-graphql/mixins/helpers/graphql-field.helper.js +72 -0
  63. package/esm2015/infra/hasura-graphql/mixins/helpers/index.js +3 -1
  64. package/esm2015/infra/hasura-graphql/mixins/with-create-hasura-graphql.mixin.js +21 -2
  65. package/esm2015/infra/hasura-graphql/mixins/with-delete-hasura-graphql.mixin.js +14 -6
  66. package/esm2015/infra/hasura-graphql/mixins/with-find-hasura-graphql.mixin.js +24 -26
  67. package/esm2015/infra/hasura-graphql/mixins/with-get-hasura-graphql.mixin.js +14 -10
  68. package/esm2015/infra/hasura-graphql/mixins/with-hasura-graphql.mixin.js +10 -84
  69. package/esm2015/infra/hasura-graphql/mixins/with-update-hasura-graphql.mixin.js +18 -7
  70. package/esm2015/infra/hasura-graphql/models/category-hasura-graphql.js +1 -1
  71. package/esm2015/infra/hasura-graphql/models/index.js +4 -1
  72. package/esm2015/infra/hasura-graphql/models/kit-product-hasura-graphql.js +15 -0
  73. package/esm2015/infra/hasura-graphql/models/product-hasura-graphql.js +11 -0
  74. package/esm2015/infra/hasura-graphql/models/variant-hasura-graphql.js +9 -0
  75. package/esm2015/infra/hasura-graphql/repositories/catalog/category-hasura-graphql.repository.js +47 -15
  76. package/esm2015/infra/hasura-graphql/repositories/catalog/index.js +2 -1
  77. package/esm2015/infra/hasura-graphql/repositories/catalog/product-hasura-graphql.repository.js +362 -63
  78. package/esm2015/infra/hasura-graphql/repositories/catalog/variant-hasura-graphql.repository.js +116 -0
  79. package/esm2015/infra/hasura-graphql/types/graphql.repository.type.js +1 -1
  80. package/esm2015/infra/hasura-graphql/types/hasura-graphql-fields.type.js +1 -1
  81. package/esm2015/infra/hasura-graphql/types/hasura-graphql-headers.type.js +2 -0
  82. package/esm2015/infra/hasura-graphql/types/index.js +2 -1
  83. package/fesm2015/infrab4a-connect.js +870 -219
  84. package/fesm2015/infrab4a-connect.js.map +1 -1
  85. package/infra/elasticsearch/adapters/axios.adapter.d.ts +3 -0
  86. package/infra/elasticsearch/adapters/elastic-search.adapter.d.ts +3 -0
  87. package/infra/elasticsearch/indexes/products-index.d.ts +5 -1
  88. package/infra/firebase/auth/authentication-firebase-auth.service.d.ts +1 -1
  89. package/infra/firebase/auth/register-firebase-auth.service.d.ts +1 -1
  90. package/infra/firebase/firestore/mixins/with-find-firestore.mixin.d.ts +1 -1
  91. package/infra/firebase/firestore/mixins/with-firestore.mixin.d.ts +1 -1
  92. package/infra/firebase/firestore/repositories/catalog/product-firestore.repository.d.ts +4 -2
  93. package/infra/hasura-graphql/index.d.ts +2 -1
  94. package/infra/hasura-graphql/mixins/helpers/attribute-option.helper.d.ts +9 -6
  95. package/infra/hasura-graphql/mixins/helpers/filter-option.helper.d.ts +6 -0
  96. package/infra/hasura-graphql/mixins/helpers/graphql-field.helper.d.ts +8 -0
  97. package/infra/hasura-graphql/mixins/helpers/index.d.ts +2 -0
  98. package/infra/hasura-graphql/mixins/with-create-hasura-graphql.mixin.d.ts +1 -1
  99. package/infra/hasura-graphql/mixins/with-find-hasura-graphql.mixin.d.ts +8 -7
  100. package/infra/hasura-graphql/mixins/with-get-hasura-graphql.mixin.d.ts +5 -5
  101. package/infra/hasura-graphql/mixins/with-hasura-graphql.mixin.d.ts +3 -3
  102. package/infra/hasura-graphql/mixins/with-update-hasura-graphql.mixin.d.ts +1 -1
  103. package/infra/hasura-graphql/models/category-hasura-graphql.d.ts +3 -1
  104. package/infra/hasura-graphql/models/index.d.ts +3 -0
  105. package/infra/hasura-graphql/models/kit-product-hasura-graphql.d.ts +6 -0
  106. package/infra/hasura-graphql/models/product-hasura-graphql.d.ts +10 -0
  107. package/infra/hasura-graphql/models/variant-hasura-graphql.d.ts +9 -0
  108. package/infra/hasura-graphql/repositories/catalog/index.d.ts +1 -0
  109. package/infra/hasura-graphql/repositories/catalog/product-hasura-graphql.repository.d.ts +22 -5
  110. package/infra/hasura-graphql/repositories/catalog/variant-hasura-graphql.repository.d.ts +14 -0
  111. package/infra/hasura-graphql/types/graphql.repository.type.d.ts +5 -5
  112. package/infra/hasura-graphql/types/hasura-graphql-fields.type.d.ts +15 -19
  113. package/infra/hasura-graphql/types/hasura-graphql-headers.type.d.ts +7 -0
  114. package/infra/hasura-graphql/types/index.d.ts +1 -0
  115. package/package.json +4 -3
@@ -1,14 +1,14 @@
1
1
  import 'reflect-metadata';
2
- import { plainToClass, classToPlain, Expose, Type } from 'class-transformer';
3
- import { __decorate, __metadata, __awaiter } from 'tslib';
2
+ import { plainToInstance, instanceToPlain, Expose, Type } from 'class-transformer';
3
+ import { __decorate, __metadata, __awaiter, __rest } from 'tslib';
4
4
  import { parseISO } from 'date-fns';
5
5
  export { add, addBusinessDays, addDays, addMonths, addYears, endOfDay, format, formatISO9075, parseISO, startOfDay, sub } from 'date-fns';
6
- import { isString, isNil, isNumber, isDate, set, isObject, isEmpty, chunk, isBoolean, isInteger, isNaN as isNaN$1 } from 'lodash';
6
+ import { isString, isNil, isNumber, isDate, set, isObject, isEmpty, chunk, isBoolean, isInteger, isNaN as isNaN$1, omit } from 'lodash';
7
7
  export { chunk, isBoolean, isDate, isEmpty, isInteger, isNaN, isNil, isNumber, isObject, isString, now, omit, pick, set } from 'lodash';
8
+ import { CustomError } from 'ts-custom-error';
8
9
  import { Md5 } from 'ts-md5';
9
10
  import axios from 'axios';
10
11
  import firebase from 'firebase';
11
- import firebase$1 from 'firebase/app';
12
12
  import { mutation, query } from 'gql-query-builder';
13
13
  import fetch from 'node-fetch';
14
14
 
@@ -24,13 +24,13 @@ class BaseModel {
24
24
  Object.assign(this, args);
25
25
  }
26
26
  static toInstance(data) {
27
- return plainToClass(this, data || {});
27
+ return plainToInstance(this, data || {});
28
28
  }
29
29
  static isModel(value) {
30
30
  return value instanceof this;
31
31
  }
32
32
  toPlain() {
33
- return classToPlain(this);
33
+ return instanceToPlain(this);
34
34
  }
35
35
  }
36
36
 
@@ -620,7 +620,7 @@ class Lead extends BaseModel {
620
620
  }
621
621
  }
622
622
 
623
- class UnauthorizedError extends Error {
623
+ class UnauthorizedError extends CustomError {
624
624
  constructor(message) {
625
625
  super(message);
626
626
  this.message = message;
@@ -663,14 +663,14 @@ class Authentication {
663
663
  }
664
664
  }
665
665
 
666
- class UserAlreadyRegisteredError extends Error {
666
+ class UserAlreadyRegisteredError extends CustomError {
667
667
  constructor(message) {
668
668
  super(message);
669
669
  this.message = message;
670
670
  }
671
671
  }
672
672
 
673
- class WeakPasswordError extends Error {
673
+ class WeakPasswordError extends CustomError {
674
674
  constructor(message = 'Weak password') {
675
675
  super(message);
676
676
  this.message = message;
@@ -730,13 +730,6 @@ class RecoveryPassword {
730
730
  }
731
731
  }
732
732
 
733
- var Shops;
734
- (function (Shops) {
735
- Shops["MENSMARKET"] = "mensmarket";
736
- Shops["GLAMSHOP"] = "Glamshop";
737
- Shops["GLAMPOINTS"] = "Glampoints";
738
- })(Shops || (Shops = {}));
739
-
740
733
  class Category extends BaseModel {
741
734
  identifierFields() {
742
735
  return ['id'];
@@ -746,6 +739,13 @@ class Category extends BaseModel {
746
739
  }
747
740
  }
748
741
 
742
+ var Shops;
743
+ (function (Shops) {
744
+ Shops["MENSMARKET"] = "mensmarket";
745
+ Shops["GLAMSHOP"] = "Glamshop";
746
+ Shops["GLAMPOINTS"] = "Glampoints";
747
+ })(Shops || (Shops = {}));
748
+
749
749
  class Product extends BaseModel {
750
750
  identifierFields() {
751
751
  return ['id'];
@@ -758,6 +758,24 @@ class Product extends BaseModel {
758
758
  return ['id'];
759
759
  }
760
760
  }
761
+ __decorate([
762
+ Type(() => KitProduct),
763
+ __metadata("design:type", Array)
764
+ ], Product.prototype, "kitProducts", void 0);
765
+
766
+ class KitProduct extends BaseModel {
767
+ static get identifiersFields() {
768
+ return ['productId', 'kitProducId'];
769
+ }
770
+ }
771
+ __decorate([
772
+ Type(() => Product),
773
+ __metadata("design:type", Product)
774
+ ], KitProduct.prototype, "kit", void 0);
775
+ __decorate([
776
+ Type(() => Product),
777
+ __metadata("design:type", Product)
778
+ ], KitProduct.prototype, "product", void 0);
761
779
 
762
780
  class Variant extends BaseModel {
763
781
  identifierFields() {
@@ -980,14 +998,14 @@ class ShopMenu extends BaseModel {
980
998
  }
981
999
  }
982
1000
 
983
- class InvalidArgumentError extends Error {
1001
+ class InvalidArgumentError extends CustomError {
984
1002
  constructor(message) {
985
1003
  super(message);
986
1004
  this.message = message;
987
1005
  }
988
1006
  }
989
1007
 
990
- class RequiredArgumentError extends Error {
1008
+ class RequiredArgumentError extends CustomError {
991
1009
  constructor(args) {
992
1010
  super(`Required arguments: ${args.join(', ')}`);
993
1011
  this.args = args;
@@ -995,14 +1013,14 @@ class RequiredArgumentError extends Error {
995
1013
  }
996
1014
  }
997
1015
 
998
- class NotFoundError extends Error {
1016
+ class NotFoundError extends CustomError {
999
1017
  constructor(message) {
1000
1018
  super(message);
1001
1019
  this.message = message;
1002
1020
  }
1003
1021
  }
1004
1022
 
1005
- class DuplicatedResultsError extends Error {
1023
+ class DuplicatedResultsError extends CustomError {
1006
1024
  constructor(message) {
1007
1025
  super(message);
1008
1026
  this.message = message;
@@ -1013,6 +1031,21 @@ class AxiosAdapter {
1013
1031
  constructor(config) {
1014
1032
  this.config = config;
1015
1033
  }
1034
+ get(index) {
1035
+ return __awaiter(this, void 0, void 0, function* () {
1036
+ try {
1037
+ const { data } = yield axios({
1038
+ url: `${this.config.url}/${index}`,
1039
+ method: 'GET',
1040
+ headers: { Authorization: `Basic ${this.config.credential}` },
1041
+ });
1042
+ return data._source;
1043
+ }
1044
+ catch (error) {
1045
+ throw new NotFoundError(error.message);
1046
+ }
1047
+ });
1048
+ }
1016
1049
  query(index, query) {
1017
1050
  return __awaiter(this, void 0, void 0, function* () {
1018
1051
  const { data } = yield axios({
@@ -1027,12 +1060,37 @@ class AxiosAdapter {
1027
1060
  };
1028
1061
  });
1029
1062
  }
1063
+ save(index, data) {
1064
+ return __awaiter(this, void 0, void 0, function* () {
1065
+ yield axios({
1066
+ url: `${this.config.url}/${index}`,
1067
+ method: 'PUT',
1068
+ headers: { Authorization: `Basic ${this.config.credential}` },
1069
+ data,
1070
+ });
1071
+ });
1072
+ }
1073
+ delete(index) {
1074
+ return __awaiter(this, void 0, void 0, function* () {
1075
+ yield axios({
1076
+ url: `${this.config.url}/${index}`,
1077
+ method: 'DELETE',
1078
+ headers: { Authorization: `Basic ${this.config.credential}` },
1079
+ });
1080
+ });
1081
+ }
1030
1082
  }
1031
1083
 
1032
1084
  class ProductsIndex {
1033
1085
  constructor(adapter) {
1034
1086
  this.adapter = adapter;
1035
1087
  }
1088
+ get(id) {
1089
+ return __awaiter(this, void 0, void 0, function* () {
1090
+ const data = yield this.adapter.get(`products/_doc/${id}`);
1091
+ return Product.toInstance(data);
1092
+ });
1093
+ }
1036
1094
  findById(ids, options) {
1037
1095
  return __awaiter(this, void 0, void 0, function* () {
1038
1096
  const publishedField = options.shop === Shops.GLAMSHOP ? 'publishedGlam' : 'published';
@@ -1084,6 +1142,34 @@ class ProductsIndex {
1084
1142
  return hits.map((hit) => Product.toInstance(hit._source));
1085
1143
  });
1086
1144
  }
1145
+ save(product) {
1146
+ return __awaiter(this, void 0, void 0, function* () {
1147
+ delete product.createdAt;
1148
+ delete product.updatedAt;
1149
+ delete product.kitProducts;
1150
+ try {
1151
+ if (!product.firestoreId)
1152
+ throw new Error('Is not a product from firestore');
1153
+ yield this.get(product.firestoreId);
1154
+ yield this.adapter.save(`products/_doc/${product.firestoreId}`, product.toPlain());
1155
+ }
1156
+ catch (error) {
1157
+ console.info(error.message);
1158
+ yield this.adapter.save(`products/_doc/${product.id}`, product.toPlain());
1159
+ }
1160
+ });
1161
+ }
1162
+ delete(product) {
1163
+ return __awaiter(this, void 0, void 0, function* () {
1164
+ try {
1165
+ yield this.get(product.firestoreId);
1166
+ yield this.adapter.delete(`products/_doc/${product.firestoreId}`);
1167
+ }
1168
+ catch (error) {
1169
+ yield this.adapter.delete(`products/_doc/${product.id}`);
1170
+ }
1171
+ });
1172
+ }
1087
1173
  }
1088
1174
 
1089
1175
  const withFirestore = (MixinBase) => {
@@ -1097,7 +1183,7 @@ const withFirestore = (MixinBase) => {
1097
1183
  fromFirestore: (snap) => {
1098
1184
  const data = snap.data();
1099
1185
  Object.keys(data).forEach((key) => {
1100
- if (data[key] instanceof firebase.firestore.Timestamp) {
1186
+ if (data[key] && typeof data[key] === 'object' && '_seconds' in data[key]) {
1101
1187
  data[key] = data[key].toDate();
1102
1188
  }
1103
1189
  });
@@ -1182,11 +1268,17 @@ const withFindFirestore = (MixinBase) => {
1182
1268
  return queryReference.where(firestoreFieldName, (options === null || options === void 0 ? void 0 : options.operator) || '==', (options === null || options === void 0 ? void 0 : options.value) || options);
1183
1269
  };
1184
1270
  }
1185
- find({ filters, limits, orderBy, }) {
1271
+ find({ filters, limits, orderBy, } = {}) {
1186
1272
  return __awaiter(this, void 0, void 0, function* () {
1187
- let query = this.collection(this.buildCollectionPathForFind(filters));
1188
- query = this.makeFirestoreWhere(query, filters);
1189
- Object.keys(orderBy).forEach((fieldName) => (query = query.orderBy(fieldName, orderBy[fieldName])));
1273
+ const orderByKeys = Object.keys(orderBy || {});
1274
+ let query = this.collection(this.buildCollectionPathForFind(filters || {}));
1275
+ query = this.makeFirestoreWhere(query, filters || {});
1276
+ if (orderByKeys.length) {
1277
+ const filtersKeysWithUnordered = Object.keys(filters || {}).filter((filterKey) => !orderByKeys.includes(filterKey));
1278
+ if (filtersKeysWithUnordered.length)
1279
+ filtersKeysWithUnordered.forEach((filterKey) => (orderBy = Object.assign({ [filterKey]: 'asc' }, orderBy)));
1280
+ Object.keys(orderBy).forEach((fieldName) => (query = query.orderBy(fieldName, orderBy[fieldName])));
1281
+ }
1190
1282
  query = yield this.defineLimits(query, filters, limits);
1191
1283
  const docs = yield query.get();
1192
1284
  const data = docs.docs.map((doc) => doc.data());
@@ -1534,7 +1626,9 @@ class CategoryFirestoreRepository extends withCrudFirestore(withHelpers(withFire
1534
1626
  for (const productIds of chunks) {
1535
1627
  if ((options === null || options === void 0 ? void 0 : options.limit) && products.length >= (options === null || options === void 0 ? void 0 : options.limit))
1536
1628
  break;
1537
- let query = yield this.collection('products').where(publishedField, '==', true).where('id', 'in', productIds);
1629
+ let query = yield this.collection('productsErpVitrine')
1630
+ .where(publishedField, '==', true)
1631
+ .where('id', 'in', productIds);
1538
1632
  if (options === null || options === void 0 ? void 0 : options.hasStock)
1539
1633
  query = query.where('stock.quantity', '>', 0);
1540
1634
  if (options === null || options === void 0 ? void 0 : options.limit)
@@ -1553,21 +1647,48 @@ class ProductFirestoreRepository extends withCrudFirestore(withHelpers(withFires
1553
1647
  constructor(firestore) {
1554
1648
  super();
1555
1649
  this.firestore = firestore;
1556
- this.collectionName = 'products';
1650
+ this.reviews = {};
1651
+ this.collectionName = 'productsErpVitrine';
1557
1652
  this.model = Product;
1558
1653
  }
1559
- getBySlug(slug, shop) {
1654
+ getBySlug(slug) {
1560
1655
  var _a;
1561
1656
  return __awaiter(this, void 0, void 0, function* () {
1562
1657
  const result = yield this.find({
1563
1658
  filters: {
1564
1659
  slug: { operator: Where.EQUALS, value: slug },
1565
- shopAvailability: { operator: Where.IN, value: [shop] },
1566
1660
  },
1567
1661
  });
1568
1662
  return (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.shift();
1569
1663
  });
1570
1664
  }
1665
+ fetchReviews(status) {
1666
+ return __awaiter(this, void 0, void 0, function* () {
1667
+ const { data: products } = yield this.find();
1668
+ products.forEach((product) => {
1669
+ var _a;
1670
+ if ([undefined, 0].includes((_a = product.reviews) === null || _a === void 0 ? void 0 : _a.length))
1671
+ return;
1672
+ const productInfo = {
1673
+ productId: product.id,
1674
+ productName: product.name,
1675
+ productSku: product.sku,
1676
+ };
1677
+ this.reviews.pending = [];
1678
+ this.reviews.approved = [];
1679
+ this.reviews.rejected = [];
1680
+ product.reviews.forEach((review) => {
1681
+ if ([null, undefined].includes(review.status))
1682
+ return this.reviews.pending.push(Object.assign(Object.assign({}, review), productInfo));
1683
+ if (review.status === false)
1684
+ return this.reviews.rejected.push(Object.assign(Object.assign({}, review), productInfo));
1685
+ if (!!review.status)
1686
+ return this.reviews.approved.push(Object.assign(Object.assign({}, review), productInfo));
1687
+ });
1688
+ });
1689
+ return this.reviews[status];
1690
+ });
1691
+ }
1571
1692
  }
1572
1693
 
1573
1694
  class ProductVariantFirestoreRepository extends withSubCollection(withCrudFirestore(withHelpers(withFirestore(Base))), Product) {
@@ -1758,7 +1879,7 @@ class AuthenticationFirebaseAuthService {
1758
1879
  }
1759
1880
  signInWithGoogle() {
1760
1881
  return __awaiter(this, void 0, void 0, function* () {
1761
- const credentials = yield this.firebaseAuth.signInWithPopup(new firebase$1.auth.GoogleAuthProvider());
1882
+ const credentials = yield this.firebaseAuth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
1762
1883
  const user = credentials.user;
1763
1884
  return {
1764
1885
  id: user.uid,
@@ -1813,6 +1934,123 @@ class RegisterFirebaseAuthService {
1813
1934
  }
1814
1935
  }
1815
1936
 
1937
+ class AttributeOptionHelper {
1938
+ }
1939
+ AttributeOptionHelper.FindByAttribute = (attributeName, fields) => {
1940
+ if (fields.includes(attributeName))
1941
+ return { columnName: attributeName.toString(), attributeName };
1942
+ const field = fields.find((columnOption) => isObject(columnOption) && Object.keys(columnOption).includes(attributeName.toString()));
1943
+ const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName.toString()];
1944
+ if (isNil(fieldOption))
1945
+ return { columnName: attributeName.toString(), attributeName };
1946
+ if (Array.isArray(fieldOption))
1947
+ return { columnName: attributeName.toString(), attributeName, fields: fieldOption };
1948
+ return Object.assign({ attributeName, columnName: attributeName.toString() }, fieldOption);
1949
+ };
1950
+ AttributeOptionHelper.CheckIsColumnOption = (fieldValue) => !!fieldValue.columnName;
1951
+ AttributeOptionHelper.FindColumnOptionFromList = (columnName, fields) => {
1952
+ if (fields.includes(columnName))
1953
+ return { columnName, attributeName: columnName };
1954
+ const field = fields.find((columnOption) => {
1955
+ var _a;
1956
+ return isObject(columnOption) &&
1957
+ ((_a = Object.values(columnOption).find((option) => AttributeOptionHelper.CheckIsColumnOption(option) && option.columnName === columnName)) === null || _a === void 0 ? void 0 : _a.columnName) === columnName;
1958
+ }) || {};
1959
+ const attributeName = Object.keys(field).find((fieldOptionFromList) => AttributeOptionHelper.CheckIsColumnOption(field[fieldOptionFromList]) ||
1960
+ Array.isArray(field[fieldOptionFromList]));
1961
+ const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName];
1962
+ if (Array.isArray(fieldOption))
1963
+ return { attributeName: attributeName, fields: fieldOption };
1964
+ return Object.assign({ attributeName: attributeName || columnName, columnName }, fieldOption);
1965
+ };
1966
+
1967
+ class GraphQLFieldHelper {
1968
+ }
1969
+ GraphQLFieldHelper.CheckIsGraphQLParams = (params) => !isString(params) && Array.isArray(params) && params.length >= 0 && !!params[0].operation;
1970
+ GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields = (fields) => {
1971
+ return fields === null || fields === void 0 ? void 0 : fields.map((field) => {
1972
+ if (isString(field))
1973
+ return field.toString();
1974
+ const fieldName = Object.keys(field).shift();
1975
+ const fieldValue = field[fieldName];
1976
+ if (Array.isArray(fieldValue))
1977
+ return { [fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue) };
1978
+ if (!AttributeOptionHelper.CheckIsColumnOption(fieldValue))
1979
+ return;
1980
+ if (fieldValue.fields)
1981
+ return {
1982
+ [fieldValue.columnName || fieldName]: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fieldValue.fields),
1983
+ };
1984
+ return fieldValue.columnName;
1985
+ }).filter((field) => !!field);
1986
+ };
1987
+ GraphQLFieldHelper.ConvertFieldValueFrom = (data, fields) => Object.keys(data).reduce((result, columnName) => {
1988
+ const { attributeName, fields: attributeFields, from, } = AttributeOptionHelper.FindColumnOptionFromList(columnName, fields);
1989
+ if (!!attributeFields && Array.isArray(attributeFields)) {
1990
+ if (Array.isArray(data[columnName]))
1991
+ return Object.assign(Object.assign({}, result), { [attributeName]: from
1992
+ ? from(data[columnName], data)
1993
+ : data[columnName].map((value) => GraphQLFieldHelper.ConvertFieldValueFrom(value, attributeFields)) });
1994
+ if (isObject(data[columnName]))
1995
+ return Object.assign(Object.assign({}, result), { [attributeName]: !!from
1996
+ ? from(data[columnName])
1997
+ : GraphQLFieldHelper.ConvertFieldValueFrom(data[columnName], attributeFields) });
1998
+ }
1999
+ if (!!from)
2000
+ return Object.assign(Object.assign({}, result), { [attributeName]: from(data[columnName], data) });
2001
+ return Object.assign(Object.assign({}, result), { [attributeName]: parseDateTime(data[columnName]) });
2002
+ }, {});
2003
+ GraphQLFieldHelper.ConvertFieldValueTo = (instance, fields, update = false) => {
2004
+ var _a;
2005
+ const data = ((_a = instance.toPlain) === null || _a === void 0 ? void 0 : _a.call(instance)) || instance;
2006
+ return Object.keys(data).reduce((result, attributeName) => {
2007
+ const { columnName, fields: attributeFields, foreignKeyColumn, to, bindPersistData, } = AttributeOptionHelper.FindByAttribute(attributeName, fields);
2008
+ if (bindPersistData)
2009
+ return Object.assign(Object.assign({}, result), bindPersistData(data[attributeName], instance));
2010
+ if (isNil(columnName))
2011
+ return result;
2012
+ if (!!foreignKeyColumn &&
2013
+ !isEmpty(foreignKeyColumn) &&
2014
+ !Object.keys(foreignKeyColumn).filter((key) => { var _a; return !((_a = data[attributeName]) === null || _a === void 0 ? void 0 : _a[key]); }).length)
2015
+ return Object.keys(foreignKeyColumn).reduce((object, current) => { var _a; return (Object.assign(Object.assign({}, object), { [foreignKeyColumn[current]]: (_a = data[attributeName]) === null || _a === void 0 ? void 0 : _a[current] })); }, Object.assign({}, result));
2016
+ if (update && isObject(data[attributeName]) && !isNil(attributeFields) && !isDate(data[attributeName]))
2017
+ return result;
2018
+ if (!!columnName && Array.isArray(attributeFields) && isObject(data[attributeName])) {
2019
+ const converted = !isNil(columnName) && to ? to(instance[attributeName], instance) : data[attributeName];
2020
+ return Object.assign(Object.assign({}, result), (converted !== undefined
2021
+ ? {
2022
+ [columnName]: {
2023
+ data: instance[attributeName] instanceof BaseModel
2024
+ ? GraphQLFieldHelper.ConvertFieldValueTo(data[attributeName], attributeFields)
2025
+ : converted,
2026
+ },
2027
+ }
2028
+ : {}));
2029
+ }
2030
+ if (!!to)
2031
+ return Object.assign(Object.assign({}, result), { [columnName]: to(instance[attributeName], instance) });
2032
+ return Object.assign(Object.assign({}, result), { [columnName]: data[attributeName] });
2033
+ }, {});
2034
+ };
2035
+
2036
+ class FilterOptionHelper {
2037
+ }
2038
+ FilterOptionHelper.CheckIfIsFilterOption = (filter) => !isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
2039
+ FilterOptionHelper.GetValueFromFilter = (filter, fieldOption) => {
2040
+ if (!FilterOptionHelper.CheckIfIsFilterOption(filter))
2041
+ return filter;
2042
+ if (filter.operator === Where.ISNULL)
2043
+ return true;
2044
+ if (filter.operator === Where.ISNOTNULL)
2045
+ return false;
2046
+ const converter = fieldOption.to
2047
+ ? fieldOption.to
2048
+ : (value) => (filter.operator === Where.LIKE && value.indexOf('%') < 0 ? `%${value}%` : value);
2049
+ return Array.isArray(filter.value) && !fieldOption.fields && [Where.IN, Where.NOTIN].includes(filter.operator)
2050
+ ? filter.value.map((fieldValue) => converter(fieldValue))
2051
+ : converter(filter.value);
2052
+ };
2053
+
1816
2054
  const withCreateHasuraGraphQL = (MixinBase) => {
1817
2055
  return class CreateHasuraGraphQLMixin extends MixinBase {
1818
2056
  constructor(...params) {
@@ -1829,7 +2067,25 @@ const withCreateHasuraGraphQL = (MixinBase) => {
1829
2067
  }
1830
2068
  save(data) {
1831
2069
  return __awaiter(this, void 0, void 0, function* () {
1832
- const result = yield this.mutation(this.insertGraphQLOperation, this.model.identifiersFields, {
2070
+ const primaryKeyColumns = this.model.identifiersFields.map((field) => AttributeOptionHelper.FindByAttribute(field, this.fields).columnName);
2071
+ const foreignKeyColumns = this.fields
2072
+ .map((field) => {
2073
+ const columnOptions = Object.values(field).shift();
2074
+ return (AttributeOptionHelper.CheckIsColumnOption(columnOptions) &&
2075
+ columnOptions.foreignKeyColumn && [
2076
+ ...Object.values(columnOptions.foreignKeyColumn),
2077
+ {
2078
+ [columnOptions.columnName]: Object.keys(columnOptions.foreignKeyColumn).map((foreignKeyField) => {
2079
+ var _a;
2080
+ return ((_a = AttributeOptionHelper.FindByAttribute(foreignKeyField, columnOptions === null || columnOptions === void 0 ? void 0 : columnOptions.fields)) === null || _a === void 0 ? void 0 : _a.columnName) ||
2081
+ foreignKeyField;
2082
+ }),
2083
+ },
2084
+ ]);
2085
+ })
2086
+ .filter(Boolean)
2087
+ .reduce((keys, current) => [...keys, ...current], []);
2088
+ const result = yield this.mutation(this.insertGraphQLOperation, [...primaryKeyColumns, ...foreignKeyColumns], {
1833
2089
  object: { type: this.insertGraphQLObjectType, required: true, value: this.convertDataToHasura(data) },
1834
2090
  });
1835
2091
  return Object.assign(Object.assign({}, data.toPlain()), this.convertDataFromHasura(result[this.insertGraphQLOperation]).toPlain());
@@ -1848,105 +2104,23 @@ const withDeleteHasuraGraphQL = (MixinBase) => {
1848
2104
  delete(identifiers) {
1849
2105
  return __awaiter(this, void 0, void 0, function* () {
1850
2106
  const instance = this.model.toInstance(identifiers);
1851
- yield this.mutation(this.deleteGraphQLOperation, this.model.identifiersFields, Object.keys(instance.identifier).reduce((variables, key) => (Object.assign(Object.assign({}, variables), { [key]: {
1852
- type: this.getAttributeGraphQLTypeOf(instance[key]),
1853
- required: true,
1854
- value: instance.identifier[key],
1855
- } })), {}));
2107
+ yield this.mutation(this.deleteGraphQLOperation, this.model.identifiersFields.map((field) => AttributeOptionHelper.FindByAttribute(field, this.fields).columnName), this.model.identifiersFields.reduce((ids, identifier) => {
2108
+ if (isNil(instance[identifier]))
2109
+ return ids;
2110
+ const columnOption = AttributeOptionHelper.FindByAttribute(identifier, this.fields);
2111
+ const value = columnOption.to(identifiers[identifier.toString()], instance);
2112
+ return Object.assign(Object.assign({}, ids), { [columnOption.columnName]: {
2113
+ type: this.getAttributeGraphQLTypeOf(columnOption.type || value),
2114
+ value,
2115
+ required: true,
2116
+ } });
2117
+ }, {}));
1856
2118
  });
1857
2119
  }
1858
2120
  };
1859
2121
  };
1860
2122
 
1861
- class AttributeOptionHelper {
1862
- }
1863
- AttributeOptionHelper.findByAttribute = (attributeName, fields) => {
1864
- if (fields.includes(attributeName))
1865
- return { columnName: attributeName.toString(), attributeName };
1866
- const field = fields.find((columnOption) => isObject(columnOption) && Object.keys(columnOption).includes(attributeName.toString()));
1867
- const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName.toString()];
1868
- if (isNil(fieldOption))
1869
- return { columnName: attributeName.toString(), attributeName };
1870
- if (Array.isArray(fieldOption))
1871
- return { columnName: attributeName.toString(), attributeName, fields: fieldOption };
1872
- return Object.assign({ attributeName, columnName: attributeName.toString() }, fieldOption);
1873
- };
1874
-
1875
2123
  const withHasuraGraphQL = (MixinBase) => {
1876
- const checkIsGraphQLParams = (params) => !isString(params) && Array.isArray(params) && params.length >= 0 && !!params[0].operation;
1877
- const checkIsColumnModelOption = (fieldValue) => !!fieldValue.columnName && !!fieldValue.fields;
1878
- const checkIsColumnOption = (fieldValue) => checkIsColumnModelOption(fieldValue) || !!fieldValue.columnName;
1879
- const convertModelFieldsToGraphQLFields = (fields) => {
1880
- return fields
1881
- .map((field) => {
1882
- if (isString(field))
1883
- return field.toString();
1884
- const fieldName = Object.keys(field).shift();
1885
- const fieldValue = field[fieldName];
1886
- if (Array.isArray(fieldValue))
1887
- return { [fieldName]: convertModelFieldsToGraphQLFields(fieldValue) };
1888
- if (checkIsColumnModelOption(fieldValue))
1889
- return { [fieldValue.columnName || fieldName]: convertModelFieldsToGraphQLFields(fieldValue.fields) };
1890
- if (checkIsColumnOption(fieldValue))
1891
- return fieldValue.columnName;
1892
- return;
1893
- })
1894
- .filter((field) => !!field);
1895
- };
1896
- const findColumnOptionFromList = (columnName, fields) => {
1897
- if (fields.includes(columnName))
1898
- return { columnName, attributeName: columnName };
1899
- const field = fields.find((columnOption) => {
1900
- var _a;
1901
- return isObject(columnOption) &&
1902
- ((_a = Object.values(columnOption).find((option) => checkIsColumnOption(option) && option.columnName === columnName)) === null || _a === void 0 ? void 0 : _a.columnName) === columnName;
1903
- }) || {};
1904
- const attributeName = Object.keys(field).find((fieldOption) => checkIsColumnOption(field[fieldOption]) || Array.isArray(field[fieldOption]));
1905
- const fieldOption = field === null || field === void 0 ? void 0 : field[attributeName];
1906
- if (Array.isArray(fieldOption))
1907
- return { attributeName: attributeName, fields: fieldOption };
1908
- return Object.assign({ attributeName: attributeName || columnName, columnName }, fieldOption);
1909
- };
1910
- const convertFieldValueFrom = (data, fields) => Object.keys(data).reduce((result, columnName) => {
1911
- const { attributeName, fields: attributeFields, from } = findColumnOptionFromList(columnName, fields);
1912
- if (!!attributeFields && Array.isArray(attributeFields)) {
1913
- if (Array.isArray(data[columnName]))
1914
- return Object.assign(Object.assign({}, result), { [attributeName]: from
1915
- ? from(data[columnName], data)
1916
- : data[columnName].map((value) => convertFieldValueFrom(value, attributeFields)) });
1917
- if (isObject(data[columnName]))
1918
- return Object.assign(Object.assign({}, result), { [attributeName]: convertFieldValueFrom(data[columnName], attributeFields) });
1919
- }
1920
- if (!!from)
1921
- return Object.assign(Object.assign({}, result), { [attributeName]: from(data[columnName], data) });
1922
- return Object.assign(Object.assign({}, result), { [attributeName]: parseDateTime(data[columnName]) });
1923
- }, {});
1924
- const convertFieldValueTo = (instance, fields, update = false) => {
1925
- var _a;
1926
- const data = ((_a = instance.toPlain) === null || _a === void 0 ? void 0 : _a.call(instance)) || instance;
1927
- return Object.keys(data)
1928
- .filter((key) => !isNil(data[key]))
1929
- .reduce((result, attributeName) => {
1930
- const { columnName, fields: attributeFields, foreignKeyColumn, to, } = AttributeOptionHelper.findByAttribute(attributeName, fields);
1931
- if (isNil(columnName))
1932
- return result;
1933
- if (!!foreignKeyColumn &&
1934
- !isEmpty(foreignKeyColumn) &&
1935
- !Object.keys(foreignKeyColumn).filter((key) => !data[attributeName][key]).length)
1936
- return Object.keys(foreignKeyColumn).reduce((object, current) => (Object.assign(Object.assign({}, object), { [foreignKeyColumn[current]]: data[attributeName][current] })), Object.assign({}, result));
1937
- if (update && isObject(data[attributeName]) && !isDate(data[attributeName]))
1938
- return result;
1939
- if (!!columnName && Array.isArray(attributeFields) && isObject(data[attributeName])) {
1940
- const converted = !isNil(columnName) ? to(instance[attributeName], instance) : data[attributeName];
1941
- return Object.assign(Object.assign({}, result), (converted !== undefined
1942
- ? { [columnName]: { data: convertFieldValueTo(data[attributeName], attributeFields) } }
1943
- : {}));
1944
- }
1945
- if (!!to)
1946
- return Object.assign(Object.assign({}, result), { [columnName]: to(instance[attributeName], instance) });
1947
- return Object.assign(Object.assign({}, result), { [columnName]: data[attributeName] });
1948
- }, {});
1949
- };
1950
2124
  return class HasuraGraphQLMixin extends MixinBase {
1951
2125
  constructor(...params) {
1952
2126
  const options = params[0];
@@ -1967,23 +2141,23 @@ const withHasuraGraphQL = (MixinBase) => {
1967
2141
  const resultQuery = mutation({
1968
2142
  operation,
1969
2143
  variables,
1970
- fields: convertModelFieldsToGraphQLFields(fields),
2144
+ fields: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fields),
1971
2145
  });
1972
2146
  return this.fetch(resultQuery);
1973
2147
  });
1974
2148
  }
1975
2149
  query(operation, fields, variables) {
1976
2150
  return __awaiter(this, void 0, void 0, function* () {
1977
- const resultQuery = checkIsGraphQLParams(operation)
2151
+ const resultQuery = GraphQLFieldHelper.CheckIsGraphQLParams(operation)
1978
2152
  ? query(operation.map((option) => ({
1979
2153
  operation: option.operation,
1980
2154
  variables: option.variables,
1981
- fields: convertModelFieldsToGraphQLFields(option.fields),
2155
+ fields: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(option.fields),
1982
2156
  })))
1983
2157
  : query({
1984
2158
  operation,
1985
2159
  variables,
1986
- fields: convertModelFieldsToGraphQLFields(fields),
2160
+ fields: GraphQLFieldHelper.ConvertModelFieldsToGraphQLFields(fields),
1987
2161
  });
1988
2162
  return this.fetch(resultQuery);
1989
2163
  });
@@ -2026,20 +2200,22 @@ const withHasuraGraphQL = (MixinBase) => {
2026
2200
  return date;
2027
2201
  }
2028
2202
  convertDataFromHasura(data) {
2029
- const plain = convertFieldValueFrom(data, this.fields);
2203
+ const plain = GraphQLFieldHelper.ConvertFieldValueFrom(data, this.fields);
2030
2204
  return this.model.toInstance(plain);
2031
2205
  }
2032
2206
  convertDataToHasura(instance, update = false) {
2033
- return convertFieldValueTo(instance, this.fields, update);
2207
+ return GraphQLFieldHelper.ConvertFieldValueTo(instance, this.fields, update);
2034
2208
  }
2035
2209
  };
2036
2210
  };
2037
2211
 
2038
2212
  const withUpdateHasuraGraphQL = (MixinBase) => {
2039
2213
  const getValueByAction = (options) => {
2040
- if (isNil(options.action))
2214
+ if (options instanceof BaseModel)
2215
+ return options.toPlain();
2216
+ if (isNil(options === null || options === void 0 ? void 0 : options.action))
2041
2217
  return options;
2042
- if (options.action === UpdateOptionActions.REMOVE_FIELD)
2218
+ if ([UpdateOptionActions.REMOVE_FIELD.toString(), UpdateOptionActions.NULL.toString()].includes(options.action))
2043
2219
  return null;
2044
2220
  return options.value;
2045
2221
  };
@@ -2054,7 +2230,7 @@ const withUpdateHasuraGraphQL = (MixinBase) => {
2054
2230
  update(data) {
2055
2231
  return __awaiter(this, void 0, void 0, function* () {
2056
2232
  const plainData = this.paramsToPlain(data);
2057
- yield this.mutation(this.updateGraphQLOperation, this.model.identifiersFields, {
2233
+ yield this.mutation(this.updateGraphQLOperation, this.model.identifiersFields.map((field) => AttributeOptionHelper.FindByAttribute(field, this.fields).columnName), {
2058
2234
  _set: {
2059
2235
  type: this.updateGraphQLObjectType,
2060
2236
  value: this.convertDataToHasura(this.model.toInstance(plainData), true),
@@ -2069,10 +2245,18 @@ const withUpdateHasuraGraphQL = (MixinBase) => {
2069
2245
  const model = this.model;
2070
2246
  if (model.isModel(params))
2071
2247
  return params.toPlain();
2072
- return Object.keys(params).reduce((data, currentKey) => (Object.assign(Object.assign({}, data), { [currentKey]: getValueByAction(params[currentKey]) })), {});
2248
+ return Object.keys(params).reduce((data, currentKey) => (Object.assign(Object.assign({}, data), (params[currentKey] !== undefined && { [currentKey]: getValueByAction(params[currentKey]) }))), {});
2073
2249
  }
2074
2250
  getUpdateModelKeys(data) {
2075
- return this.model.identifiersFields.reduce((columns, key) => (Object.assign(Object.assign({}, columns), { [key]: data[key] })), {});
2251
+ const instance = this.model.toInstance(data);
2252
+ return this.model.identifiersFields.reduce((ids, identifier) => {
2253
+ var _a;
2254
+ if (isNil(instance[identifier]))
2255
+ return ids;
2256
+ const columnOption = AttributeOptionHelper.FindByAttribute(identifier, this.fields);
2257
+ const value = ((_a = columnOption === null || columnOption === void 0 ? void 0 : columnOption.to) === null || _a === void 0 ? void 0 : _a.call(columnOption, data[identifier.toString()], instance)) || data[columnOption.attributeName];
2258
+ return Object.assign(Object.assign({}, ids), { [columnOption.columnName]: value });
2259
+ }, {});
2076
2260
  }
2077
2261
  };
2078
2262
  };
@@ -2087,15 +2271,18 @@ const withGetHasuraGraphQL = (MixinBase) => {
2087
2271
  get(identifiers) {
2088
2272
  return __awaiter(this, void 0, void 0, function* () {
2089
2273
  const instance = this.model.toInstance(identifiers);
2090
- const result = yield this.query(this.getGraphQLOperation, this.fields, this.model.identifiersFields.reduce((ids, identifier) => (Object.assign(Object.assign({}, ids), (instance[identifier] === undefined
2091
- ? {}
2092
- : {
2093
- [identifier]: {
2094
- type: this.getAttributeGraphQLTypeOf(instance[identifier]),
2095
- value: identifiers[identifier],
2274
+ const result = yield this.query(this.getGraphQLOperation, this.fields, this.model.identifiersFields.reduce((ids, identifier) => {
2275
+ var _a;
2276
+ if (isNil(instance[identifier]))
2277
+ return ids;
2278
+ const columnOption = AttributeOptionHelper.FindByAttribute(identifier, this.fields);
2279
+ const value = ((_a = columnOption === null || columnOption === void 0 ? void 0 : columnOption.to) === null || _a === void 0 ? void 0 : _a.call(columnOption, identifiers[identifier.toString()], instance)) || identifiers[identifier.toString()];
2280
+ return Object.assign(Object.assign({}, ids), { [columnOption.columnName]: {
2281
+ type: this.getAttributeGraphQLTypeOf(columnOption.type || value),
2282
+ value,
2096
2283
  required: true,
2097
- },
2098
- }))), {}));
2284
+ } });
2285
+ }, {}));
2099
2286
  const data = result[this.getGraphQLOperation];
2100
2287
  if (isNil(data))
2101
2288
  throw new NotFoundError(`${instance.constructor.name} not found`);
@@ -2134,33 +2321,25 @@ var HasuraGraphQLColumnType;
2134
2321
  })(HasuraGraphQLColumnType || (HasuraGraphQLColumnType = {}));
2135
2322
 
2136
2323
  const withFindHasuraGraphQL = (MixinBase) => {
2137
- const checkIfIsFilterOption = (filter) => !isNil(filter === null || filter === void 0 ? void 0 : filter.operator);
2138
- const getValueFromFilter = (filter, fieldOption) => {
2139
- if (!checkIfIsFilterOption(filter))
2140
- return filter;
2141
- if (filter.operator === Where.ISNULL)
2142
- return true;
2143
- if (filter.operator === Where.ISNOTNULL)
2144
- return false;
2145
- const converter = fieldOption.to ? fieldOption.to : (value) => value;
2146
- return Array.isArray(filter.value) && [Where.IN, Where.NOTIN].includes(filter.operator)
2147
- ? filter.value.map((fieldValue) => converter(fieldValue))
2148
- : converter(filter.value);
2149
- };
2150
2324
  return class FindHasuraGraphQLMixin extends MixinBase {
2151
2325
  constructor() {
2152
2326
  super(...arguments);
2153
- this.makeGraphQLWhere = (filter, fields) => Object.keys(filter).reduce((variables, fieldName) => (Object.assign(Object.assign({}, variables), { [AttributeOptionHelper.findByAttribute(fieldName, fields)
2154
- .columnName]: this.buildWhereSentence(fieldName, filter[fieldName], fields) })), {});
2327
+ this.makeGraphQLWhere = (filter, fields) => Object.keys(filter).reduce((variables, fieldName) => {
2328
+ const columnOption = AttributeOptionHelper.FindByAttribute(fieldName, fields);
2329
+ if (!columnOption.bindFindFilter)
2330
+ return Object.assign(Object.assign({}, variables), { [columnOption.columnName]: this.buildWhereSentence(fieldName, filter[fieldName], fields) });
2331
+ const builtFilter = columnOption.bindFindFilter(filter[fieldName]);
2332
+ return Object.assign(Object.assign({}, variables), Object.keys(builtFilter).reduce((variablesList, columnName) => (Object.assign(Object.assign({}, variablesList), { [columnName]: this.buildWhereSentence(fieldName, builtFilter[columnName], fields) })), {}));
2333
+ }, {});
2155
2334
  this.buildWhereSentence = (field, options, fields) => {
2156
- const fieldSentenceOptions = AttributeOptionHelper.findByAttribute(field, fields);
2335
+ const fieldSentenceOptions = AttributeOptionHelper.FindByAttribute(field, fields);
2157
2336
  if (!Array.isArray(options) &&
2158
2337
  isObject(options) &&
2159
2338
  isNil(options === null || options === void 0 ? void 0 : options.operator) &&
2160
2339
  isNil(options === null || options === void 0 ? void 0 : options.value) &&
2161
2340
  isNil(fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.to))
2162
2341
  return Object.keys(options).reduce((variables, key) => {
2163
- const fieldOptions = AttributeOptionHelper.findByAttribute(key, fields);
2342
+ const fieldOptions = AttributeOptionHelper.FindByAttribute(key, (fieldSentenceOptions === null || fieldSentenceOptions === void 0 ? void 0 : fieldSentenceOptions.fields) || fields);
2164
2343
  const columnName = fieldOptions.columnName;
2165
2344
  const columnFields = fieldOptions.fields;
2166
2345
  return Object.assign(Object.assign({}, variables), { [columnName]: this.buildWhereSentence(key, options[key], columnFields || []) });
@@ -2169,16 +2348,16 @@ const withFindHasuraGraphQL = (MixinBase) => {
2169
2348
  return {
2170
2349
  [fieldSentenceOptions.fields[0]]: this.buildOperatorSentence(options, fieldSentenceOptions),
2171
2350
  };
2172
- if (isObject(options) && !checkIfIsFilterOption(options))
2351
+ if (isObject(options) && !FilterOptionHelper.CheckIfIsFilterOption(options))
2173
2352
  options = Object.values(options)[0];
2174
2353
  return Array.isArray(options)
2175
2354
  ? options.reduce((whereSentence, option) => (Object.assign(Object.assign({}, whereSentence), this.buildOperatorSentence(option, fieldSentenceOptions))), {})
2176
2355
  : this.buildOperatorSentence(options, fieldSentenceOptions);
2177
2356
  };
2178
2357
  this.buildOperatorSentence = (options, fieldOption) => ({
2179
- [this.getHasuraOperator(options, fieldOption)]: getValueFromFilter(options, fieldOption),
2358
+ [this.getHasuraOperator(options, fieldOption)]: FilterOptionHelper.GetValueFromFilter(options, fieldOption),
2180
2359
  });
2181
- this.getHasuraOperator = (options, fieldOption) => checkIfIsFilterOption(options)
2360
+ this.getHasuraOperator = (options, fieldOption) => FilterOptionHelper.CheckIfIsFilterOption(options)
2182
2361
  ? fieldOption.type === HasuraGraphQLColumnType.Jsonb
2183
2362
  ? this.getHasuraJsonbOperator(options)
2184
2363
  : HasuraGraphQLWhere[Object.keys(HasuraGraphQLWhere).find((graphQLOperator) => graphQLOperator === Object.keys(Where).find((operator) => Where[operator] === (options === null || options === void 0 ? void 0 : options.operator)))]
@@ -2202,11 +2381,17 @@ const withFindHasuraGraphQL = (MixinBase) => {
2202
2381
  },
2203
2382
  }));
2204
2383
  const variables = Object.assign(Object.assign({}, (isNil(limits) ? {} : limits)), variablesCount);
2205
- console.log(JSON.stringify(variables));
2206
2384
  const result = yield this.query([
2207
2385
  {
2208
2386
  operation: this.tableName,
2209
- fields: this.fields,
2387
+ fields: options.fields
2388
+ ? options.fields
2389
+ .map((fieldName) => {
2390
+ var _a;
2391
+ return (_a = this.fields.find((fieldOption) => fieldOption === fieldName)) !== null && _a !== void 0 ? _a : this.fields.find((fieldOption) => Object.keys(fieldOption).shift() === fieldName);
2392
+ })
2393
+ .filter(Boolean)
2394
+ : this.fields,
2210
2395
  variables,
2211
2396
  },
2212
2397
  {
@@ -2215,7 +2400,7 @@ const withFindHasuraGraphQL = (MixinBase) => {
2215
2400
  variables: variablesCount,
2216
2401
  },
2217
2402
  ]);
2218
- const data = result[this.tableName].map((data) => this.convertDataFromHasura(data));
2403
+ const data = result[this.tableName].map((row) => this.convertDataFromHasura(row));
2219
2404
  const count = result[`${this.tableName}_aggregate`].aggregate.count;
2220
2405
  return { count, data };
2221
2406
  });
@@ -2228,6 +2413,35 @@ const withCrudHasuraGraphQL = (MixinBase) => {
2228
2413
  };
2229
2414
  };
2230
2415
 
2416
+ class CategoryHasuraGraphQL extends Category {
2417
+ }
2418
+
2419
+ class ProductHasuraGraphQL extends Product {
2420
+ }
2421
+ __decorate([
2422
+ Type(() => KitProductHasuraGraphQL),
2423
+ __metadata("design:type", Array)
2424
+ ], ProductHasuraGraphQL.prototype, "kitProducts", void 0);
2425
+
2426
+ class KitProductHasuraGraphQL extends KitProduct {
2427
+ }
2428
+ __decorate([
2429
+ Type(() => ProductHasuraGraphQL),
2430
+ __metadata("design:type", ProductHasuraGraphQL)
2431
+ ], KitProductHasuraGraphQL.prototype, "kit", void 0);
2432
+ __decorate([
2433
+ Type(() => ProductHasuraGraphQL),
2434
+ __metadata("design:type", ProductHasuraGraphQL)
2435
+ ], KitProductHasuraGraphQL.prototype, "product", void 0);
2436
+
2437
+ class VariantHasuraGraphQL extends Variant {
2438
+ constructor() {
2439
+ super(...arguments);
2440
+ this.name = '';
2441
+ this.hasVariants = false;
2442
+ }
2443
+ }
2444
+
2231
2445
  class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
2232
2446
  constructor(endpoint, authOptions, productRepository) {
2233
2447
  super({
@@ -2237,7 +2451,7 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
2237
2451
  authOptions,
2238
2452
  fields: [
2239
2453
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
2240
- 'firestore_id',
2454
+ { firestoreId: { columnName: 'firestore_id' } },
2241
2455
  'name',
2242
2456
  'description',
2243
2457
  'image',
@@ -2248,11 +2462,22 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
2248
2462
  { brandCategoryBanner: { columnName: 'brand_banner' } },
2249
2463
  { brandCategoryBannerMobile: { columnName: 'brand_banner_mobile' } },
2250
2464
  { brandLogo: { columnName: 'brand_logo' } },
2251
- { conditions: { columnName: 'brand_condition' } },
2465
+ { brandCondition: { columnName: 'brand_condition' } },
2252
2466
  {
2253
2467
  conditions: {
2254
2468
  columnName: 'tag_condition',
2255
- from: (tags, row) => ({ brand: row.brand_condition, tags }),
2469
+ type: HasuraGraphQLColumnType.Jsonb,
2470
+ from: (tags, row) => ({ brand: row.brand_condition, tags: Array.isArray(tags) ? tags : [] }),
2471
+ bindPersistData: (value) => {
2472
+ var _a, _b;
2473
+ return {
2474
+ brand_condition: value.brand,
2475
+ tag_condition: `{"${((_b = (_a = value === null || value === void 0 ? void 0 : value.tags) === null || _a === void 0 ? void 0 : _a.join) === null || _b === void 0 ? void 0 : _b.call(_a, '","')) || ''}"}`,
2476
+ };
2477
+ },
2478
+ bindFindFilter: (sentence) => {
2479
+ return Object.assign(Object.assign({}, (sentence.brand ? { brand_condition: sentence.brand } : {})), (sentence.tags ? { tag_condition: sentence.tags } : {}));
2480
+ },
2256
2481
  },
2257
2482
  },
2258
2483
  'filters',
@@ -2263,6 +2488,9 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
2263
2488
  columnName: 'products',
2264
2489
  fields: ['product_id'],
2265
2490
  from: (value) => value.map((product) => product.product_id.toString()),
2491
+ to: (productIds) => productIds.map((productId) => ({
2492
+ product_id: +productId,
2493
+ })),
2266
2494
  },
2267
2495
  },
2268
2496
  ],
@@ -2276,7 +2504,7 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
2276
2504
  var _a;
2277
2505
  return __awaiter(this, void 0, void 0, function* () {
2278
2506
  return Number.isNaN(+identifiers.id)
2279
- ? (_a = (yield this.find({ filters: { firestore_id: identifiers.id } })).data) === null || _a === void 0 ? void 0 : _a[0]
2507
+ ? (_a = (yield this.find({ filters: { firestoreId: identifiers.id } })).data) === null || _a === void 0 ? void 0 : _a[0]
2280
2508
  : _super.get.call(this, identifiers);
2281
2509
  });
2282
2510
  }
@@ -2295,7 +2523,7 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
2295
2523
  getCategoriesForHome(categoryIds, limit = 4) {
2296
2524
  return __awaiter(this, void 0, void 0, function* () {
2297
2525
  const { data: categories, count } = yield this.find({
2298
- filters: { firestore_id: { operator: Where.IN, value: categoryIds.filter(Boolean) }, published: true },
2526
+ filters: { firestoreId: { operator: Where.IN, value: categoryIds.filter(Boolean) }, published: true },
2299
2527
  });
2300
2528
  if (!count)
2301
2529
  throw new NotFoundError('Categories not found');
@@ -2312,15 +2540,32 @@ class CategoryHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGr
2312
2540
  return __awaiter(this, void 0, void 0, function* () {
2313
2541
  if (!category.products)
2314
2542
  throw new RequiredArgumentError(['Category products is empty']);
2315
- console.log(category);
2316
- console.log(category.products);
2317
2543
  const products = [];
2318
2544
  const publishedField = category.shop === Shops.GLAMSHOP ? 'publishedGlam' : 'published';
2319
- const { data: productsData } = yield this.productRepository.find(Object.assign({ filters: {
2320
- id: { operator: Where.IN, value: category.products },
2321
- [publishedField]: true,
2322
- ///...(options?.hasStock ? { stock: { quantity: { operator: Where.GT, value: 0 } } } : {}),
2323
- } }, ((options === null || options === void 0 ? void 0 : options.limit) ? { limits: { limit: options === null || options === void 0 ? void 0 : options.limit } } : {})));
2545
+ const { data: productsData } = yield this.productRepository.find(Object.assign({ filters: Object.assign({ id: { operator: Where.IN, value: category.products }, [publishedField]: true }, ((options === null || options === void 0 ? void 0 : options.hasStock) ? { stock: { quantity: { operator: Where.GT, value: 0 } } } : {})), fields: [
2546
+ 'id',
2547
+ 'name',
2548
+ 'slug',
2549
+ 'images',
2550
+ 'miniatures',
2551
+ 'price',
2552
+ 'fullPrice',
2553
+ 'subscriberDiscountPercentage',
2554
+ 'subscriberPrice',
2555
+ 'stock',
2556
+ 'published',
2557
+ 'publishedGlam',
2558
+ 'CEST',
2559
+ 'EAN',
2560
+ 'NCM',
2561
+ 'brand',
2562
+ 'costPrice',
2563
+ 'hasVariants',
2564
+ 'isKit',
2565
+ 'shopAvailability',
2566
+ 'sku',
2567
+ 'rate',
2568
+ ] }, ((options === null || options === void 0 ? void 0 : options.limit) ? { limits: { limit: options === null || options === void 0 ? void 0 : options.limit } } : {})));
2324
2569
  products.push(...productsData);
2325
2570
  return products;
2326
2571
  });
@@ -2331,24 +2576,393 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
2331
2576
  constructor(endpoint, authOptions) {
2332
2577
  super({
2333
2578
  tableName: 'product',
2334
- model: Product,
2579
+ model: ProductHasuraGraphQL,
2580
+ endpoint,
2581
+ authOptions,
2582
+ fields: [],
2583
+ });
2584
+ this.bindReviewToModel = (plain) => (Object.assign(Object.assign({}, omit(plain, ['product_id', 'created_at', 'updated_at', 'person_id', 'order_id'])), { createdAt: typeof plain.created_at === 'string' ? new Date(plain.created_at) : plain.created_at, updatedAt: typeof plain.updated_at === 'string' ? new Date(plain.updated_at) : plain.updated_at, personId: plain.person_id, orderId: plain.order_id }));
2585
+ this.bindReviewToHasura = (review) => (Object.assign(Object.assign({}, omit(review, ['productId', 'createdAt', 'updatedAt', 'personId', 'orderId'])), { person_id: review.personId, order_id: review.orderId }));
2586
+ const commonFields = [
2587
+ { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
2588
+ { firestoreId: { columnName: 'firestore_id' } },
2589
+ { productId: { columnName: 'main_product_id' } },
2590
+ { CEST: { columnName: 'cest' } },
2591
+ { EAN: { columnName: 'ean' } },
2592
+ { NCM: { columnName: 'ncm' } },
2593
+ 'brand',
2594
+ { costPrice: { columnName: 'cost_price' } },
2595
+ {
2596
+ description: {
2597
+ columnName: 'description',
2598
+ from: (description) => Object.values(Shops).reduce((shops, shop) => (Object.assign(Object.assign({}, shops), { [shop]: { description } })), {}),
2599
+ to: (value) => Object.values(value).shift().description,
2600
+ },
2601
+ },
2602
+ { hasVariants: { columnName: 'has_variants' } },
2603
+ { images: { columnName: 'images', to: (value) => { var _a; return `{"${((_a = value === null || value === void 0 ? void 0 : value.join) === null || _a === void 0 ? void 0 : _a.call(value, `","`)) || ''}"}`; } } },
2604
+ { miniatures: { columnName: 'miniatures', to: (value) => { var _a; return `{"${((_a = value === null || value === void 0 ? void 0 : value.join) === null || _a === void 0 ? void 0 : _a.call(value, `","`)) || ''}"}`; } } },
2605
+ 'name',
2606
+ {
2607
+ price: {
2608
+ columnName: 'price',
2609
+ from: (price, data) => Object.values(Shops).reduce((prices, shop) => (Object.assign(Object.assign({}, prices), { [shop]: {
2610
+ price,
2611
+ fullPrice: data.full_price,
2612
+ subscriberDiscountPercentage: data.subscriber_discount_percentage,
2613
+ subscriberPrice: data.subscriber_price,
2614
+ } })), {}),
2615
+ bindFindFilter: (sentence) => {
2616
+ const filters = Object.values(sentence).shift();
2617
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, (((filters === null || filters === void 0 ? void 0 : filters.price) || (filters === null || filters === void 0 ? void 0 : filters.price) === 0) && { price: filters.price })), ((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice })), ((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
2618
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
2619
+ })), ((filters.subscriberPrice || filters.subscriberPrice === 0) && {
2620
+ subscriber_price: filters.subscriberPrice,
2621
+ }));
2622
+ },
2623
+ bindPersistData: (value) => {
2624
+ const priceData = Object.values(value).shift();
2625
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, ((priceData === null || priceData === void 0 ? void 0 : priceData.price) >= 0 && { price: priceData.price })), (priceData.fullPrice >= 0 && { full_price: priceData.fullPrice })), (priceData.subscriberDiscountPercentage >= 0 && {
2626
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
2627
+ })), (priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }));
2628
+ },
2629
+ },
2630
+ },
2631
+ { fullPrice: { columnName: 'full_price' } },
2632
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
2633
+ { subscriberPrice: { columnName: 'subscriber_price' } },
2634
+ 'published',
2635
+ { publishedGlam: { columnName: 'published_glam' } },
2636
+ 'sku',
2637
+ {
2638
+ stock: {
2639
+ columnName: 'stock',
2640
+ from: (quantity) => ({ quantity }),
2641
+ to: (value) => (isNil(value === null || value === void 0 ? void 0 : value.quantity) ? value : value === null || value === void 0 ? void 0 : value.quantity),
2642
+ },
2643
+ },
2644
+ 'slug',
2645
+ 'type',
2646
+ 'video',
2647
+ 'weight',
2648
+ {
2649
+ shopAvailability: {
2650
+ columnName: 'shop_availabilities',
2651
+ fields: ['shop'],
2652
+ from: (shop) => (Array.isArray(shop) ? shop.map((row) => row.shop) : []),
2653
+ bindPersistData: (shops) => ({ shop_availabilities: { data: shops.map((shop) => ({ shop })) } }),
2654
+ },
2655
+ },
2656
+ { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
2657
+ { isKit: { columnName: 'is_kit' } },
2658
+ { createdAt: { columnName: 'created_at' } },
2659
+ { updatedAt: { columnName: 'updated_at' } },
2660
+ {
2661
+ rate: {
2662
+ columnName: 'reviews_aggregate',
2663
+ fields: [{ aggregate: [{ avg: ['rate'] }] }],
2664
+ from: (value) => value.aggregate.avg.rate,
2665
+ },
2666
+ },
2667
+ ];
2668
+ this.fields = [
2669
+ ...commonFields,
2670
+ {
2671
+ categories: {
2672
+ columnName: 'categories',
2673
+ fields: ['category_id'],
2674
+ bindPersistData: (value) => ({
2675
+ categories: { data: value.map((category) => ({ category_id: +category })) },
2676
+ }),
2677
+ to: (categories) => categories.map((categoryId) => +categoryId),
2678
+ from: (categories) => (categories === null || categories === void 0 ? void 0 : categories.map((category) => { var _a; return (_a = category === null || category === void 0 ? void 0 : category.category_id) === null || _a === void 0 ? void 0 : _a.toString(); })) || [],
2679
+ },
2680
+ },
2681
+ {
2682
+ kitProducts: {
2683
+ columnName: 'kit_products',
2684
+ foreignKeyColumn: { productId: 'id' },
2685
+ fields: [
2686
+ { productId: { columnName: 'product_id' } },
2687
+ { kitProductId: { columnName: 'kit_product_id' } },
2688
+ 'quantity',
2689
+ { product: { columnName: 'product', foreignKeyColumn: { id: 'product_id' }, fields: commonFields } },
2690
+ ],
2691
+ },
2692
+ },
2693
+ ];
2694
+ }
2695
+ get reviewsFields() {
2696
+ return [
2697
+ 'id',
2698
+ 'shop',
2699
+ 'rate',
2700
+ 'author',
2701
+ 'email',
2702
+ 'location',
2703
+ 'review',
2704
+ 'status',
2705
+ 'title',
2706
+ 'person_id',
2707
+ 'points',
2708
+ 'order_id',
2709
+ 'created_at',
2710
+ 'updated_at',
2711
+ ];
2712
+ }
2713
+ create(data) {
2714
+ const _super = Object.create(null, {
2715
+ create: { get: () => super.create }
2716
+ });
2717
+ return __awaiter(this, void 0, void 0, function* () {
2718
+ const product = yield _super.create.call(this, omit(data, ['reviews']));
2719
+ try {
2720
+ product.reviews = yield this.updateReviews(+product.id, data);
2721
+ }
2722
+ catch (error) {
2723
+ yield this.delete({ id: product.id });
2724
+ throw error;
2725
+ }
2726
+ return product;
2727
+ });
2728
+ }
2729
+ get(identifiers) {
2730
+ const _super = Object.create(null, {
2731
+ get: { get: () => super.get }
2732
+ });
2733
+ var _a;
2734
+ return __awaiter(this, void 0, void 0, function* () {
2735
+ const product = Number.isNaN(+identifiers.id)
2736
+ ? (_a = (yield this.find({ filters: { firestoreId: identifiers.id } })).data) === null || _a === void 0 ? void 0 : _a[0]
2737
+ : yield _super.get.call(this, identifiers);
2738
+ product.reviews = yield this.findReviewsByProduct(+product.id);
2739
+ return product;
2740
+ });
2741
+ }
2742
+ find(params) {
2743
+ const _super = Object.create(null, {
2744
+ find: { get: () => super.find }
2745
+ });
2746
+ return __awaiter(this, void 0, void 0, function* () {
2747
+ const _a = params || {}, { filters } = _a, options = __rest(_a, ["filters"]);
2748
+ return _super.find.call(this, Object.assign(Object.assign({}, options), { filters: Object.assign(Object.assign({}, filters), { productId: { operator: Where.ISNULL } }) }));
2749
+ });
2750
+ }
2751
+ getBySlug(slug) {
2752
+ var _a;
2753
+ return __awaiter(this, void 0, void 0, function* () {
2754
+ const result = yield this.find({
2755
+ filters: {
2756
+ slug,
2757
+ },
2758
+ });
2759
+ const product = (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.shift();
2760
+ product.reviews = yield this.findReviewsByProduct(+product.id);
2761
+ return product;
2762
+ });
2763
+ }
2764
+ update(params) {
2765
+ const _super = Object.create(null, {
2766
+ update: { get: () => super.update }
2767
+ });
2768
+ return __awaiter(this, void 0, void 0, function* () {
2769
+ const { categories, kitProducts, reviews, id: checkId, shopAvailability, rate } = params, data = __rest(params, ["categories", "kitProducts", "reviews", "id", "shopAvailability", "rate"]);
2770
+ const plainData = this.paramsToPlain({ id: checkId });
2771
+ const id = yield this.getId(plainData.id);
2772
+ const product = yield _super.update.call(this, Object.assign({ id }, data));
2773
+ product.categories = categories && (yield this.updateCategories(+id, { categories }));
2774
+ product.kitProducts = kitProducts && (yield this.updateKitProducts(+id, { kitProducts }));
2775
+ product.reviews = reviews && (yield this.updateReviews(+id, { reviews }));
2776
+ return product;
2777
+ });
2778
+ }
2779
+ fetchReviews(status) {
2780
+ return __awaiter(this, void 0, void 0, function* () {
2781
+ const reviews = {
2782
+ status: status === 'pending'
2783
+ ? { [HasuraGraphQLWhere.ISNULL]: true }
2784
+ : { [HasuraGraphQLWhere.EQUALS]: status === 'approved' },
2785
+ };
2786
+ const { product: data } = yield this.query('product', ['id', 'name', 'sku', { reviews: { columnName: 'reviews', fields: this.reviewsFields } }], {
2787
+ where: { value: { reviews }, type: 'product_bool_exp', required: true },
2788
+ });
2789
+ return data.reduce((reviews, product) => [
2790
+ ...reviews,
2791
+ ...product.reviews
2792
+ .filter((review) => (status === 'pending' && [undefined, null].includes(review.status)) ||
2793
+ (status === 'approved' && review.status === true) ||
2794
+ (status === 'rejected' && review.status === false))
2795
+ .map((review) => (Object.assign(Object.assign({}, this.bindReviewToModel(review)), { productId: product.id, productName: product.name, productSku: product.sku }))),
2796
+ ], []);
2797
+ });
2798
+ }
2799
+ updateCategories(productId, { categories }) {
2800
+ return __awaiter(this, void 0, void 0, function* () {
2801
+ const plainData = this.paramsToPlain({ categories });
2802
+ yield this.mutation('delete_category_product', ['affected_rows'], {
2803
+ where: {
2804
+ type: 'category_product_bool_exp',
2805
+ required: true,
2806
+ value: { product_id: { _eq: productId } },
2807
+ },
2808
+ });
2809
+ yield this.mutation('insert_category_product', ['affected_rows'], {
2810
+ objects: {
2811
+ type: '[category_product_insert_input!]',
2812
+ required: true,
2813
+ value: plainData.categories.map((categoryId) => ({ category_id: categoryId, product_id: productId })),
2814
+ },
2815
+ });
2816
+ return plainData.categories;
2817
+ });
2818
+ }
2819
+ updateKitProducts(productId, { kitProducts }) {
2820
+ return __awaiter(this, void 0, void 0, function* () {
2821
+ const plainData = this.paramsToPlain({ kitProducts });
2822
+ yield this.mutation('delete_product_kit', ['affected_rows'], {
2823
+ where: {
2824
+ type: 'product_kit_bool_exp',
2825
+ required: true,
2826
+ value: { product_id: { _eq: productId } },
2827
+ },
2828
+ });
2829
+ yield this.mutation('insert_product_kit', ['affected_rows'], {
2830
+ objects: {
2831
+ type: '[product_kit_insert_input!]',
2832
+ required: true,
2833
+ value: plainData.kitProducts.map((kitProduct) => ({
2834
+ kit_product_id: kitProduct.productId || kitProduct.product.id,
2835
+ product_id: productId,
2836
+ quantity: kitProduct.quantity,
2837
+ })),
2838
+ },
2839
+ });
2840
+ return plainData.kitProducts;
2841
+ });
2842
+ }
2843
+ updateReviews(productId, { reviews }) {
2844
+ return __awaiter(this, void 0, void 0, function* () {
2845
+ if (!reviews)
2846
+ return [];
2847
+ if ('action' in reviews && reviews.action === 'remove') {
2848
+ const reviewIds = yield Promise.all(reviews.value.map((reviewData) => __awaiter(this, void 0, void 0, function* () {
2849
+ const review = yield this.findReview(reviewData, productId);
2850
+ return review === null || review === void 0 ? void 0 : review.id;
2851
+ })));
2852
+ yield this.mutation('delete_product_review', ['affected_rows'], {
2853
+ where: { value: { id: { _in: reviewIds.filter(Boolean) } }, type: 'product_review_bool_exp', required: true },
2854
+ });
2855
+ return reviews.value.map((review, index) => !reviewIds[index] && review).filter(Boolean);
2856
+ }
2857
+ const plainData = this.paramsToPlain({ reviews });
2858
+ return Promise.all(plainData.reviews.map((reviewData) => __awaiter(this, void 0, void 0, function* () {
2859
+ const review = yield this.findReview(reviewData, productId);
2860
+ if (review.id)
2861
+ return this.bindReviewToModel((yield this.mutation('update_product_review_by_pk', this.reviewsFields, {
2862
+ pk_columns: {
2863
+ value: { id: review.id },
2864
+ type: 'product_review_pk_columns_input',
2865
+ required: true,
2866
+ },
2867
+ _set: {
2868
+ value: omit(this.bindReviewToHasura(reviewData), ['id', 'product_id']),
2869
+ type: 'product_review_set_input',
2870
+ required: true,
2871
+ },
2872
+ })).update_product_review_by_pk);
2873
+ return this.bindReviewToModel((yield this.mutation('insert_product_review_one', this.reviewsFields, {
2874
+ object: {
2875
+ value: omit(Object.assign(Object.assign({}, this.bindReviewToHasura(reviewData)), { product_id: productId }), ['id']),
2876
+ type: 'product_review_insert_input',
2877
+ required: true,
2878
+ },
2879
+ })).insert_product_review_one);
2880
+ })));
2881
+ });
2882
+ }
2883
+ getId(id) {
2884
+ var _a, _b;
2885
+ return __awaiter(this, void 0, void 0, function* () {
2886
+ if (!Number.isNaN(+id))
2887
+ return id;
2888
+ const { data } = yield this.find({ filters: { firestoreId: id } });
2889
+ if ((_a = data === null || data === void 0 ? void 0 : data[0]) === null || _a === void 0 ? void 0 : _a.id)
2890
+ return (_b = data === null || data === void 0 ? void 0 : data[0]) === null || _b === void 0 ? void 0 : _b.id;
2891
+ throw new NotFoundError(`Product with id ${id} not found`);
2892
+ });
2893
+ }
2894
+ findReviewsByProduct(productId) {
2895
+ return __awaiter(this, void 0, void 0, function* () {
2896
+ const { product_review: data } = yield this.query('product_review', this.reviewsFields, {
2897
+ where: {
2898
+ value: {
2899
+ product_id: { _eq: productId },
2900
+ },
2901
+ type: 'product_review_bool_exp',
2902
+ required: true,
2903
+ },
2904
+ });
2905
+ return data && data.map((review) => this.bindReviewToModel(review));
2906
+ });
2907
+ }
2908
+ findReview(review, productId) {
2909
+ return __awaiter(this, void 0, void 0, function* () {
2910
+ if (review.id)
2911
+ return review;
2912
+ let loadedReview;
2913
+ if (review.personId)
2914
+ loadedReview = yield this.getReviewByPersonId(review.personId, productId);
2915
+ if (!loadedReview && review.author && review.email)
2916
+ loadedReview = yield this.getReviewByAuthorAndEmail(review.author, review.email, productId);
2917
+ return loadedReview || review;
2918
+ });
2919
+ }
2920
+ getReviewByPersonId(personId, productId) {
2921
+ return __awaiter(this, void 0, void 0, function* () {
2922
+ const { product_review: data } = yield this.query('product_review', this.reviewsFields, {
2923
+ where: {
2924
+ value: {
2925
+ product_id: { _eq: productId },
2926
+ person_id: { _eq: personId },
2927
+ },
2928
+ type: `product_review_bool_exp`,
2929
+ required: true,
2930
+ },
2931
+ });
2932
+ return data && data[0] && this.bindReviewToModel(data[0]);
2933
+ });
2934
+ }
2935
+ getReviewByAuthorAndEmail(author, email, productId) {
2936
+ return __awaiter(this, void 0, void 0, function* () {
2937
+ const { product_review: data } = yield this.query('product_review', this.reviewsFields, {
2938
+ where: {
2939
+ value: {
2940
+ product_id: { _eq: productId },
2941
+ author: { _eq: author },
2942
+ email: { _eq: email },
2943
+ },
2944
+ type: `product_review_bool_exp`,
2945
+ required: true,
2946
+ },
2947
+ });
2948
+ return data && data[0] && this.bindReviewToModel(data[0]);
2949
+ });
2950
+ }
2951
+ }
2952
+
2953
+ class VariantHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGraphQL(Base)) {
2954
+ constructor(endpoint, authOptions) {
2955
+ super({
2956
+ tableName: 'product',
2957
+ model: VariantHasuraGraphQL,
2335
2958
  endpoint,
2336
2959
  authOptions,
2337
2960
  fields: [
2338
2961
  { id: { columnName: 'id', to: (value) => +value, from: (value) => value.toString() } },
2339
- { CEST: { columnName: 'cest' } },
2962
+ { firestoreId: { columnName: 'firestore_id' } },
2963
+ { productId: { columnName: 'main_product_id', to: (value) => +value, from: (value) => value === null || value === void 0 ? void 0 : value.toString() } },
2340
2964
  { EAN: { columnName: 'ean' } },
2341
- { NCM: { columnName: 'ncm' } },
2342
- 'brand',
2343
2965
  { costPrice: { columnName: 'cost_price' } },
2344
- 'description',
2345
- { hasVariants: { columnName: 'has_variants' } },
2346
- 'images',
2347
- 'miniatures',
2348
- 'name',
2349
- { price: { columnName: 'full_price' } },
2350
- { price: { columnName: 'subscriber_discount_percentage' } },
2351
- { price: { columnName: 'subscriber_price' } },
2352
2966
  {
2353
2967
  price: {
2354
2968
  columnName: 'price',
@@ -2358,52 +2972,89 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
2358
2972
  subscriberDiscountPercentage: data.subscriber_discount_percentage,
2359
2973
  subscriberPrice: data.subscriber_price,
2360
2974
  } })), {}),
2975
+ bindFindFilter: (sentence) => {
2976
+ const filters = Object.values(sentence).shift();
2977
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, (((filters === null || filters === void 0 ? void 0 : filters.price) || (filters === null || filters === void 0 ? void 0 : filters.price) === 0) && { price: filters.price })), ((filters.fullPrice || filters.fullPrice === 0) && { full_price: filters.fullPrice })), ((filters.subscriberDiscountPercentage || filters.subscriberDiscountPercentage === 0) && {
2978
+ subscriber_discount_percentage: filters.subscriberDiscountPercentage,
2979
+ })), ((filters.subscriberPrice || filters.subscriberPrice === 0) && {
2980
+ subscriber_price: filters.subscriberPrice,
2981
+ }));
2982
+ },
2983
+ bindPersistData: (value) => {
2984
+ const priceData = Object.values(value).shift();
2985
+ return Object.assign(Object.assign(Object.assign(Object.assign({}, ((priceData === null || priceData === void 0 ? void 0 : priceData.price) >= 0 && { price: priceData.price })), (priceData.fullPrice >= 0 && { full_price: priceData.fullPrice })), (priceData.subscriberDiscountPercentage >= 0 && {
2986
+ subscriber_discount_percentage: priceData.subscriberDiscountPercentage,
2987
+ })), (priceData.subscriberPrice >= 0 && { subscriber_price: priceData.subscriberPrice }));
2988
+ },
2361
2989
  },
2362
2990
  },
2363
- 'published',
2364
- { publishedGlam: { columnName: 'published_glam' } },
2991
+ { fullPrice: { columnName: 'full_price' } },
2992
+ { subscriberDiscountPercentage: { columnName: 'subscriber_discount_percentage' } },
2993
+ { subscriberPrice: { columnName: 'subscriber_price' } },
2365
2994
  'sku',
2366
2995
  {
2367
2996
  stock: {
2368
2997
  columnName: 'stock',
2369
2998
  from: (quantity) => ({ quantity }),
2370
- to: (value) => (value === null || value === void 0 ? void 0 : value.quantity) || value,
2999
+ to: (value) => (isNil(value === null || value === void 0 ? void 0 : value.quantity) ? value : value === null || value === void 0 ? void 0 : value.quantity),
2371
3000
  },
2372
3001
  },
2373
- 'type',
2374
- 'video',
2375
3002
  'weight',
3003
+ { name: { to: () => '', from: () => undefined } },
3004
+ { hasVariants: { columnName: 'has_variants', to: () => false, from: () => undefined } },
3005
+ { createdAt: { columnName: 'created_at' } },
3006
+ { updatedAt: { columnName: 'updated_at' } },
2376
3007
  {
2377
- categories: {
2378
- columnName: 'categories',
2379
- fields: ['category_id'],
2380
- to: (category_id) => +category_id,
2381
- from: (categories) => (categories === null || categories === void 0 ? void 0 : categories.map((category) => { var _a; return (_a = category === null || category === void 0 ? void 0 : category.category_id) === null || _a === void 0 ? void 0 : _a.toString(); })) || [],
2382
- },
2383
- },
2384
- {
2385
- shopAvailability: {
2386
- columnName: 'shop_availabilities',
2387
- fields: ['shop'],
2388
- from: (shop) => (Array.isArray(shop) ? shop.map((row) => row.shop) : []),
3008
+ grade: {
3009
+ columnName: 'grade',
3010
+ type: HasuraGraphQLColumnType.Jsonb,
2389
3011
  },
2390
3012
  },
2391
- { tags: { columnName: 'tags', type: HasuraGraphQLColumnType.Jsonb } },
2392
- { createdAt: { columnName: 'created_at' } },
2393
- { updatedAt: { columnName: 'updated_at' } },
2394
3013
  ],
2395
3014
  });
2396
3015
  }
2397
- getBySlug(slug, shop) {
3016
+ get(identifiers) {
3017
+ const _super = Object.create(null, {
3018
+ get: { get: () => super.get }
3019
+ });
2398
3020
  var _a;
2399
3021
  return __awaiter(this, void 0, void 0, function* () {
2400
- const result = yield this.find({
2401
- filters: {
2402
- slug: { operator: Where.EQUALS, value: slug },
2403
- shopAvailability: { operator: Where.IN, value: [shop] },
2404
- },
2405
- });
2406
- return (_a = result === null || result === void 0 ? void 0 : result.data) === null || _a === void 0 ? void 0 : _a.shift();
3022
+ return Number.isNaN(+identifiers.id)
3023
+ ? (_a = (yield this.find({ filters: { firestoreId: identifiers.id } })).data) === null || _a === void 0 ? void 0 : _a[0]
3024
+ : _super.get.call(this, identifiers);
3025
+ });
3026
+ }
3027
+ find(params) {
3028
+ const _super = Object.create(null, {
3029
+ find: { get: () => super.find }
3030
+ });
3031
+ return __awaiter(this, void 0, void 0, function* () {
3032
+ const _a = params || {}, { filters } = _a, options = __rest(_a, ["filters"]);
3033
+ return _super.find.call(this, Object.assign(Object.assign({}, options), { filters: Object.assign(Object.assign({}, filters), { productId: { operator: Where.ISNOTNULL } }) }));
3034
+ });
3035
+ }
3036
+ update(params) {
3037
+ const _super = Object.create(null, {
3038
+ update: { get: () => super.update }
3039
+ });
3040
+ return __awaiter(this, void 0, void 0, function* () {
3041
+ const { productId, id: checkId } = params, data = __rest(params, ["productId", "id"]);
3042
+ const dataWithProductId = this.paramsToPlain({ id: checkId, productId });
3043
+ const id = yield this.getId(dataWithProductId.id);
3044
+ const product = yield _super.update.call(this, Object.assign({ id }, data));
3045
+ product.productId = dataWithProductId.productId;
3046
+ return product;
3047
+ });
3048
+ }
3049
+ getId(id) {
3050
+ var _a, _b;
3051
+ return __awaiter(this, void 0, void 0, function* () {
3052
+ if (!Number.isNaN(+id))
3053
+ return id;
3054
+ const { data } = yield this.find({ filters: { firestoreId: id } });
3055
+ if ((_a = data === null || data === void 0 ? void 0 : data[0]) === null || _a === void 0 ? void 0 : _a.id)
3056
+ return (_b = data === null || data === void 0 ? void 0 : data[0]) === null || _b === void 0 ? void 0 : _b.id;
3057
+ throw new NotFoundError(`Product with id ${id} not found`);
2407
3058
  });
2408
3059
  }
2409
3060
  }
@@ -2412,5 +3063,5 @@ class ProductHasuraGraphQLRepository extends withCrudHasuraGraphQL(withHasuraGra
2412
3063
  * Generated bundle index. Do not edit.
2413
3064
  */
2414
3065
 
2415
- export { AccessoryImportances, Address, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, Buy2Win, Buy2WinFirestoreRepository, Category, CategoryFirestoreRepository, CategoryHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, Coupon, CouponFirestoreRepository, CouponSubtypes, CouponTypes, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, FilterType, FinancialCoupon, FragranceImportances, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, NotFoundError, OfficePosition, Order, OrderFirestoreRepository, OrderStatus, Payment, PaymentFirestoreRepository, PaymentType, Product, ProductFirestoreRepository, ProductHasuraGraphQLRepository, ProductSpents, ProductVariantFirestoreRepository, ProductsIndex, QuestionsFilters, RecoveryPassword, Register, RegisterFirebaseAuthService, RequiredArgumentError, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, Shops, SignInMethods, SignOut, Status, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, UnauthorizedError, UpdateOptionActions, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserSearchFirestoreRepository, UserType, Variant, WeakPasswordError, Where, isUUID, parseDateTime, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
3066
+ export { AccessoryImportances, Address, Area, Authentication, AuthenticationFirebaseAuthService, AxiosAdapter, Base, BaseModel, BeardProblems, BeardSizes, BeautyProductImportances, BeautyProfile, BeautyQuestionsHelper, BillingStatus, BodyProblems, BodyShapes, BodyTattoos, Buy2Win, Buy2WinFirestoreRepository, Category, CategoryFirestoreRepository, CategoryHasuraGraphQL, CategoryHasuraGraphQLRepository, Checkout, CheckoutFirestoreRepository, CheckoutSubscription, CheckoutSubscriptionFirestoreRepository, CheckoutTypes, Coupon, CouponFirestoreRepository, CouponSubtypes, CouponTypes, DuplicatedResultsError, Edition, EditionStatus, Exclusivities, FaceSkinOilinesses, FaceSkinProblems, FaceSkinTones, FamilyIncomes, FilterType, FinancialCoupon, FragranceImportances, HairColors, HairProblems, HairStrands, HairTypes, Home, HomeFirestoreRepository, InvalidArgumentError, KitProduct, KitProductHasuraGraphQL, Lead, LeadFirestoreRepository, LegacyOrderFirestoreRepository, LineItem, NotFoundError, OfficePosition, Order, OrderFirestoreRepository, OrderStatus, Payment, PaymentFirestoreRepository, PaymentType, Product, ProductFirestoreRepository, ProductHasuraGraphQL, ProductHasuraGraphQLRepository, ProductSpents, ProductVariantFirestoreRepository, ProductsIndex, QuestionsFilters, RecoveryPassword, Register, RegisterFirebaseAuthService, RequiredArgumentError, ShippingMethod, ShopMenu, ShopMenuFirestoreRepository, Shops, SignInMethods, SignOut, Status, Subscription, SubscriptionEditionFirestoreRepository, SubscriptionFirestoreRepository, SubscriptionPayment, SubscriptionPaymentFirestoreRepository, SubscriptionPlan, SubscriptionPlanFirestoreRepository, SubscriptionProductFirestoreRepository, UnauthorizedError, UpdateOptionActions, User, UserAddress, UserAddressFirestoreRepository, UserAlreadyRegisteredError, UserBeautyProfileFirestoreRepository, UserFirestoreRepository, UserPaymentMethod, UserPaymentMethodFirestoreRepository, UserSearchFirestoreRepository, UserType, Variant, VariantHasuraGraphQL, VariantHasuraGraphQLRepository, WeakPasswordError, Where, isUUID, parseDateTime, withCreateFirestore, withCreateHasuraGraphQL, withCrudFirestore, withCrudHasuraGraphQL, withDeleteFirestore, withDeleteHasuraGraphQL, withFindFirestore, withFindHasuraGraphQL, withFirestore, withGetFirestore, withGetHasuraGraphQL, withHasuraGraphQL, withHelpers, withSubCollection, withUpdateFirestore, withUpdateHasuraGraphQL };
2416
3067
  //# sourceMappingURL=infrab4a-connect.js.map