/
product.class.php
3357 lines (2998 loc) · 106 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-2013 Regis Houssin <regis.houssin@capnetworks.com>
* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
* Copyright (C) 2007-2011 Jean Heimburger <jean@tiaris.info>
* Copyright (C) 2010-2013 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2013-2014 Cedric GROSS <c.gross@kreiz-it.fr>
* Copyright (C) 2013 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2011-2014 Alexandre Spangaro <alexandre.spangaro@gmail.com>
*
* 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 <http://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/class/commonobject.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
/**
* Class to manage products or services
*/
class Product extends CommonObject
{
public $element='product';
public $table_element='product';
public $fk_element='fk_product';
protected $childtables=array('propaldet','commandedet','facturedet','contratdet','facture_fourn_det','commande_fournisseurdet'); // To test if we can delete object
protected $isnolinkedbythird = 1; // No field fk_soc
protected $ismultientitymanaged = 1; // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
//! Identifiant unique
var $id ;
//! Ref
var $ref;
var $libelle; // TODO deprecated
var $label;
var $description;
//! Type 0 for regular product, 1 for service (Advanced feature: 2 for assembly kit, 3 for stock kit)
var $type;
//! Selling price
var $price; // Price net
var $price_ttc; // Price with tax
var $price_min; // Minimum price net
var $price_min_ttc; // Minimum price with tax
//! Base price ('TTC' for price including tax or 'HT' for net price)
var $price_base_type;
//! Arrays for multiprices
var $multiprices=array();
var $multiprices_ttc=array();
var $multiprices_base_type=array();
var $multiprices_tva_tx=array();
var $multiprices_recuperableonly=array();
//! Price by quantity arrays
var $price_by_qty;
var $prices_by_qty=array();
var $prices_by_qty_id=array();
var $prices_by_qty_list=array();
//! Default VAT rate of product
var $tva_tx;
//! French VAT NPR (0 or 1)
var $tva_npr=0;
//! Spanish local taxes
var $localtax1_tx;
var $localtax2_tx;
//! Stock
var $stock_reel;
//! Average price value for product entry into stock (PMP)
var $pmp;
//! Stock alert
var $seuil_stock_alerte;
//! Ask for replenishment when $desiredstock < $stock_reel
public $desiredstock;
//! Duree de validite du service
var $duration_value;
//! Unite de duree
var $duration_unit;
// Statut indique si le produit est en vente '1' ou non '0'
var $status;
// Status indicate whether the product is available for purchase '1' or not '0'
var $status_buy;
// Statut indique si le produit est un produit fini '1' ou une matiere premiere '0'
var $finished;
// We must manage batch number, sell-by date and so on : '1':yes '0':no
var $status_batch;
var $customcode; // Customs code
var $country_id; // Country origin id
var $country_code; // Country origin code (US, FR, ...)
//! Unites de mesure
var $weight;
var $weight_units;
var $length;
var $length_units;
var $surface;
var $surface_units;
var $volume;
var $volume_units;
var $accountancy_code_buy;
var $accountancy_code_sell;
//! barcode
var $barcode; // value
var $barcode_type; // id
var $barcode_type_code; // code (loaded by fetch_barcode). Example ean, isbn...
var $barcode_type_label; // label (loaded by fetch_barcode)
var $barcode_type_coder; // coder (loaded by fetch_barcode)
var $stats_propale=array();
var $stats_commande=array();
var $stats_contrat=array();
var $stats_facture=array();
var $multilangs=array();
//! Taille de l'image
var $imgWidth;
var $imgHeight;
//! Canevas a utiliser si le produit n'est pas un produit generique
var $canvas;
var $import_key;
var $date_creation;
var $date_modification;
//! Id du fournisseur
var $product_fourn_id;
//! Product ID already linked to a reference supplier
var $product_id_already_linked;
var $nbphoto;
//! Contains detail of stock of product into each warehouse
var $stock_warehouse=array();
var $oldcopy;
//note not visible on orders and invoices
var $note;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
function __construct($db)
{
global $langs;
$this->db = $db;
$this->status = 0;
$this->status_buy = 0;
$this->nbphoto = 0;
$this->stock_reel = 0;
$this->seuil_stock_alerte = 0;
$this->desiredstock = 0;
$this->canvas = '';
$this->status_batch=0;
}
/**
* Check that ref and label are ok
*
* @return int >1 if OK, <=0 if KO
*/
function check()
{
$this->ref = dol_sanitizeFileName(stripslashes($this->ref));
$err = 0;
if (dol_strlen(trim($this->ref)) == 0)
$err++;
if (dol_strlen(trim($this->libelle)) == 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
*/
function create($user,$notrigger=0)
{
global $conf, $langs;
$error=0;
// Clean parameters
$this->ref = dol_string_nospecial(trim($this->ref));
$this->libelle = trim($this->libelle);
if (empty($this->type)) $this->type=0;
$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->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_sell= trim($this->accountancy_code_sell);
// Barcode value
$this->barcode=trim($this->barcode);
// Check parameters
if (empty($this->libelle))
{
$this->error='ErrorMandatoryParametersNotProvided';
return -1;
}
if (empty($this->ref))
{
// 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', 1).")";
$sql.= " AND ref = '" .$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";
$sql.= ", accountancy_code_buy";
$sql.= ", accountancy_code_sell";
$sql.= ", canvas";
$sql.= ", finished";
$sql.= ", tobatch";
$sql.= ") VALUES (";
$sql.= "'".$this->db->idate($now)."'";
$sql.= ", ".$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->libelle)?"'".$this->db->escape($this->libelle)."'":"null");
$sql.= ", ".$user->id;
$sql.= ", ".$this->type;
$sql.= ", ".price2num($price_ht);
$sql.= ", ".price2num($price_ttc);
$sql.= ", '".$this->price_base_type."'";
$sql.= ", ".$this->status;
$sql.= ", ".$this->status_buy;
$sql.= ", '".$this->accountancy_code_buy."'";
$sql.= ", '".$this->accountancy_code_sell."'";
$sql.= ", '".$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':$this->status_batch);
$sql.= ")";
dol_syslog(get_class($this)."::Create sql=".$sql);
$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();
}
}
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)
{
// Appel des triggers
include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
$interface=new Interfaces($this->db);
$result=$interface->run_triggers('PRODUCT_CREATE',$this,$user,$langs,$conf);
if ($result < 0) { $error++; $this->errors=$interface->errors; }
// Fin appel 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
*/
function verify()
{
$this->errors=array();
$result = 0;
$this->ref = trim($this->ref);
if (! $this->ref)
{
$this->errors[] = 'ErrorBadRef';
$result = -2;
}
$rescode = $this->check_barcode($this->barcode,$this->barcode_type_code);
if ($rescode <> 0)
{
if ($rescode == -1)
{
$this->errors[] = 'ErrorBadBarCodeSyntax';
}
if ($rescode == -2)
{
$this->errors[] = 'ErrorBarCodeRequired';
}
if ($rescode == -3)
{
$this->errors[] = 'ErrorBarCodeAlreadyUsed';
}
$result = -3;
}
return $result;
}
/**
* 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
*/
function check_barcode($valuetotest,$typefortest)
{
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
*
* @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')
* @return int 1 if OK, -1 if ref already exists, -2 if other error
*/
function update($id, $user, $notrigger=false, $action='update')
{
global $langs, $conf, $hookmanager;
$error=0;
// Check parameters
if (! $this->libelle) $this->libelle = 'MISSING LABEL';
// Clean parameters
$this->ref = dol_string_nospecial(trim($this->ref));
$this->libelle = trim($this->libelle);
$this->description = trim($this->description);
$this->note = (isset($this->note) ? trim($this->note) : null);
$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->surface = price2num($this->surface);
$this->surface_units = trim($this->surface_units);
$this->volume = price2num($this->volume);
$this->volume_units = trim($this->volume_units);
if (empty($this->tva_tx)) $this->tva_tx = 0;
if (empty($this->tva_npr)) $this->tva_npr = 0;
if (empty($this->localtax1_tx)) $this->localtax1_tx = 0;
if (empty($this->localtax2_tx)) $this->localtax2_tx = 0;
if (empty($this->status)) $this->status = 0;
if (empty($this->status_buy)) $this->status_buy = 0;
if (empty($this->country_id)) $this->country_id = 0;
// Barcode value
$this->barcode=trim($this->barcode);
$this->accountancy_code_buy = trim($this->accountancy_code_buy);
$this->accountancy_code_sell= trim($this->accountancy_code_sell);
$this->db->begin();
// Check name is required and codes are ok or unique.
// If error, this->errors[] is filled
if ($action != 'add')
{
$result = $this->verify(); // We don't check when update called during a create because verify was already done
}
if ($result >= 0)
{
// For automatic creation
if ($this->barcode == -1) $this->barcode = $this->get_barcode($this,$this->barcode_type_code);
$sql = "UPDATE ".MAIN_DB_PREFIX."product";
$sql.= " SET label = '" . $this->db->escape($this->libelle) ."'";
$sql.= ", ref = '" . $this->ref ."'";
$sql.= ", ref_ext = ".(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext)."'":"null");
$sql.= ", tva_tx = " . $this->tva_tx;
$sql.= ", recuperableonly = " . $this->tva_npr;
$sql.= ", localtax1_tx = " . $this->localtax1_tx;
$sql.= ", localtax2_tx = " . $this->localtax2_tx;
$sql.= ", barcode = ". (empty($this->barcode)?"null":"'".$this->db->escape($this->barcode)."'");
$sql.= ", fk_barcode_type = ". (empty($this->barcode_type)?"null":$this->db->escape($this->barcode_type));
$sql.= ", tosell = " . $this->status;
$sql.= ", tobuy = " . $this->status_buy;
$sql.= ", tobatch = " . ((empty($this->status_batch) || $this->status_batch < 0) ? '0' : $this->status_batch);
$sql.= ", finished = " . ((! isset($this->finished) || $this->finished < 0) ? "null" : (int) $this->finished);
$sql.= ", weight = " . ($this->weight!='' ? "'".$this->weight."'" : 'null');
$sql.= ", weight_units = " . ($this->weight_units!='' ? "'".$this->weight_units."'": 'null');
$sql.= ", length = " . ($this->length!='' ? "'".$this->length."'" : 'null');
$sql.= ", length_units = " . ($this->length_units!='' ? "'".$this->length_units."'" : 'null');
$sql.= ", surface = " . ($this->surface!='' ? "'".$this->surface."'" : 'null');
$sql.= ", surface_units = " . ($this->surface_units!='' ? "'".$this->surface_units."'" : 'null');
$sql.= ", volume = " . ($this->volume!='' ? "'".$this->volume."'" : 'null');
$sql.= ", volume_units = " . ($this->volume_units!='' ? "'".$this->volume_units."'" : 'null');
$sql.= ", seuil_stock_alerte = " . ((isset($this->seuil_stock_alerte) && $this->seuil_stock_alerte != '') ? "'".$this->seuil_stock_alerte."'" : "null");
$sql.= ", description = '" . $this->db->escape($this->description) ."'";
$sql.= ", url = " . ($this->url?"'".$this->db->escape($this->url)."'":'null');
$sql.= ", customcode = '" . $this->db->escape($this->customcode) ."'";
$sql.= ", fk_country = " . ($this->country_id > 0 ? $this->country_id : 'null');
$sql.= ", note = ".(isset($this->note) ? "'" .$this->db->escape($this->note)."'" : 'null');
$sql.= ", duration = '" . $this->duration_value . $this->duration_unit ."'";
$sql.= ", accountancy_code_buy = '" . $this->accountancy_code_buy."'";
$sql.= ", accountancy_code_sell= '" . $this->accountancy_code_sell."'";
$sql.= ", desiredstock = " . ((isset($this->desiredstock) && $this->desiredstock != '') ? $this->desiredstock : "null");
$sql.= " WHERE rowid = " . $id;
dol_syslog(get_class($this)."update sql=".$sql);
$resql=$this->db->query($sql);
if ($resql)
{
$this->id = $id;
// Multilangs
if (! empty($conf->global->MAIN_MULTILANGS))
{
if ( $this->setMultiLangs() < 0)
{
$this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql;
return -2;
}
}
// Actions on extra fields (by external module or standard code)
$hookmanager->initHooks(array('productdao'));
$parameters=array('id'=>$this->id);
$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if (empty($reshook))
{
if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
{
$result=$this->insertExtraFields();
if ($result < 0)
{
$error++;
}
}
}
else if ($reshook < 0) $error++;
if (! $error && ! $notrigger)
{
// Appel des triggers
include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
$interface=new Interfaces($this->db);
$result=$interface->run_triggers('PRODUCT_MODIFY',$this,$user,$langs,$conf);
if ($result < 0) { $error++; $this->errors=$interface->errors; }
// Fin appel triggers
}
if (! $error && (is_object($this->oldcopy) && $this->oldcopy->ref != $this->ref))
{
// We remove directory
if ($conf->product->dir_output)
{
$olddir = $conf->product->dir_output . "/" . dol_sanitizeFileName($this->oldcopy->ref);
$newdir = $conf->product->dir_output . "/" . dol_sanitizeFileName($this->ref);
if (file_exists($olddir))
{
include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
$res=@dol_move($olddir, $newdir);
if (! $res)
{
$this->error='ErrorFailToMoveDir';
$error++;
}
}
}
}
if (! $error)
{
$this->db->commit();
return 1;
}
else
{
$this->db->rollback();
return -$error;
}
}
else
{
if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
{
$this->error=$langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists",$this->ref);
$this->db->rollback();
return -1;
}
else
{
$this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql;
$this->db->rollback();
return -2;
}
}
}
else
{
$this->db->rollback();
dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
return -3;
}
}
/**
* Delete a product from database (if not used)
*
* @param int $id Product id (usage of this is deprecated, delete should be called without parameters on a fetched object)
* @return int < 0 if KO, 0 = Not possible, > 0 if OK
*/
function delete($id=0)
{
global $conf,$user,$langs;
$error=0;
// Clean parameters
if (empty($id)) $id=$this->id;
else $this->fetch($id);
// Check parameters
if (empty($id))
{
$this->error = "Object must be fetched before calling delete";
return -1;
}
if (($this->type == 0 && empty($user->rights->produit->supprimer)) || ($this->type == 1 && empty($user->rights->service->supprimer)))
{
$this->error = "ErrorForbidden";
return 0;
}
$objectisused = $this->isObjectUsed($id);
if (empty($objectisused))
{
$this->db->begin();
if (! $error)
{
// Appel des triggers
include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
$interface=new Interfaces($this->db);
$result=$interface->run_triggers('PRODUCT_DELETE',$this,$user,$langs,$conf);
if ($result < 0) {
$error++; $this->errors=$interface->errors;
}
// Fin appel triggers
}
// Delete all child tables
$elements = array('product_fournisseur_price','product_price','product_lang','categorie_product','product_stock');
foreach($elements as $table)
{
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX.$table;
$sql.= " WHERE fk_product = ".$id;
dol_syslog(get_class($this).'::delete sql='.$sql, LOG_DEBUG);
$result = $this->db->query($sql);
if (! $result)
{
$error++;
$this->errors[] = $this->db->lasterror();
dol_syslog(get_class($this).'::delete error '.$this->error, LOG_ERR);
}
}
}
// Delete product
if (! $error)
{
$sqlz = "DELETE FROM ".MAIN_DB_PREFIX."product";
$sqlz.= " WHERE rowid = ".$id;
dol_syslog(get_class($this).'::delete sql='.$sqlz, LOG_DEBUG);
$resultz = $this->db->query($sqlz);
if ( ! $resultz )
{
$error++;
$this->errors[] = $this->db->lasterror();
dol_syslog(get_class($this).'::delete error '.$this->error, LOG_ERR);
}
}
if (! $error)
{
// We remove directory
$ref = dol_sanitizeFileName($this->ref);
if ($conf->product->dir_output)
{
$dir = $conf->product->dir_output . "/" . $ref;
if (file_exists($dir))
{
$res=@dol_delete_dir_recursive($dir);
if (! $res)
{
$this->errors[] = 'ErrorFailToDeleteDir';
$error++;
}
}
}
}
// Remove extrafields
if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
{
$result=$this->deleteExtraFields();
if ($result < 0)
{
$error++;
dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
}
}
if (! $error)
{
$this->db->commit();
return 1;
}
else
{
foreach($this->errors as $errmsg)
{
dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
$this->error.=($this->error?', '.$errmsg:$errmsg);
}
$this->db->rollback();
return -$error;
}
}
else
{
$this->error = "ErrorRecordIsUsedCantDelete";
return 0;
}
}
/**
* Update ou cree les traductions des infos produits
*
* @return int <0 if KO, >0 if OK
*/
function setMultiLangs()
{
global $langs;
$langs_available = $langs->get_available_languages();
$current_lang = $langs->getDefaultLang();
foreach ($langs_available as $key => $value)
{
$sql = "SELECT rowid";
$sql.= " FROM ".MAIN_DB_PREFIX."product_lang";
$sql.= " WHERE fk_product=".$this->id;
$sql.= " AND lang='".$key."'";
$result = $this->db->query($sql);
if ($key == $current_lang)
{
if ($this->db->num_rows($result)) // si aucune ligne dans la base
{
$sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang";
$sql2.= " SET label='".$this->db->escape($this->libelle)."',";
$sql2.= " description='".$this->db->escape($this->description)."',";
$sql2.= " note='".$this->db->escape($this->note)."'";
$sql2.= " WHERE fk_product=".$this->id." AND lang='".$key."'";
}
else
{
$sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description, note)";
$sql2.= " VALUES(".$this->id.",'".$key."','". $this->db->escape($this->libelle);
$sql2.= "','".$this->db->escape($this->description);
$sql2.= "','".$this->db->escape($this->note)."')";
}
dol_syslog(get_class($this).'::setMultiLangs sql='.$sql2);
if (! $this->db->query($sql2))
{
$this->error=$this->db->lasterror();
dol_syslog(get_class($this).'::setMultiLangs error='.$this->error, LOG_ERR);
return -1;
}
}
else if (isset($this->multilangs["$key"]))
{
if ($this->db->num_rows($result)) // si aucune ligne dans la base
{
$sql2 = "UPDATE ".MAIN_DB_PREFIX."product_lang";
$sql2.= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',";
$sql2.= " description='".$this->db->escape($this->multilangs["$key"]["description"])."',";
$sql2.= " note='".$this->db->escape($this->multilangs["$key"]["note"])."'";
$sql2.= " WHERE fk_product=".$this->id." AND lang='".$key."'";
}
else
{
$sql2 = "INSERT INTO ".MAIN_DB_PREFIX."product_lang (fk_product, lang, label, description, note)";
$sql2.= " VALUES(".$this->id.",'".$key."','". $this->db->escape($this->multilangs["$key"]["label"]);
$sql2.= "','".$this->db->escape($this->multilangs["$key"]["description"]);
$sql2.= "','".$this->db->escape($this->multilangs["$key"]["note"])."')";
}
// on ne sauvegarde pas des champs vides
if ( $this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"] )
dol_syslog(get_class($this).'::setMultiLangs sql='.$sql2);
if (! $this->db->query($sql2))
{
$this->error=$this->db->lasterror();
dol_syslog(get_class($this).'::setMultiLangs error='.$this->error, LOG_ERR);
return -1;
}
}
}
return 1;
}
/**
* Load array this->multilangs
*
* @return int <0 if KO, >0 if OK
*/
function getMultiLangs()
{
global $langs;
$current_lang = $langs->getDefaultLang();
$sql = "SELECT lang, label, description, note";
$sql.= " FROM ".MAIN_DB_PREFIX."product_lang";
$sql.= " WHERE fk_product=".$this->id;
$result = $this->db->query($sql);
if ($result)
{
while ( $obj = $this->db->fetch_object($result) )
{
//print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
if( $obj->lang == $current_lang ) // si on a les traduct. dans la langue courante on les charge en infos principales.
{
$this->label = $obj->label;
$this->description = $obj->description;
$this->note = $obj->note;
}
$this->multilangs["$obj->lang"]["label"] = $obj->label;
$this->multilangs["$obj->lang"]["description"] = $obj->description;
$this->multilangs["$obj->lang"]["note"] = $obj->note;
}
return 1;
}
else
{
$this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql;
return -1;
}
}
/**
* Ajoute un changement de prix en base dans l'historique des prix
*
* @param User $user Objet utilisateur qui modifie le prix
* @param int $level price level to change
* @return int <0 if KO, >0 if OK
*/
function _log_price($user,$level=0)
{
global $conf;
$now=dol_now();
// Add new price
$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_price(price_level,date_price,fk_product,fk_user_author,price,price_ttc,price_base_type,tosell,tva_tx,recuperableonly,";
$sql.= " localtax1_tx, localtax2_tx, price_min,price_min_ttc,price_by_qty,entity) ";
$sql.= " VALUES(".($level?$level:1).", '".$this->db->idate($now)."',".$this->id.",".$user->id.",".$this->price.",".$this->price_ttc.",'".$this->price_base_type."',".$this->status.",".$this->tva_tx.",".$this->tva_npr.",";
$sql.= " ".$this->localtax1_tx.",".$this->localtax2_tx.",".$this->price_min.",".$this->price_min_ttc.",".$this->price_by_qty.",".$conf->entity;