-
Notifications
You must be signed in to change notification settings - Fork 4
/
product.go
1043 lines (881 loc) · 31.1 KB
/
product.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package product
// DefaultProduct type implements:
// - InterfaceProduct
// - InterfaceModel
// - InterfaceObject
// - InterfaceStorable
// - InterfaceListable
// - InterfaceMedia
import (
"fmt"
"sort"
"strings"
"github.com/ottemo/commerce/app/helpers/attributes"
"github.com/ottemo/commerce/db"
"github.com/ottemo/commerce/env"
"github.com/ottemo/commerce/media"
"github.com/ottemo/commerce/utils"
"github.com/ottemo/commerce/app/models"
"github.com/ottemo/commerce/app/models/product"
)
// ---------------------------------------------------------------------------------
// InterfaceModel implementation (package "github.com/ottemo/commerce/app/models")
// ---------------------------------------------------------------------------------
// GetModelName returns model name
func (it *DefaultProduct) GetModelName() string {
return product.ConstModelNameProduct
}
// GetImplementationName returns model implementation name
func (it *DefaultProduct) GetImplementationName() string {
return "Default" + product.ConstModelNameProduct
}
// New returns new instance of model implementation object
func (it *DefaultProduct) New() (models.InterfaceModel, error) {
newInstance := new(DefaultProduct)
customAttributes, err := attributes.CustomAttributes(product.ConstModelNameProduct, ConstCollectionNameProduct)
if err != nil {
return nil, env.ErrorDispatch(err)
}
newInstance.customAttributes = customAttributes
externalAttributes, err := attributes.ExternalAttributes(newInstance)
if err != nil {
return nil, env.ErrorDispatch(err)
}
newInstance.externalAttributes = externalAttributes
return newInstance, nil
}
// -------------------------------------------------------------------------------------------
// InterfaceProduct implementation (package "github.com/ottemo/commerce/app/models/product")
// -------------------------------------------------------------------------------------------
// GetEnabled returns enabled flag for the given product
func (it *DefaultProduct) GetEnabled() bool {
return it.Enabled
}
// GetSku returns requested sku for the given product
func (it *DefaultProduct) GetSku() string {
return it.Sku
}
// GetName returns the name of the given product
func (it *DefaultProduct) GetName() string {
return it.Name
}
// GetShortDescription returns the short description of the requested product
func (it *DefaultProduct) GetShortDescription() string {
return it.ShortDescription
}
// GetDescription returns the long description of the requested product
func (it *DefaultProduct) GetDescription() string {
return it.Description
}
// GetDefaultImage returns the imaged identified as defult for the given product
func (it *DefaultProduct) GetDefaultImage() string {
return it.DefaultImage
}
// GetPrice returns the price as a float64 for the given product
func (it *DefaultProduct) GetPrice() float64 {
return it.Price
}
// GetWeight returns the weight for the given product
func (it *DefaultProduct) GetWeight() float64 {
return it.Weight
}
// GetOptions returns current products possible options as a map[string]interface{}
func (it *DefaultProduct) GetOptions() map[string]interface{} {
options := it.Options
eventData := map[string]interface{}{"id": it.GetID(), "product": it, "options": options}
env.Event("product.getOptions", eventData)
return options
}
// GetRelatedProductIds returns the related product id list
func (it *DefaultProduct) GetRelatedProductIds() []string {
return it.RelatedProductIds
}
// GetRelatedProducts returns related products instances list
func (it *DefaultProduct) GetRelatedProducts() []product.InterfaceProduct {
var result []product.InterfaceProduct
for _, productID := range it.RelatedProductIds {
if productID == "" {
continue
}
productModel, err := product.LoadProductByID(productID)
if err == nil {
result = append(result, productModel)
}
}
return result
}
// GetAppliedOptions returns applied options for current product instance
func (it *DefaultProduct) GetAppliedOptions() map[string]interface{} {
if it.appliedOptions != nil {
return it.appliedOptions
}
return make(map[string]interface{})
}
// ApplyOptions updates current product attributes according to given product options,
// returns error if specified option are not possible for the product
func (it *DefaultProduct) ApplyOptions(options map[string]interface{}) error {
// taking item specified options and product options
productOptions := it.GetOptions()
// storing start price for a case of percentage price modifier
var startPrice = it.GetPrice()
var selectedProductIDs []string
var storedImageName string
var foundOptions []string
for itemOptionName := range options {
// get product option (color, size, etc)
productOption, ok := productOptions[itemOptionName]
if !ok {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "5b7d5166-f687-4c65-b109-5c2cee27e3f5", "unknown option '"+itemOptionName+"'")
}
productOptionHashMap, ok := productOption.(map[string]interface{})
if !ok {
continue
}
// check receiver have options (color:{options:...})
optionOptions, ok := productOptionHashMap["options"]
if !ok {
continue
}
optionOptionsHashMap, ok := optionOptions.(map[string]interface{})
if !ok {
continue
}
if productOptionHashMap["type"] == "multi_select" {
continue
}
// check single value (color:{options:{red:{...}}})
itemOptionValue := utils.InterfaceToString(options[itemOptionName])
optionOptionsItem, present := optionOptionsHashMap[itemOptionValue]
if !present {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "11b4cf1b-2324-4ed1-b592-32bd66b751e4", "invalid '"+itemOptionName+"' option value: '"+itemOptionValue)
}
optionOptionsItemHashMap, ok := optionOptionsItem.(map[string]interface{})
if !ok {
continue
}
// check option product IDs (color:{options:{red:{product_ids:"1,2,3", ...}}})
productIDsHashMap, present := optionOptionsItemHashMap[product.ConstOptionProductIDs]
if !present {
continue
}
foundOptions = append(foundOptions, itemOptionName)
if newImageName, present := optionOptionsItemHashMap[product.ConstOptionImageName]; present {
storedImageName = utils.InterfaceToString(newImageName)
}
// filter selected product ids by current option product ids
productIDs := utils.InterfaceToStringArray(productIDsHashMap)
if len(selectedProductIDs) == 0 {
// initialization
selectedProductIDs = productIDs
} else {
// filtering
var newProductIDs []string
for _, productID := range productIDs {
if utils.IsInArray(productID, selectedProductIDs) {
newProductIDs = append(newProductIDs, productID)
}
}
selectedProductIDs = newProductIDs
}
// cleaning option values were not used by customer
for optionOptionsItemName := range optionOptionsHashMap {
if optionOptionsItemName != itemOptionValue {
delete(optionOptionsHashMap, optionOptionsItemName)
}
}
}
var optionsWithoutSimpleIds = make(map[string]interface{})
var isSimpleProductUsed = false
// if options with simple product ids found
if len(foundOptions) > 0 {
if len(selectedProductIDs) < 1 {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "2ae359d4-36b8-4182-bb12-c302938b28ad", "no product specified for selected options")
} else if len(selectedProductIDs) > 1 {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "6e356239-5d7e-42a8-8392-b97c80e56fda", "more than one product specified for selected options")
} else {
var storedOptions = it.GetOptions();
var storedID = it.GetID()
if len(storedImageName) == 0 {
storedImageName = it.GetDefaultImage()
}
// replace configurable product with simple product
if err := it.Load(selectedProductIDs[0]); err != nil {
return env.ErrorDispatch(err)
}
// use configurable ID and options
if err := it.SetID(storedID); err != nil {
return env.ErrorDispatch(err)
}
if err := it.Set("options", storedOptions); err != nil {
return env.ErrorDispatch(err)
}
if err := it.Set("default_image", storedImageName); err != nil {
return env.ErrorDispatch(err)
}
isSimpleProductUsed = true
}
}
// filter already processed options
for optionName, optionValue := range options {
if !utils.IsInArray(optionName, foundOptions) {
optionsWithoutSimpleIds[optionName] = optionValue
}
}
// sorting applicable product attributes according to "order" field
// optionsApplyOrder := make([]string, 0)
var optionsApplyOrder []string
for itemOptionName := range optionsWithoutSimpleIds {
// options already filtered by product options
productOption := productOptions[itemOptionName].(map[string]interface{})
orderValue := int(^uint(0) >> 1) // default order - max integer
if optionValue, present := productOption["order"]; present {
orderValue = utils.InterfaceToInt(optionValue)
}
// encoding key order to string "000000000000001 [attribute name]"
// for future sort as string (16 digits - max for js integer)
key := fmt.Sprintf("%.16d %s", orderValue, itemOptionName)
optionsApplyOrder = append(optionsApplyOrder, key)
}
sort.Strings(optionsApplyOrder)
// function to modify orderItem according to option values
applyOptionModifiers := func(optionToApply map[string]interface{}) {
// price modifier
if optionValue, present := optionToApply["price"]; present {
if stringValue, ok := optionValue.(string); ok {
if stringValue != "" && strings.Trim(stringValue, "1234567890+-%.") == "" {
isDelta := false
isPercent := false
stringValue = strings.TrimSpace(stringValue)
if strings.HasSuffix(stringValue, "%") {
isPercent = true
stringValue = strings.TrimSuffix(stringValue, "%")
}
var priceValue float64
switch {
case strings.HasPrefix(stringValue, "+"):
stringValue = strings.TrimPrefix(stringValue, "+")
isDelta = true
priceValue = utils.InterfaceToFloat64(stringValue)
case strings.HasPrefix(stringValue, "-"):
stringValue = strings.TrimPrefix(stringValue, "-")
isDelta = true
priceValue = -1 * utils.InterfaceToFloat64(stringValue)
default:
priceValue = utils.InterfaceToFloat64(stringValue)
}
if isPercent {
it.Price += startPrice * priceValue / 100
} else if isDelta {
it.Price += priceValue
} else {
it.Price = priceValue
}
}
} else {
if err := it.Set("price", optionValue); err != nil {
_ = env.ErrorNew(ConstErrorModule, ConstErrorLevel, "016da6e7-5489-49d7-a8fb-14f3733398be", err.Error())
}
}
}
// sku modifier
if optionValue, present := optionToApply["sku"]; present {
skuModifier := utils.InterfaceToString(optionValue)
if strings.HasPrefix(skuModifier, "-") || strings.HasPrefix(skuModifier, "_") {
it.Sku += skuModifier
} else {
it.Sku = skuModifier
}
}
}
// loop over item applied option in right order
for _, itemOptionNameKey := range optionsApplyOrder {
itemOptionName := itemOptionNameKey[strings.Index(itemOptionNameKey, " ")+1:]
itemOptionValue := options[itemOptionName]
// options already filtered by product options
// get product option (color, size, etc)
productOptions := productOptions[itemOptionName].(map[string]interface{})
// product option itself can contain price, sku modifiers
if !isSimpleProductUsed {
applyOptionModifiers(productOptions)
}
// if product option value have predefined option values, then checking their modifiers
if productOptionValues, present := productOptions["options"]; present {
if productOptionValues, ok := productOptionValues.(map[string]interface{}); ok {
// option user set can be single on multi-value
// making it uniform
// itemOptionValueSet := make([]string, 0)
var itemOptionValueSet []string
switch typedOptionValue := itemOptionValue.(type) {
case string:
itemOptionValueSet = append(itemOptionValueSet, typedOptionValue)
case []string:
itemOptionValueSet = typedOptionValue
case []interface{}:
for _, value := range typedOptionValue {
if value, ok := value.(string); ok {
itemOptionValueSet = append(itemOptionValueSet, value)
}
}
default:
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "6d02be30-ca5e-46e4-94c7-2f01782f30b2", "unexpected option value for "+itemOptionName+" option")
}
// loop through option values customer set for product
if !isSimpleProductUsed {
for _, itemOptionValue := range itemOptionValueSet {
var productOptionValue = productOptionValues[itemOptionValue].(map[string]interface{})
applyOptionModifiers(productOptionValue)
}
}
// cleaning option values were not used by customer
for productOptionValueName := range productOptionValues {
if !utils.IsInArray(productOptionValueName, itemOptionValueSet) {
delete(productOptionValues, productOptionValueName)
}
}
}
}
}
// cleaning options were not used by customer
for productOptionName, productOption := range productOptions {
if _, present := options[productOptionName]; present {
if productOption, ok := productOption.(map[string]interface{}); ok {
productOption["value"] = options[productOptionName]
}
} else {
delete(productOptions, productOptionName)
}
}
it.Price = utils.RoundPrice(it.Price)
it.appliedOptions = options
if !isSimpleProductUsed {
err := it.LoadExternalAttributes();
if err != nil {
return env.ErrorDispatch(err)
}
}
return nil
}
// LoadExternalAttributes loads external attributes from storage
func (it *DefaultProduct) LoadExternalAttributes() error {
err := it.externalAttributes.Load(it.GetID())
if err != nil {
return env.ErrorDispatch(err)
}
return nil
}
// ----------------------------------------------------------------------------------
// InterfaceObject implementation (package "github.com/ottemo/commerce/app/models")
// ----------------------------------------------------------------------------------
// Get returns an object attribute value or nil
func (it *DefaultProduct) Get(attribute string) interface{} {
if _, present := it.externalAttributes.ListExternalAttributes()[attribute]; present {
return it.externalAttributes.Get(attribute)
}
switch strings.ToLower(attribute) {
case "_id", "id":
return it.id
case "enable", "enabled":
return it.Enabled
case "sku":
return it.Sku
case "name":
return it.Name
case "short_description":
return it.ShortDescription
case "description":
return it.Description
case "default_image", "defaultimage":
return it.DefaultImage
case "price":
return it.Price
case "weight":
return it.Weight
case "options":
return it.GetOptions()
case "related_pids":
return it.GetRelatedProductIds()
case "visible":
return it.Visible
}
return it.customAttributes.Get(attribute)
}
// Set will apply the given attribute value to the product or return an error
func (it *DefaultProduct) Set(attribute string, value interface{}) error {
lowerCaseAttribute := strings.ToLower(attribute)
if _, present := it.externalAttributes.ListExternalAttributes()[lowerCaseAttribute]; present {
if err := it.externalAttributes.Set(lowerCaseAttribute, value); err != nil {
return env.ErrorDispatch(err)
}
return nil
}
switch lowerCaseAttribute {
case "_id", "id":
it.id = utils.InterfaceToString(value)
case "enable", "enabled":
it.Enabled = utils.InterfaceToBool(value)
case "sku":
it.Sku = utils.InterfaceToString(value)
case "name":
it.Name = utils.InterfaceToString(value)
case "short_description":
it.ShortDescription = utils.InterfaceToString(value)
case "description":
it.Description = utils.InterfaceToString(value)
case "default_image", "defaultimage":
it.DefaultImage = utils.InterfaceToString(value)
case "price":
it.Price = utils.InterfaceToFloat64(value)
case "weight":
it.Weight = utils.InterfaceToFloat64(value)
case "options":
it.Options = utils.InterfaceToMap(value)
case "visible":
it.Visible = utils.InterfaceToBool(value)
case "related_pids":
it.RelatedProductIds = make([]string, 0)
switch typedValue := value.(type) {
case []product.InterfaceProduct:
for _, productItem := range typedValue {
it.RelatedProductIds = append(it.RelatedProductIds, productItem.GetID())
}
case []interface{}:
for _, listItem := range typedValue {
var relatedProductIDs []string
currentProductID := it.GetID()
if relatedProductID, ok := listItem.(string); ok &&
relatedProductID != "" &&
currentProductID != relatedProductID {
relatedProductIDs = append(relatedProductIDs, relatedProductID)
}
// checking related products existence
dbCollection, err := db.GetCollection(ConstCollectionNameProduct)
if err != nil {
return env.ErrorDispatch(err)
}
err = dbCollection.AddFilter("_id", "in", relatedProductIDs)
if err != nil {
return env.ErrorDispatch(err)
}
err = dbCollection.SetResultColumns("_id")
if err != nil {
return env.ErrorDispatch(err)
}
records, err := dbCollection.Load()
if err != nil {
return env.ErrorDispatch(err)
}
// adding only exist products to model
for _, record := range records {
productID := utils.InterfaceToString(record["_id"])
it.RelatedProductIds = append(it.RelatedProductIds, productID)
}
}
default:
if value != nil {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "3c402ecc-7c7d-49ab-879e-16af5f4661ed", "unsupported 'related_pids' attribute value")
}
}
default:
err := it.customAttributes.Set(attribute, value)
if err != nil {
return env.ErrorDispatch(err)
}
}
return nil
}
// FromHashMap will populate object attributes from map[string]interface{}
func (it *DefaultProduct) FromHashMap(input map[string]interface{}) error {
for attribute, value := range input {
if err := it.Set(attribute, value); err != nil {
env.LogError(err)
}
}
return nil
}
// ToHashMap returns a map[string]interface{}
func (it *DefaultProduct) ToHashMap() map[string]interface{} {
result := it.customAttributes.ToHashMap()
result["_id"] = it.id
result["enabled"] = it.Enabled
result["sku"] = it.Sku
result["name"] = it.Name
result["short_description"] = it.ShortDescription
result["description"] = it.Description
result["default_image"] = it.DefaultImage
result["price"] = it.Price
result["weight"] = it.Weight
result["options"] = it.GetOptions()
result["visible"] = it.Visible
result["related_pids"] = it.Get("related_pids")
for key, value := range it.externalAttributes.ToHashMap() {
result[key] = value
}
return result
}
// GetAttributesInfo returns the requested object attributes
func (it *DefaultProduct) GetAttributesInfo() []models.StructAttributeInfo {
result := []models.StructAttributeInfo{
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "_id",
Type: db.ConstTypeID,
IsRequired: false,
IsStatic: true,
Label: "ID",
Group: "General",
Editors: "not_editable",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "enabled",
Type: db.ConstTypeBoolean,
IsRequired: true,
IsStatic: true,
Label: "Enabled",
Group: "General",
Editors: "boolean",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "sku",
Type: db.ConstTypeVarchar,
IsRequired: true,
IsStatic: true,
Label: "SKU",
Group: "General",
Editors: "line_text",
Options: "",
Default: "",
Validators: "sku",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "name",
Type: db.ConstTypeVarchar,
IsRequired: true,
IsStatic: true,
Label: "Name",
Group: "General",
Editors: "line_text",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "short_description",
Type: db.ConstTypeVarchar,
IsRequired: false,
IsStatic: true,
Label: "Short Description",
Group: "General",
Editors: "multiline_text",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "description",
Type: db.ConstTypeText,
IsRequired: false,
IsStatic: true,
Label: "Description",
Group: "General",
Editors: "multiline_text",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "default_image",
Type: db.ConstTypeVarchar,
IsRequired: false,
IsStatic: true,
Label: "DefaultImage",
Group: "General",
Editors: "image_selector",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "price",
Type: db.ConstTypeMoney,
IsRequired: true,
IsStatic: true,
Label: "Price",
Group: "General",
Editors: "price",
Options: "",
Default: "",
Validators: "price",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "weight",
Type: db.ConstTypeDecimal,
IsRequired: true,
IsStatic: true,
Label: "Weight",
Group: "General",
Editors: "numeric",
Options: "",
Default: "",
Validators: "numeric positive",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "options",
Type: db.ConstTypeJSON,
IsRequired: false,
IsStatic: true,
Label: "Options",
Group: "Options",
Editors: "product_options",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "related_pids",
Type: db.TypeArrayOf(db.ConstTypeInteger),
IsRequired: false,
IsStatic: true,
Label: "Related Products",
Group: "General",
Editors: "products_selector",
Options: "",
Default: "",
},
models.StructAttributeInfo{
Model: product.ConstModelNameProduct,
Collection: ConstCollectionNameProduct,
Attribute: "visible",
Type: db.ConstTypeBoolean,
IsRequired: false,
IsStatic: true,
Label: "Visible",
Group: "General",
Editors: "boolean",
Options: "",
Default: "true",
},
}
customAttributesInfo := it.customAttributes.GetAttributesInfo()
for _, customAttribute := range customAttributesInfo {
result = append(result, customAttribute)
}
externalAttributesInfo := it.externalAttributes.GetAttributesInfo()
for _, externalAttribute := range externalAttributesInfo {
result = append(result, externalAttribute)
}
return result
}
// ------------------------------------------------------------------------------------
// InterfaceStorable implementation (package "github.com/ottemo/commerce/app/models")
// ------------------------------------------------------------------------------------
// GetID returns current product id
func (it *DefaultProduct) GetID() string {
return it.id
}
// SetID sets current product id
func (it *DefaultProduct) SetID(id string) error {
it.id = id
return it.externalAttributes.SetID(id)
}
// Load loads product information from DB
func (it *DefaultProduct) Load(id string) error {
collection, err := db.GetCollection(ConstCollectionNameProduct)
if err != nil {
return env.ErrorDispatch(err)
}
dbRecord, err := collection.LoadByID(id)
if err != nil {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "a671dee4-b95b-11e5-a86b-28cfe917b6c7", "Unable to find product by id; "+id)
}
err = it.FromHashMap(dbRecord)
if err != nil {
return env.ErrorDispatch(err)
}
err = it.LoadExternalAttributes()
if err != nil {
return env.ErrorDispatch(err)
}
return nil
}
// Delete removes current product from DB
func (it *DefaultProduct) Delete() error {
collection, err := db.GetCollection(ConstCollectionNameProduct)
if err != nil {
return env.ErrorDispatch(err)
}
err = collection.DeleteByID(it.GetID())
if err != nil {
return env.ErrorDispatch(err)
}
err = it.externalAttributes.Delete()
if err != nil {
return env.ErrorDispatch(err)
}
return nil
}
// Save stores current product to DB
func (it *DefaultProduct) Save() error {
collection, err := db.GetCollection(ConstCollectionNameProduct)
if err != nil {
return env.ErrorDispatch(err)
}
if it.GetName() == "" || it.GetSku() == "" {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "ac7cd02e-0722-4ac8-bbe0-ffa74d091a94", "sku and name should be specified")
}
valuesToStore := it.ToHashMap()
for x := range it.externalAttributes.ListExternalAttributes() {
delete(valuesToStore, x)
}
newID, err := collection.Save(valuesToStore)
if err != nil {
return env.ErrorDispatch(err)
}
// set new ID before saving external attributes, because external attributes requires it
err = it.SetID(newID)
if err != nil {
return env.ErrorDispatch(err)
}
err = it.externalAttributes.Save()
if err != nil {
return env.ErrorDispatch(err)
}
return nil
}
// ------------------------------------------------------------------------------------
// InterfaceListable implementation (package "github.com/ottemo/commerce/app/models")
// ------------------------------------------------------------------------------------
// GetCollection returns collection of current instance type
func (it *DefaultProduct) GetCollection() models.InterfaceCollection {
model, _ := models.GetModel(product.ConstModelNameProductCollection)
if result, ok := model.(product.InterfaceProductCollection); ok {
return result
}
return nil
}
// ---------------------------------------------------------------------------------
// InterfaceMedia implementation (package "github.com/ottemo/commerce/app/models")
// ---------------------------------------------------------------------------------
// AddMedia adds new media assigned to product
func (it *DefaultProduct) AddMedia(mediaType string, mediaName string, content []byte) error {
productID := it.GetID()
if productID == "" {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "85650715-3acf-4e47-a365-c6e8911d9118", "product id not set")
}
mediaStorage, err := media.GetMediaStorage()
if err != nil {
return env.ErrorDispatch(err)
}
return mediaStorage.Save(it.GetModelName(), productID, mediaType, mediaName, content)
}
// RemoveMedia removes media assigned to product
func (it *DefaultProduct) RemoveMedia(mediaType string, mediaName string) error {
productID := it.GetID()
if productID == "" {
return env.ErrorNew(ConstErrorModule, ConstErrorLevel, "87bb383a-cf35-48e0-9d50-ad517ed2e8f9", "product id not set")
}
mediaStorage, err := media.GetMediaStorage()
if err != nil {
return env.ErrorDispatch(err)
}
return mediaStorage.Remove(it.GetModelName(), productID, mediaType, mediaName)
}
// ListMedia lists media assigned to product
func (it *DefaultProduct) ListMedia(mediaType string) ([]string, error) {
var result []string
productID := it.GetID()
if productID == "" {
return result, env.ErrorNew(ConstErrorModule, ConstErrorLevel, "45b1ebde-3dd0-4c6c-9960-fddd89f4907f", "product id not set")
}
mediaStorage, err := media.GetMediaStorage()
if err != nil {
return result, env.ErrorDispatch(err)
}
return mediaStorage.ListMedia(it.GetModelName(), productID, mediaType)
}
// GetMedia returns content of media assigned to product
func (it *DefaultProduct) GetMedia(mediaType string, mediaName string) ([]byte, error) {
productID := it.GetID()
if productID == "" {
return nil, env.ErrorNew(ConstErrorModule, ConstErrorLevel, "5f5d3c33-de82-4580-a6e7-f5c45e9281e5", "product id not set")
}
mediaStorage, err := media.GetMediaStorage()
if err != nil {
return nil, env.ErrorDispatch(err)
}
return mediaStorage.Load(it.GetModelName(), productID, mediaType, mediaName)
}
// GetMediaPath returns relative location of media assigned to product in media storage
func (it *DefaultProduct) GetMediaPath(mediaType string) (string, error) {
productID := it.GetID()
if productID == "" {
return "", env.ErrorNew(ConstErrorModule, ConstErrorLevel, "0055f93a-5d10-41db-8d93-ea2bb4bee216", "product id not set")
}
mediaStorage, err := media.GetMediaStorage()
if err != nil {
return "", env.ErrorDispatch(err)
}
return mediaStorage.GetMediaPath(it.GetModelName(), productID, mediaType)
}
// --------------------------------------------------------------------------------------------
// InterfaceCustomAttributes implementation (package "github.com/ottemo/commerce/app/models")
// --------------------------------------------------------------------------------------------
// GetInstance returns current instance delegate attached to
func (it *DefaultProduct) GetInstance() interface{} {
return it
}
// EditAttribute modifies custom attribute for collection
func (it *DefaultProduct) EditAttribute(attributeName string, attributeValues models.StructAttributeInfo) error {