/
product.class.php
6055 lines (5392 loc) · 219 KB
/
product.class.php
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
<?php
/* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
* Copyright (C) 2007-2011 Jean Heimburger <jean@tiaris.info>
* Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
* Copyright (C) 2013-2014 Cedric GROSS <c.gross@kreiz-it.fr>
* Copyright (C) 2013-2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2011-2021 Open-DSI <support@open-dsi.fr>
* Copyright (C) 2014 Henry Florian <florian.henry@open-concept.pro>
* Copyright (C) 2014-2016 Philippe Grand <philippe.grand@atoo-net.com>
* Copyright (C) 2014 Ion agorria <ion@agorria.com>
* Copyright (C) 2016-2018 Ferran Marcet <fmarcet@2byte.es>
* Copyright (C) 2017 Gustavo Novaro
* Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/product/class/product.class.php
* \ingroup produit
* \brief File of class to manage predefined products or services
*/
require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
/**
* Class to manage products or services
*/
class Product extends CommonObject
{
/**
* @var string ID to identify managed object
*/
public $element = 'product';
/**
* @var string Name of table without prefix where object is stored
*/
public $table_element = 'product';
/**
* @var string Field with ID of parent key if this field has a parent
*/
public $fk_element = 'fk_product';
/**
* @var array List of child tables. To test if we can delete object.
*/
protected $childtables = array(
'supplier_proposaldet',
'propaldet',
'commandedet',
'facturedet',
'contratdet',
'facture_fourn_det',
'commande_fournisseurdet'
);
/**
* 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
*
* @var int
*/
public $ismultientitymanaged = 1;
/**
* @var string picto
*/
public $picto = 'product';
/**
* {@inheritdoc}
*/
protected $table_ref_field = 'ref';
public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm'; // See also into images.lib.php
/**
* @deprecated
* @see $label
*/
public $libelle;
/**
* Product label
*
* @var string
*/
public $label;
/**
* Product description
*
* @var string
*/
public $description;
/**
* Product other fields PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION
*
* @var string
*/
public $other;
/**
* Check TYPE constants
*
* @var int
*/
public $type = self::TYPE_PRODUCT;
/**
* Selling price
*
* @var float
*/
public $price; // Price net
/**
* Price with tax
*
* @var float
*/
public $price_ttc;
/**
* Minimum price net
*
* @var float
*/
public $price_min;
/**
* Minimum price with tax
*
* @var float
*/
public $price_min_ttc;
/**
* Base price ('TTC' for price including tax or 'HT' for net price)
* @var string
*/
public $price_base_type;
//! Arrays for multiprices
public $multiprices = array();
public $multiprices_ttc = array();
public $multiprices_base_type = array();
public $multiprices_min = array();
public $multiprices_min_ttc = array();
public $multiprices_tva_tx = array();
public $multiprices_recuperableonly = array();
//! Price by quantity arrays
public $price_by_qty;
public $prices_by_qty = array();
public $prices_by_qty_id = array();
public $prices_by_qty_list = array();
//! Array for multilangs
public $multilangs = array();
//! Default VAT code for product (link to code into llx_c_tva but without foreign keys)
public $default_vat_code;
//! Default VAT rate of product
public $tva_tx;
//! French VAT NPR (0 or 1)
public $tva_npr = 0;
//! Other local taxes
public $localtax1_tx;
public $localtax2_tx;
public $localtax1_type;
public $localtax2_type;
public $lifetime;
public $qc_frequency;
/**
* Stock real
*
* @var int
*/
public $stock_reel = 0;
/**
* Stock virtual
*
* @var int
*/
public $stock_theorique;
/**
* Cost price
*
* @var float
*/
public $cost_price;
//! Average price value for product entry into stock (PMP)
public $pmp;
/**
* Stock alert
*
* @var float
*/
public $seuil_stock_alerte = 0;
/**
* Ask for replenishment when $desiredstock < $stock_reel
*/
public $desiredstock = 0;
/*
* Service expiration
*/
public $duration_value;
/**
* Exoiration unit
*/
public $duration_unit;
/**
* Status indicates whether the product is on sale '1' or not '0'
*
* @var int
*/
public $status = 0;
/**
* Status indicate whether the product is available for purchase '1' or not '0'
*
* @var int
*/
public $status_buy = 0;
/**
* Status indicates whether the product is a finished product '1' or a raw material '0'
*
* @var int
*/
public $finished;
/**
* fk_default_bom indicates the default bom
*
* @var int
*/
public $fk_default_bom;
/**
* We must manage lot/batch number, sell-by date and so on : '1':yes '0':no
*
* @var int
*/
public $status_batch = 0;
/**
* If allowed, we can edit batch or serial number mask for each product
*
* @var string
*/
public $batch_mask = '';
/**
* Customs code
*
* @var string
*/
public $customcode;
/**
* Product URL
*
* @var string
*/
public $url;
//! Metric of products
public $weight;
public $weight_units; // scale -3, 0, 3, 6
public $length;
public $length_units; // scale -3, 0, 3, 6
public $width;
public $width_units; // scale -3, 0, 3, 6
public $height;
public $height_units; // scale -3, 0, 3, 6
public $surface;
public $surface_units; // scale -3, 0, 3, 6
public $volume;
public $volume_units; // scale -3, 0, 3, 6
public $net_measure;
public $net_measure_units; // scale -3, 0, 3, 6
public $accountancy_code_sell;
public $accountancy_code_sell_intra;
public $accountancy_code_sell_export;
public $accountancy_code_buy;
public $accountancy_code_buy_intra;
public $accountancy_code_buy_export;
/**
* Main Barcode value
*
* @var string
*/
public $barcode;
/**
* Main Barcode type ID
*
* @var int
*/
public $barcode_type;
/**
* Main Barcode type code
*
* @var string
*/
public $barcode_type_code;
public $stats_propale = array();
public $stats_commande = array();
public $stats_contrat = array();
public $stats_facture = array();
public $stats_commande_fournisseur = array();
public $stats_reception = array();
public $stats_mrptoconsume = array();
public $stats_mrptoproduce = array();
//! Size of image
public $imgWidth;
public $imgHeight;
/**
* @var integer|string date_creation
*/
public $date_creation;
/**
* @var integer|string date_modification
*/
public $date_modification;
//! Id du fournisseur
public $product_fourn_id;
//! Product ID already linked to a reference supplier
public $product_id_already_linked;
public $nbphoto = 0;
//! Contains detail of stock of product into each warehouse
public $stock_warehouse = array();
public $oldcopy;
/**
* @var int Default warehouse Id
*/
public $fk_default_warehouse;
/**
* @var int ID
*/
public $fk_price_expression;
/* To store supplier price found */
public $fourn_pu;
public $fourn_price_base_type;
public $fourn_socid;
/**
* @deprecated
* @see $ref_supplier
*/
public $ref_fourn;
/**
* @var string ref supplier
*/
public $ref_supplier;
/**
* Unit code ('km', 'm', 'l', 'p', ...)
*
* @var string
*/
public $fk_unit;
/**
* Price is generated using multiprice rules
*
* @var int
*/
public $price_autogen = 0;
/**
* Array with list of supplier prices of product
*
* @var array
*/
public $supplierprices;
/**
* Property set to save result of isObjectUsed(). Used for example by Product API.
*
* @var boolean
*/
public $is_object_used;
/**
*
*
*
*/
public $mandatory_period;
/**
* 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
* Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
* 'label' the translation key.
* 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
* 'position' is the sort order of field.
* 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
* 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
* 'noteditable' says if field is not editable (1 or 0)
* 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
* 'index' if we want an index in database.
* 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
* 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
* 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
* 'css' is the CSS style to use on field. For example: 'maxwidth200'
* 'help' is a string visible as a tooltip on field
* 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
* 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
* 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
* 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
* 'comment' is not used. You can store here any text of your choice. It is not used by application.
*
* Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
*/
/**
* @var array fields of object product
*/
public $fields = array(
'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>5),
'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>2, 'position'=>15),
'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>'!empty($conf->barcode->enabled)', 'position'=>20, 'visible'=>-1, 'showoncombobox'=>3),
'fk_barcode_type' => array('type'=>'integer', 'label'=>'BarcodeType', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>-1,),
'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61),
'note' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62),
'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
//'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
'fk_user_author'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
//'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
'localtax1_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax1tx', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>-1,),
'localtax1_type' => array('type'=>'varchar(10)', 'label'=>'Localtax1type', 'enabled'=>'1', 'position'=>155, 'notnull'=>1, 'visible'=>-1,),
'localtax2_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax2tx', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>-1,),
'localtax2_type' => array('type'=>'varchar(10)', 'label'=>'Localtax2type', 'enabled'=>'1', 'position'=>165, 'notnull'=>1, 'visible'=>-1,),
'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
//'tosell' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
//'tobuy' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
'mandatory_period' =>array('type'=>'integer', 'label'=>'mandatory_period', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000),
);
/**
* Regular product
*/
const TYPE_PRODUCT = 0;
/**
* Service
*/
const TYPE_SERVICE = 1;
/**
* Advanced feature: assembly kit
*/
const TYPE_ASSEMBLYKIT = 2;
/**
* Advanced feature: stock kit
*/
const TYPE_STOCKKIT = 3;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
$this->canvas = '';
}
/**
* Check that ref and label are ok
*
* @return int >1 if OK, <=0 if KO
*/
public function check()
{
$this->ref = dol_sanitizeFileName(stripslashes($this->ref));
$err = 0;
if (dol_strlen(trim($this->ref)) == 0) {
$err++;
}
if (dol_strlen(trim($this->label)) == 0) {
$err++;
}
if ($err > 0) {
return 0;
} else {
return 1;
}
}
/**
* Insert product into database
*
* @param User $user User making insert
* @param int $notrigger Disable triggers
* @return int Id of product/service if OK, < 0 if KO
*/
public function create($user, $notrigger = 0)
{
global $conf, $langs;
$error = 0;
// Clean parameters
$this->ref = dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)));
$this->label = trim($this->label);
$this->price_ttc = price2num($this->price_ttc);
$this->price = price2num($this->price);
$this->price_min_ttc = price2num($this->price_min_ttc);
$this->price_min = price2num($this->price_min);
if (empty($this->tva_tx)) {
$this->tva_tx = 0;
}
if (empty($this->tva_npr)) {
$this->tva_npr = 0;
}
//Local taxes
if (empty($this->localtax1_tx)) {
$this->localtax1_tx = 0;
}
if (empty($this->localtax2_tx)) {
$this->localtax2_tx = 0;
}
if (empty($this->localtax1_type)) {
$this->localtax1_type = '0';
}
if (empty($this->localtax2_type)) {
$this->localtax2_type = '0';
}
if (empty($this->price)) {
$this->price = 0;
}
if (empty($this->price_min)) {
$this->price_min = 0;
}
// Price by quantity
if (empty($this->price_by_qty)) {
$this->price_by_qty = 0;
}
if (empty($this->status)) {
$this->status = 0;
}
if (empty($this->status_buy)) {
$this->status_buy = 0;
}
$price_ht = 0;
$price_ttc = 0;
$price_min_ht = 0;
$price_min_ttc = 0;
//
if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) {
$price_ttc = price2num($this->price_ttc, 'MU');
$price_ht = price2num($this->price_ttc / (1 + ($this->tva_tx / 100)), 'MU');
}
//
if ($this->price_base_type != 'TTC' && $this->price > 0) {
$price_ht = price2num($this->price, 'MU');
$price_ttc = price2num($this->price * (1 + ($this->tva_tx / 100)), 'MU');
}
//
if (($this->price_min_ttc > 0) && ($this->price_base_type == 'TTC')) {
$price_min_ttc = price2num($this->price_min_ttc, 'MU');
$price_min_ht = price2num($this->price_min_ttc / (1 + ($this->tva_tx / 100)), 'MU');
}
//
if (($this->price_min > 0) && ($this->price_base_type != 'TTC')) {
$price_min_ht = price2num($this->price_min, 'MU');
$price_min_ttc = price2num($this->price_min * (1 + ($this->tva_tx / 100)), 'MU');
}
$this->accountancy_code_buy = trim($this->accountancy_code_buy);
$this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
$this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
$this->accountancy_code_sell = trim($this->accountancy_code_sell);
$this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
$this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
// Barcode value
$this->barcode = trim($this->barcode);
$this->mandatory_period = empty($this->mandatory_period) ? 0 : $this->mandatory_period;
// Check parameters
if (empty($this->label)) {
$this->error = 'ErrorMandatoryParametersNotProvided';
return -1;
}
if (empty($this->ref) || $this->ref == 'auto') {
// Load object modCodeProduct
$module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard');
if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
$module = substr($module, 0, dol_strlen($module) - 4);
}
dol_include_once('/core/modules/product/'.$module.'.php');
$modCodeProduct = new $module;
if (!empty($modCodeProduct->code_auto)) {
$this->ref = $modCodeProduct->getNextValue($this, $this->type);
}
unset($modCodeProduct);
}
if (empty($this->ref)) {
$this->error = 'ProductModuleNotSetupForAutoRef';
return -2;
}
}
dol_syslog(get_class($this)."::create ref=".$this->ref." price=".$this->price." price_ttc=".$this->price_ttc." tva_tx=".$this->tva_tx." price_base_type=".$this->price_base_type, LOG_DEBUG);
$now = dol_now();
$this->db->begin();
// For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
if ($this->barcode == -1) {
$this->barcode = $this->get_barcode($this, $this->barcode_type_code);
}
// Check more parameters
// If error, this->errors[] is filled
$result = $this->verify();
if ($result >= 0) {
$sql = "SELECT count(*) as nb";
$sql .= " FROM ".MAIN_DB_PREFIX."product";
$sql .= " WHERE entity IN (".getEntity('product').")";
$sql .= " AND ref = '".$this->db->escape($this->ref)."'";
$result = $this->db->query($sql);
if ($result) {
$obj = $this->db->fetch_object($result);
if ($obj->nb == 0) {
// Produit non deja existant
$sql = "INSERT INTO ".MAIN_DB_PREFIX."product (";
$sql .= "datec";
$sql .= ", entity";
$sql .= ", ref";
$sql .= ", ref_ext";
$sql .= ", price_min";
$sql .= ", price_min_ttc";
$sql .= ", label";
$sql .= ", fk_user_author";
$sql .= ", fk_product_type";
$sql .= ", price";
$sql .= ", price_ttc";
$sql .= ", price_base_type";
$sql .= ", tobuy";
$sql .= ", tosell";
if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
$sql .= ", accountancy_code_buy";
$sql .= ", accountancy_code_buy_intra";
$sql .= ", accountancy_code_buy_export";
$sql .= ", accountancy_code_sell";
$sql .= ", accountancy_code_sell_intra";
$sql .= ", accountancy_code_sell_export";
}
$sql .= ", canvas";
$sql .= ", finished";
$sql .= ", tobatch";
$sql .= ", batch_mask";
$sql .= ", fk_unit";
$sql .= ", mandatory_period";
$sql .= ") VALUES (";
$sql .= "'".$this->db->idate($now)."'";
$sql .= ", ".((int) $conf->entity);
$sql .= ", '".$this->db->escape($this->ref)."'";
$sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
$sql .= ", ".price2num($price_min_ht);
$sql .= ", ".price2num($price_min_ttc);
$sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
$sql .= ", ".((int) $user->id);
$sql .= ", ".((int) $this->type);
$sql .= ", ".price2num($price_ht, 'MT');
$sql .= ", ".price2num($price_ttc, 'MT');
$sql .= ", '".$this->db->escape($this->price_base_type)."'";
$sql .= ", ".((int) $this->status);
$sql .= ", ".((int) $this->status_buy);
if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
$sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
$sql .= ", '".$this->db->escape($this->accountancy_code_buy_intra)."'";
$sql .= ", '".$this->db->escape($this->accountancy_code_buy_export)."'";
$sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
$sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'";
$sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'";
}
$sql .= ", '".$this->db->escape($this->canvas)."'";
$sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'NULL' : (int) $this->finished);
$sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : ((int) $this->status_batch));
$sql .= ", '".$this->db->escape($this->batch_mask)."'";
$sql .= ", ".($this->fk_unit > 0 ? ((int) $this->fk_unit) : 'NULL');
$sql .= ", '".$this->db->escape($this->mandatory_period)."'";
$sql .= ")";
dol_syslog(get_class($this)."::Create", LOG_DEBUG);
$result = $this->db->query($sql);
if ($result) {
$id = $this->db->last_insert_id(MAIN_DB_PREFIX."product");
if ($id > 0) {
$this->id = $id;
$this->price = $price_ht;
$this->price_ttc = $price_ttc;
$this->price_min = $price_min_ht;
$this->price_min_ttc = $price_min_ttc;
$result = $this->_log_price($user);
if ($result > 0) {
if ($this->update($id, $user, true, 'add') <= 0) {
$error++;
}
} else {
$error++;
$this->error = $this->db->lasterror();
}
// update accountancy for this entity
if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
$this->db->query("DELETE FROM " . MAIN_DB_PREFIX . "product_perentity WHERE fk_product = " .((int) $this->id) . " AND entity = " . ((int) $conf->entity));
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_perentity (";
$sql .= " fk_product";
$sql .= ", entity";
$sql .= ", accountancy_code_buy";
$sql .= ", accountancy_code_buy_intra";
$sql .= ", accountancy_code_buy_export";
$sql .= ", accountancy_code_sell";
$sql .= ", accountancy_code_sell_intra";
$sql .= ", accountancy_code_sell_export";
$sql .= ") VALUES (";
$sql .= $this->id;
$sql .= ", " . $conf->entity;
$sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
$sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
$sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
$sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
$sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
$sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
$sql .= ")";
$result = $this->db->query($sql);
if (!$result) {
$error++;
$this->error = 'ErrorFailedToInsertAccountancyForEntity';
}
}
} else {
$error++;
$this->error = 'ErrorFailedToGetInsertedId';
}
} else {
$error++;
$this->error = $this->db->lasterror();
}
} else {
// Product already exists with this ref
$langs->load("products");
$error++;
$this->error = "ErrorProductAlreadyExists";
}
} else {
$error++;
$this->error = $this->db->lasterror();
}
if (!$error && !$notrigger) {
// Call trigger
$result = $this->call_trigger('PRODUCT_CREATE', $user);
if ($result < 0) {
$error++;
}
// End call triggers
}
if (!$error) {
$this->db->commit();
return $this->id;
} else {
$this->db->rollback();
return -$error;
}
} else {
$this->db->rollback();
dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
return -3;
}
}
/**
* Check properties of product are ok (like name, barcode, ...).
* All properties must be already loaded on object (this->barcode, this->barcode_type_code, ...).
*
* @return int 0 if OK, <0 if KO
*/
public function verify()
{
global $langs;
$this->errors = array();
$result = 0;
$this->ref = trim($this->ref);
if (!$this->ref) {
$this->errors[] = 'ErrorBadRef';
$result = -2;
}
$arrayofnonnegativevalue = array('weight'=>'Weight', 'width'=>'Width', 'height'=>'Height', 'length'=>'Length', 'surface'=>'Surface', 'volume'=>'Volume');
foreach ($arrayofnonnegativevalue as $key => $value) {
if (property_exists($this, $key) && $this->$key < 0) {
$langs->load("other");
$this->errors[] = $langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv($value));
$result = -4;
}
}
$rescode = $this->check_barcode($this->barcode, $this->barcode_type_code);
if ($rescode) {
if ($rescode == -1) {
$this->errors[] = 'ErrorBadBarCodeSyntax';
} elseif ($rescode == -2) {
$this->errors[] = 'ErrorBarCodeRequired';
} elseif ($rescode == -3) {
// Note: Common usage is to have barcode unique. For variants, we should have a different barcode.
$this->errors[] = 'ErrorBarCodeAlreadyUsed';
}
$result = -3;
}
return $result;
}
// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
/**
* Check barcode
*
* @param string $valuetotest Value to test
* @param string $typefortest Type of barcode (ISBN, EAN, ...)
* @return int 0 if OK
* -1 ErrorBadBarCodeSyntax
* -2 ErrorBarCodeRequired
* -3 ErrorBarCodeAlreadyUsed
*/
public function check_barcode($valuetotest, $typefortest)
{
// phpcs:enable
global $conf;
if (!empty($conf->barcode->enabled) && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
$module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);
$dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
foreach ($dirsociete as $dirroot) {
$res = dol_include_once($dirroot.$module.'.php');
if ($res) {
break;
}
}
$mod = new $module();
dol_syslog(get_class($this)."::check_barcode value=".$valuetotest." type=".$typefortest." module=".$module);
$result = $mod->verif($this->db, $valuetotest, $this, 0, $typefortest);
return $result;
} else {
return 0;
}
}
/**
* Update a record into database.
* If batch flag is set to on, we create records into llx_product_batch
*
* @param int $id Id of product
* @param User $user Object user making update
* @param int $notrigger Disable triggers
* @param string $action Current action for hookmanager ('add' or 'update')
* @param boolean $updatetype Update product type
* @return int 1 if OK, -1 if ref already exists, -2 if other error
*/
public function update($id, $user, $notrigger = false, $action = 'update', $updatetype = false)
{
global $langs, $conf, $hookmanager;
$error = 0;
// Check parameters
if (!$this->label) {
$this->label = 'MISSING LABEL';
}
// Clean parameters
$this->ref = dol_string_nospecial(trim($this->ref));
$this->label = trim($this->label);
$this->description = trim($this->description);
$this->note = (isset($this->note) ? trim($this->note) : null);
$this->net_measure = price2num($this->net_measure);
$this->net_measure_units = trim($this->net_measure_units);
$this->weight = price2num($this->weight);
$this->weight_units = trim($this->weight_units);
$this->length = price2num($this->length);
$this->length_units = trim($this->length_units);
$this->width = price2num($this->width);
$this->width_units = trim($this->width_units);
$this->height = price2num($this->height);
$this->height_units = trim($this->height_units);
$this->surface = price2num($this->surface);
$this->surface_units = trim($this->surface_units);
$this->volume = price2num($this->volume);
$this->volume_units = trim($this->volume_units);
// set unit not defined
if (is_numeric($this->length_units)) {
$this->width_units = $this->length_units; // Not used yet
}
if (is_numeric($this->length_units)) {
$this->height_units = $this->length_units; // Not used yet
}
// Automated compute surface and volume if not filled
if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
$this->surface = $this->length * $this->width;
$this->surface_units = measuring_units_squared($this->length_units);
}
if (empty($this->volume) && !empty($this->surface) && !empty($this->height) && $this->length_units == $this->height_units) {
$this->volume = $this->surface * $this->height;
$this->volume_units = measuring_units_cubed($this->height_units);
}
if (empty($this->tva_tx)) {
$this->tva_tx = 0;
}
if (empty($this->tva_npr)) {