-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathordercustomer.php
2036 lines (1641 loc) · 65.1 KB
/
ordercustomer.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) 2013 Cédric Salvador <csalvador@gpcsolutions.fr>
* Copyright (C) 2014-2015 ATM Consulting <support@atm-consulting.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 <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/product/stock/replenish.php
* \ingroup produit
* \brief Page to list stocks to replenish
*/
require 'config.php';
ini_set('memory_limit', '1024M');
set_time_limit(0);
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
dol_include_once('/product/class/product.class.php');
dol_include_once('/core/class/html.formother.class.php');
dol_include_once('/core/class/html.form.class.php');
dol_include_once('/fourn/class/fournisseur.commande.class.php');
dol_include_once("/core/lib/admin.lib.php");
dol_include_once("/fourn/class/fournisseur.class.php");
dol_include_once('/supplierorderfromorder/lib/function.lib.php');
dol_include_once("/commande/class/commande.class.php");
dol_include_once("/supplier_proposal/class/supplier_proposal.class.php");
dol_include_once('/suppplierorderfromorder/class/sofo.class.php');
if (isModEnabled('categorie')) {
dol_include_once('/categories/class/categorie.class.php');
}
global $bc, $conf, $db, $langs, $user;
$prod = new Product($db);
$langs->load("products");
$langs->load("stocks");
$langs->load("orders");
$langs->load("supplierorderfromorder@supplierorderfromorder");
$hookmanager->initHooks(array('ordercustomer')); // Note that conf->hooks_modules contains array
$dolibarr_version35 = false;
$week_to_replenish = 0;
if ((float)DOL_VERSION >= 3.5) {
$dolibarr_version35 = true;
}
/*echo "<form name=\"formCreateSupplierOrder\" method=\"post\" action=\"ordercustomer.php\">";*/
// Security check
if (!empty($user->societe_id)) {
$socid = $user->societe_id;
}
$result = restrictedArea($user, 'produit|service&supplierorderfromorder');
//checks if a product has been ordered
$action = GETPOST('action', 'alpha');
$sref = GETPOST('sref', 'alpha');
$snom = GETPOST('snom', 'alpha');
$search_all = GETPOST('search_all', 'alpha');
$type = GETPOST('type', 'int');
$tobuy = GETPOST('tobuy', 'int');
$salert = GETPOST('salert', 'alpha');
$fourn_id = GETPOST('fourn_id', 'intcomma');
$sortfield = GETPOST('sortfield', 'alpha');
$sortorder = GETPOST('sortorder', 'alpha');
$page = GETPOST('page', 'int');
$page = intval($page);
$selectedSupplier = GETPOST('useSameSupplier', 'int');
$group_lines_by_product = GETPOSTISSET('group_lines_by_product', 'int') ? GETPOST('group_lines_by_product', 'int') : ( getDolGlobalInt('SOFO_GROUP_LINES_BY_PRODUCT') );
$id = GETPOST('id','int');
$origin_page = 'ordercustomer';
if (!$sortfield) {
$sortfield = 'cd.rang';
}
if (!$sortorder) {
$sortorder = 'ASC';
}
$conf->liste_limit = 1000; // Pas de pagination sur cet écran
$limit = $conf->liste_limit;
$offset = $limit * $page;
$TCategories = array();
if (isModEnabled('categorie')) {
if (!isset($_REQUEST['categorie']) && getDolGlobalString('SOFO_DEFAULT_PRODUCT_CATEGORY_FILTER')) {
$TCategories = unserialize(getDolGlobalString('SOFO_DEFAULT_PRODUCT_CATEGORY_FILTER') );
} else {
$categories = GETPOST('categorie', 'none');
if (is_array($categories)) {
if (in_array(-1, $categories) && count($categories) > 1) {
unset($categories[array_search(-1, $categories)]);
}
$TCategories = array_map('intval', $categories);
} elseif ($categories > 0) {
$TCategories = array(intval($categories));
} else {
$TCategories = array(-1);
}
}
}
$TCategoriesQuery = $TCategories;
if (!empty($TCategoriesQuery) && is_array($TCategoriesQuery)) {
foreach ($TCategories as $categID) {
if ($categID <= 0)
continue;
$cat = new Categorie($db);
$cat->fetch($categID);
$TSubCat = get_categs_enfants($cat);
foreach ($TSubCat as $subCatID) {
if (!in_array($subCatID, $TCategories)) {
$TCategoriesQuery[] = $subCatID;
}
}
}
}
if (is_array($TCategoriesQuery) && count($TCategoriesQuery) == 1 && in_array(-1, $TCategoriesQuery)) {
$TCategoriesQuery = array();
}
/*
* Actions
*/
$parameters = array('id' => $id);
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if(empty($reshook))
{
if($action == 'valid-propal') $getNomUrlConcat = '';
if (isset($_POST['button_removefilter']) || in_array($action, array('valid-propal', 'valid-order'))) {
$sref = '';
$snom = '';
$sal = '';
$salert = '';
$TCategoriesQuery = array();
$TCategories = array(-1);
}
/*echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
exit;*/
//orders creation
//FIXME: could go in the lib
if (in_array($action, array('valid-propal', 'valid-order'))) {
$actionTarget = 'order';
if ($action == 'valid-propal') {
$actionTarget = 'propal';
}
$linecount = GETPOST('linecount', 'int');
$box = false;
unset($_POST['linecount']);
if ($linecount > 0) {
$suppliers = array();
for ($i = 0; $i < $linecount; $i++) {
if (GETPOST('check' . $i, 'alpha') === 'on' && (GETPOST('fourn' . $i, 'int') > 0 || GETPOST('fourn_free' . $i, 'int') > 0)) { //one line
_prepareLine($i, $actionTarget);
}
unset($_POST[$i]);
}
//we now know how many orders we need and what lines they have
$i = 0;
$id = 0;
$nb_orders_created = 0;
$orders = array();
$suppliersid = array_keys($suppliers);
$projectid = GETPOST('projectid', 'int');
foreach ($suppliers as $idsupplier => $supplier) {
if ($actionTarget == 'propal') {
$order = new SupplierProposal($db);
$obj = _getSupplierProposalInfos($idsupplier, $projectid);
} else {
$order = new CommandeFournisseur($db);
$obj = _getSupplierOrderInfos($idsupplier, $projectid);
}
$commandeClient = new Commande($db);
$commandeClient->fetch(GETPOST('id','int'));
// Test recupération contact livraison
if (getDolGlobalString('SUPPLIERORDER_FROM_ORDER_CONTACT_DELIVERY')) {
$contact_ship = $commandeClient->getIdContact('external', 'SHIPPING');
$contact_ship = $contact_ship[0] ?? '';
} else {
$contact_ship = null;
}
//Si une commande au statut brouillon existe déjà et que l'option SOFO_CREATE_NEW_SUPPLIER_ODER_ANY_TIME
if ($obj && !getDolGlobalString('SOFO_CREATE_NEW_SUPPLIER_ODER_ANY_TIME')) {
$order->fetch($obj->rowid);
$order->socid = $idsupplier;
if (!empty($projectid)) {
$order->fk_project = GETPOST('projectid', 'int');
}
// On vérifie qu'il n'existe pas déjà un lien entre la commande client et la commande fournisseur dans la table element_element.
// S'il n'y en a pas, on l'ajoute, sinon, on ne l'ajoute pas
$order->fetchObjectLinked('', 'commande', $order->id, 'order_supplier');
$order->add_object_linked('commande', GETPOST('id','int'));
// cond reglement, mode reglement, delivery date
_appliCond($order, $commandeClient);
$id++; //$id doit être renseigné dans tous les cas pour que s'affiche le message 'Vos commandes ont été générées'
$newCommande = false;
} else {
$order->socid = $idsupplier;
if (!empty($projectid)) {
$order->fk_project = GETPOST('projectid', 'int');
}
// cond reglement, mode reglement, delivery date
_appliCond($order, $commandeClient);
$id = $order->create($user);
if (getDolGlobalInt('SUPPLIERORDER_FROM_ORDER_NOTES_PUBLIC')){
$publicNote = $commandeClient->note_public;
$order->update_note($publicNote,'_public');
}
if (getDolGlobalInt('SUPPLIERORDER_FROM_ORDER_NOTES_PRIVATE')){
$privateNote = $commandeClient->note_private;
$order->update_note($privateNote,'_private');
}
if ($contact_ship && getDolGlobalString('SUPPLIERORDER_FROM_ORDER_CONTACT_DELIVERY'))
$order->add_contact($contact_ship, 'SHIPPING');
$order->add_object_linked('commande', GETPOST('id','int'));
$newCommande = true;
$nb_orders_created++;
}
$order_id = $order->id;
if(!empty($order_id) && $action == 'valid-propal') $getNomUrlConcat .=' '.$order->getNomUrl();
//trick to know which orders have been generated this way
$order->source = 42;
$MaxAvailability = 0;
foreach ($supplier['lines'] as $line) {
$done = false;
$prodfourn = new ProductFournisseur($db);
$prodfourn->fetch_product_fournisseur_price($_REQUEST['fourn' . $i]);
foreach ($order->lines as $lineOrderFetched) {
$q = 'SELECT ee.rowid
FROM '.MAIN_DB_PREFIX.'element_element ee
WHERE ee.sourcetype="commandedet"
AND ee.targettype = "commande_fournisseurdet"
AND ee.fk_source = '.((int)$line->id).'
AND ee.fk_target = '.((int)$lineOrderFetched->id);
$resultquery = $db->query($q);
$id_line_element_element=0;
if(!empty($resultquery)) {
$res = $db->fetch_object($resultquery);
$id_line_element_element = $res->rowid;
}
if (!empty($id_line_element_element)) {
$remise_percent = $lineOrderFetched->remise_percent;
if ($line->remise_percent > $remise_percent)
$remise_percent = $line->remise_percent;
if ($order->element == 'order_supplier') {
$order->updateline(
$lineOrderFetched->id,
$lineOrderFetched->desc,
// FIXME: The current existing line may very well not be at the same purchase price
$lineOrderFetched->pu_ht,
$lineOrderFetched->qty + $line->qty,
$remise_percent,
$lineOrderFetched->tva_tx
);
} else if ($order->element == 'supplier_proposal') {
$order->updateline(
$lineOrderFetched->id,
$prodfourn->fourn_unitprice, //$lineOrderFetched->pu_ht is empty,
$lineOrderFetched->qty + $line->qty,
$remise_percent,
$lineOrderFetched->tva_tx,
0, //$txlocaltax1=0,
0, //$txlocaltax2=0,
$lineOrderFetched->desc
//$price_base_type='HT',
//$info_bits=0,
//$special_code=0,
//$fk_parent_line=0,
//$skip_update_total=0,
//$fk_fournprice=0,
//$pa_ht=0,
//$label='',
//$type=0,
//$array_option=0,
//$ref_fourn='',
//$fk_unit=''
);
}
$done = true;
break;
}
}
// On ajoute une ligne seulement si un "updateline()" n'a pas été fait et si la quantité souhaitée est supérieure à zéro
if (!$done) {
if ($order->element == 'order_supplier') {
$cf_line_id = $order->addline(
$line->desc,
$line->subprice,
$line->qty,
$line->tva_tx,
null,
null,
$line->fk_product,
// We need to pass fk_prod_fourn_price to get the right price.
$line->fk_prod_fourn_price,
$line->ref_fourn,
$line->remise_percent
, 'HT'
, 0
, $line->product_type
, $line->info_bits
, FALSE // $notrigger
, NULL // $date_start
, NULL // $date_end
, $line->array_options
, null
, 0
, $line->origin
, $line->origin_id
);
// Création d'un lien entre ligne de commande client et ligne de commande fournisseur
$cf_line = new CommandeFournisseurLigne($db);
$cf_line->element = 'commande_fournisseurdet';
$cf_line->id = $cf_line_id;
$cf_line->add_object_linked('commandedet', $line->origin_id);
} else if ($order->element == 'supplier_proposal') {
$order->addline(
$line->desc,
$line->subprice,
$line->qty,
$line->tva_tx,
null,
null,
$line->fk_product,
$line->remise_percent,
'HT',
0, //$pu_ttc=0,
$line->info_bits, //$info_bits=0,
$line->product_type, //$type=0,
-1, //$rang=-1,
0, //$special_code=0, ,
0, //$fk_parent_line=0, ,
$line->fk_prod_fourn_price, //$fk_fournprice=0, ,
0, //$pa_ht=0, ,
'', //$label='',,
$line->array_options, //$array_option=0, ,
$line->ref_fourn, //$ref_fourn='', ,
'', //$fk_unit='', ,
$line->origin, //$origin='', ,
$line->origin_id//$origin_id=0
);
}
}
$nb_day = (int)TSOFO::getMinAvailability($line->fk_product, $line->qty, 1, $prodfourn->fourn_id);
if ($MaxAvailability < $nb_day) {
$MaxAvailability = $nb_day;
}
}
if (getDolGlobalString('SOFO_USE_MAX_DELIVERY_DATE')) {
$order->delivery_date = dol_now() + $MaxAvailability * 86400;
if (version_compare(DOL_VERSION, '14', '>=')) {
$order->setDeliveryDate($user, $order->delivery_date);
} else {
$order->set_date_livraison($user, $order->delivery_date);
}
}
$order->cond_reglement_id = 0;
$order->mode_reglement_id = 0;
if ($id < 0) {
$fail++; // FIXME: declare somewhere and use, or get rid of it!
$msg = $langs->trans('OrderFail') . " : ";
$msg .= $order->error;
setEventMessage($msg, 'errors');
} else {
// CODE de redirection s'il y a un seul fournisseur (évite de le laisser sur la page sans comprendre)
if (getDolGlobalString('SUPPLIERORDER_FROM_ORDER_HEADER_SUPPLIER_ORDER')) {
if (count($suppliersid) == 1) {
if ($action === 'valid-order'){
$link = dol_buildpath('/fourn/commande/card.php?id=' . $order_id, 1);
}
else{
$link = dol_buildpath('/supplier_proposal/card.php?id=' . $order_id, 1);
}
header('Location:' . $link);exit();
}
}
}
$i++;
}
$id = GETPOST('id','int');
$origin_page = 'ordercustomer';
if($action == 'valid-order') header("Location: ".DOL_URL_ROOT."/fourn/commande/list.php?id=".$id.'&origin_page='.$origin_page);
else if($action == 'valid-propal' && !empty($getNomUrlConcat)) setEventMessage($langs->trans('SupplierProposalSuccessfullyCreated').$getNomUrlConcat, 'mesgs');
}
if ($nb_orders_created > 0) {
setEventMessages($langs->trans('supplierorderfromorder_nb_orders_created', $nb_orders_created), array());
}
if ($box === false) {
setEventMessage($langs->trans('SelectProduct'), 'warnings');
} else {
foreach ($suppliers as $idSupplier => $lines) {
$j = 0;
foreach ($lines as $line) {
$sql = "SELECT quantity";
$sql .= " FROM " . MAIN_DB_PREFIX . "product_fournisseur_price";
$sql .= " WHERE fk_soc = " . $idSupplier;
$sql .= " AND fk_product = " . $line[$j]->fk_product;
$sql .= " ORDER BY quantity ASC";
$sql .= " LIMIT 1";
$resql = $db->query($sql);
if ($resql) {
$resql = $db->fetch_object($resql);
//echo $j;
if ($line[$j]->qty < $resql->quantity) {
$p = new Product($db);
$p->fetch($line[$j]->fk_product);
$f = new Fournisseur($db);
$f->fetch($idSupplier);
$rates[$f->name] = $p->label;
} else {
$p = new Product($db);
$p->fetch($line[$j]->fk_product);
$f = new Fournisseur($db);
$f->fetch($idSupplier);
$ajoutes[$f->name] = $p->label;
}
}
/*echo "<pre>";
print_r($rates);
echo "</pre>";
echo "<pre>";
print_r($ajoutes);
echo "</pre>";*/
$j++;
}
}
$mess = "";
// FIXME: declare $ajoutes somewhere. It's unclear if it should be reinitialized or not in the interlocking loops.
if (!empty($ajoutes)) {
foreach ($ajoutes as $nomFournisseur => $nomProd) {
if ($actionTarget == 'propal') {
$mess .= $langs->trans('ProductAddToSupplierQuotation', $nomProd, $nomFournisseur) . '<br />';
} else {
$mess .= $langs->trans('ProductAddToSupplierOrder', $nomProd, $nomFournisseur) . '<br />';
}
}
}
// FIXME: same as $ajoutes.
if (!empty($rates)) {
foreach ($rates as $nomFournisseur => $nomProd) {
$mess .= "Quantité insuffisante de ' " . $nomProd . " ' pour le fournisseur ' " . $nomFournisseur . " '<br />";
}
}
if (!empty($rates)) {
setEventMessage($mess, 'warnings');
} else {
setEventMessage($mess, 'mesgs');
}
}
}
if (in_array($action, array('view-valid-order'))) {
header("Location: ".DOL_URL_ROOT."/fourn/commande/list.php?id=".$id.'&origin_page='.$origin_page);
}
}
/*
* View
*/
$param = (isset($type) ? '&type=' . $type : '');
$TCachedProductId =& $_SESSION['TCachedProductId'];
if (empty($TCachedProductId))
$TCachedProductId = array();
if (GETPOST('purge_cached_product', 'none') == 'yes')
$TCachedProductId = array();
//Do we want include shared sotck to kwon what order
if (!getDolGlobalString('SOFO_CHECK_STOCK_ON_SHARED_STOCK')) {
$entityToTest = $conf->entity;
} else {
$entityToTest = getEntity('stock');
}
$title = $langs->trans('ProductsToOrder');
$db->query("SET SQL_MODE=''");
$sql = 'SELECT prod.rowid, prod.ref, prod.label, cd.description, prod.price, cd.qty as qty, COALESCE(SUM(ed.qty), 0) as qty_shipped, cd.buy_price_ht';
$sql .= ', prod.price_ttc, prod.price_base_type,prod.fk_product_type';
$sql .= ', prod.tms as datem, prod.duration, prod.tobuy, prod.seuil_stock_alerte, cd.rang,';
if (in_array($db->type, array('pgsql'))) {
$sql .= ' string_agg(DISTINCT cd.rowid::character varying, \'@\') as lineid,';
} else {
$sql .= ' GROUP_CONCAT(cd.rowid SEPARATOR "@") as lineid,';
}
$sql .= ' ( SELECT SUM(s.reel) FROM ' . $db->prefix() . 'product_stock s';
$sql .= ' INNER JOIN ' . $db->prefix() . 'entrepot as entre ON entre.rowid=s.fk_entrepot';
$sql .= ' WHERE s.fk_product=prod.rowid AND entre.entity IN (' . $entityToTest . ')) as stock_physique';
$sql .= $dolibarr_version35 ? ', prod.desiredstock' : "";
$sql .= ' FROM ' . $db->prefix() . 'product as prod';
// Inclure fk_commande dans la sous-requête
$sql .= ' LEFT OUTER JOIN (';
$sql .= ' SELECT fk_product, fk_commande, SUM(qty) as qty, description, MAX(buy_price_ht) as buy_price_ht, MAX(rang) as rang, GROUP_CONCAT(rowid SEPARATOR "@") as rowid';
$sql .= ' FROM ' . $db->prefix() . 'commandedet';
$sql .= ' GROUP BY fk_product, fk_commande';
$sql .= ') as cd ON prod.rowid = cd.fk_product';
if ((float)DOL_VERSION >= 20.0) {
$sql .= ' LEFT JOIN ' . $db->prefix() . 'expeditiondet as ed ON (cd.rowid = ed.fk_elementdet)';
}else{
$sql .= ' LEFT JOIN ' . $db->prefix() . 'expeditiondet as ed ON (cd.rowid = ed.fk_origin_line)';
}
if (!empty($TCategoriesQuery)) {
$sql .= ' LEFT OUTER JOIN ' . $db->prefix() . 'categorie_product as cp ON (prod.rowid = cp.fk_product)';
}
$sql .= ' WHERE prod.fk_product_type IN (0,1) AND prod.entity IN (' . getEntity("product", 1) . ')';
$fk_commande = GETPOST('id', 'int');
if (intval($fk_commande) > 0) {
// Appliquer le filtre sur fk_commande
$sql .= ' AND cd.fk_commande = ' . $fk_commande;
}
if (!empty($TCategoriesQuery)) {
$sql .= ' AND cp.fk_categorie IN ( ' . implode(',', $TCategoriesQuery) . ' ) ';
}
if ($search_all) {
$sql .= ' AND (prod.ref LIKE "%' . $db->escape($search_all) . '%" ';
$sql .= 'OR prod.label LIKE "%' . $db->escape($search_all) . '%" ';
$sql .= 'OR prod.description LIKE "%' . $db->escape($search_all) . '%" ';
$sql .= 'OR prod.note LIKE "%' . $db->escape($search_all) . '%")';
}
// if the type is not 1, we show all products (type = 0,2,3)
if (dol_strlen($type)) {
if ($type == 1) {
$sql .= ' AND prod.fk_product_type = 1';
} else {
$sql .= ' AND prod.fk_product_type != 1';
}
}
if ($sref) {
//natural search
$scrit = explode(' ', $sref);
foreach ($scrit as $crit) {
$sql .= ' AND prod.ref LIKE "%' . $crit . '%"';
}
}
if ($snom) {
//natural search
$scrit = explode(' ', $snom);
foreach ($scrit as $crit) {
$sql .= ' AND prod.label LIKE "%' . $db->escape($crit) . '%"';
}
}
$sql .= ' AND prod.tobuy = 1';
if (!empty($canvas)) {
$sql .= ' AND prod.canvas = "' . $db->escape($canvas) . '"';
}
if ($salert == 'on') {
$sql .= " AND prod.seuil_stock_alerte is not NULL ";
}
$sql .= ' GROUP BY prod.rowid, prod.ref, prod.label, prod.price';
$sql .= ', prod.price_ttc, prod.price_base_type,prod.fk_product_type, prod.tms';
$sql .= ', prod.duration, prod.tobuy, prod.seuil_stock_alerte';
//$sql .= ', cd.rang';
//$sql .= ', prod.desiredstock';
//$sql .= ', s.fk_product';
if ($salert == 'on') {
$sql .= ' HAVING stock_physique < prod.seuil_stock_alerte ';
$alertchecked = 'checked="checked"';
}
$sql2 = '';
//On prend les lignes libre
if (GETPOST('id','int') && getDolGlobalString('SOFO_ADD_FREE_LINES')) {
$sql2 .= 'SELECT cd.rowid, cd.description, cd.qty as qty, cd.product_type, cd.price, cd.buy_price_ht
FROM ' . $db->prefix() . 'commandedet as cd
LEFT JOIN ' . $db->prefix() . 'commande as c ON (cd.fk_commande = c.rowid)
WHERE c.rowid = ' . GETPOST('id','int') . ' AND cd.product_type IN(0,1) AND fk_product IS NULL';
if (getDolGlobalString('SUPPORDERFROMORDER_USE_ORDER_DESC')) {
$sql2 .= ' GROUP BY cd.description';
}
}
$sql .= $db->order($sortfield, $sortorder);
if (getDolGlobalString('SOFO_USE_DELIVERY_TIME'))
$sql .= $db->plimit($limit + 1, $offset);
$resql = $db->query($sql);
if (isset($_REQUEST['DEBUG']) || $resql === false) {
dol_print_error($db);
exit;
}
if ($sql2 && $fk_commande > 0) {
$sql2 .= $db->order($sortfield, $sortorder);
$sql2 .= $db->plimit($limit + 1, $offset);
$resql2 = $db->query($sql2);
}
$form = new Form($db);
if ($resql || $resql2) {
$num = $db->num_rows($resql);
//pour chaque produit de la commande client on récupère ses sous-produits
$TProducts= array(); //on rassemble produit et sous-produit dans ce tableau
$i = 0;
while ($i < min($num, $limit)) {
//fetch le produit
$objp = $db->fetch_object($resql);
array_push($TProducts, $objp);
$product = new Product($db);
$product->fetch($objp->rowid);
if(getDolGlobalString('PRODUIT_SOUSPRODUITS') && getDolGlobalString('SOFO_VIRTUAL_PRODUCTS')) {
//récupération des sous-produits
$product->get_sousproduits_arbo();
$prods_arbo = $product->get_arbo_each_prod();
if (!empty($prods_arbo)) {
$TProductToHaveQtys = array(); //tableau des dernières quantités à commander par niveau
foreach ($prods_arbo as $key => $value) {
//si on est au premier niveau, on réinitialise
if ($value['level'] == 1) {
$TProductToHaveQtys[$value['level']] = $objp->qty;
$qtyParentToHave = $TProductToHaveQtys[$value['level']];
}
//si on est au niveau supérieur à 1, alors on récupère la quantité de produit parent à avoir
if ($value['level'] > 1) {
$qtyParentToHave = $TProductToHaveQtys[$value['level'] - 1];
}
//on définit l'objet sous produit
$objsp = new stdClass();
$sousproduit = new Product($db);
$sousproduit->fetch($value['id']);
$objsp->rowid = $sousproduit->id;
$objsp->ref = $sousproduit->ref;
$objsp->label = $sousproduit->label;
$objsp->price = $sousproduit->price;
$objsp->price_ttc = $sousproduit->price_ttc;
$objsp->price_base_type = $sousproduit->price_base_type;
$objsp->fk_product_type = $sousproduit->type;
$objsp->datem = $sousproduit->date_modification;
$objsp->duration = $sousproduit->duration_value;
$objsp->tobuy = $sousproduit->status_buy;
$objsp->seuil_stock_alert = $sousproduit->seuil_stock_alerte;
$objsp->stock_physique = $sousproduit->stock_reel;
$objsp->qty = $qtyParentToHave * $value['nb']; //qty du produit = quantité du produit parent commandé * nombre du sous-produit nécessaire pour le produit parent
$objsp->desiredstock = $sousproduit->desiredstock;
$objsp->fk_parent = $value['id_parent'];
$objsp->level = $value['level'];
//Sauvegarde du dernier stock commandé pour le niveau du sous-produit
$TProductToHaveQtys[$value['level']] = $objsp->qty;
//ajout du sous-produit dans le tableau
array_push($TProducts, $objsp);
}
}
}
$i++;
}
$i = 0;
$num = count($TProducts);
$num2 = $sql2 ? $db->num_rows($resql2) : 0;
$helpurl = 'EN:Module_Stocks_En|FR:Module_Stock|';
$helpurl .= 'ES:Módulo_Stocks';
llxHeader('', $title, $helpurl, $title);
$includeProduct = '';
if (getDolGlobalInt('INCLUDE_PRODUCT_LINES_WITH_ADEQUATE_STOCK') == 1) {
$includeProduct = '&show_stock_no_need=yes';
$param .= '&show_stock_no_need=yes';
}
$head = array();
$head[0][0] = dol_buildpath('/supplierorderfromorder/ordercustomer.php?id=' . GETPOST('id','int').'&origin_page='.$origin_page.$includeProduct, 2);
$head[0][1] = $title;
$head[0][2] = 'supplierorderfromorder';
if (getDolGlobalString('SOFO_USE_NOMENCLATURE')) {
$head[1][0] = dol_buildpath('/supplierorderfromorder/dispatch_to_supplier_order.php?from=commande&fromid=' . GETPOST('id','int'), 2);
$head[1][1] = $langs->trans('ProductsAssetsToOrder');
$head[1][2] = 'supplierorderfromorder_dispatch';
}
/*$head[1][0] = DOL_URL_ROOT.'/product/stock/replenishorders.php';
$head[1][1] = $langs->trans("ReplenishmentOrders");
$head[1][2] = 'replenishorders';*/
dol_fiche_head($head, 'supplierorderfromorder', $langs->trans('Replenishment'), -1, 'stock');
$origin = New Commande($db);
$id = GETPOST('id','int');
$res = $origin->fetch($id);
if ($res > 0 ){
$morehtmlref='<div class="refidno">';
$morehtmlref.= $langs->trans('InitialCommande').$origin->getNomUrl();
$morehtmlref.='</div>';
dol_banner_tab($origin, 'ref', '', 0, 'ref', 'ref', $morehtmlref );
}
if ($sref || $snom || $search_all || $salert || GETPOST('search', 'alpha')) {
$filters = '&sref=' . $sref . '&snom=' . $snom;
$filters .= '&search_all=' . $search_all;
$filters .= '&salert=' . $salert;
if (!getDolGlobalInt('SOFO_USE_DELIVERY_TIME') ) {
print_barre_liste(
$title,
$page,
'ordercustomer.php',
$filters,
$sortfield,
$sortorder,
'',
$num);
}
} else {
$filters = '&sref=' . $sref . '&snom=' . $snom;
$filters .= '&fourn_id=' . $fourn_id;
$filters .= (isset($type) ? '&type=' . $type : '');
$filters .= '&salert=' . $salert;
if (getDolGlobalString('SOFO_USE_DELIVERY_TIME')) {
print_barre_liste(
$title,
$page,
'ordercustomer.php',
$filters,
$sortfield,
$sortorder,
'',
$num
);
}
}
if(getDolGlobalString('SOFO_QTY_LINES_COMES_FROM_ORIGIN_ORDER_ONLY')) {
print '<br>'.img_warning().' <STRONG><span style="color:red">' . $langs->trans('SOFO_QTY_LINES_COMES_FROM_ORIGIN_ORDER_ONLY') . '</span></STRONG><br>';
}
$yesno = getDolGlobalString('INCLUDE_PRODUCT_LINES_WITH_ADEQUATE_STOCK') ? '&show_stock_no_need=yes' : '';
print'</div>';
print '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . GETPOST('id','int') . '&projectid=' . (!empty($_REQUEST['projectid'])?$_REQUEST['projectid']:'') . $yesno .'" method="post" name="formulaire">' .
'<input type="hidden" name="id" value="' . GETPOST('id','int') . '">' .
'<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">' .
'<input type="hidden" name="sortfield" value="' . $sortfield . '">' .
'<input type="hidden" name="sortorder" value="' . $sortorder . '">' .
'<input type="hidden" name="type" value="' . $type . '">' .
'<input type="hidden" name="linecount" value="' . ($num + $num2) . '">' .
'<input type="hidden" name="group_lines_by_product" value="' . $group_lines_by_product . '">' .
'<input type="hidden" name="fk_commande" value="' . GETPOST('fk_commande', 'int') . '">' .
'<input type="hidden" name="show_stock_no_need" value="' . GETPOST('show_stock_no_need', 'none') . '">' ;
if (getDolGlobalInt('INCLUDE_PRODUCT_LINES_WITH_ADEQUATE_STOCK') == 0) {
echo '<div style="text-align:right"><a href="'.$_SERVER["PHP_SELF"].'?'.$_SERVER["QUERY_STRING"].'&show_stock_no_need=yes">'.$langs->trans('ShowLineEvenIfStockIsSuffisant').'</a></div><br>';
}
if (!empty($TCachedProductId)) {
echo '<a style="color:red; font-weight:bold;" href="' . $_SERVER["PHP_SELF"] . '?' . $_SERVER["QUERY_STRING"] . '&purge_cached_product=yes">' . $langs->trans('PurgeSessionForCachedProduct') . '</a><br>';
}
if(!empty($group_lines_by_product)) {
print '<STRONG>'.$langs->trans('SOFO_GROUP_LINES_BY_PRODUCT').'</STRONG> / <a href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&group_lines_by_product=0'.$param.'">'.$langs->trans('DontGroupByProduct').'</a>'.img_help(1, $langs->trans('GroupByProductHelp')).'<br><br>';
} else {
print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&group_lines_by_product=1'.$param.'">'.$langs->trans('SOFO_GROUP_LINES_BY_PRODUCT').'</a> / <STRONG>'.$langs->trans('DontGroupByProduct').'</STRONG>'.img_help(1, $langs->trans('GroupByProductHelp')).'<br><br>';
}
print '<div style="text-align:right"> </div>' .
'<table class="liste" width="100%">';
$colspan = 9;
if (getDolGlobalString('FOURN_PRODUCT_AVAILABILITY'))
$colspan++;
if (getDolGlobalString('SOFO_USE_DELIVERY_TIME')) {
$colspan++;
}
if (isModEnabled('categorie') && getDolGlobalString('SOFO_DISPLAY_CAT_COLUMN')) {
$colspan++;
}
if (isModEnabled('service') && $type == 1) {
$colspan++;
}
if ($dolibarr_version35) {
$colspan++;
}
$colspan++;
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (!empty($reshook)) {
print $hookmanager->resPrint;
}
if (getDolGlobalString('SOFO_USE_DELIVERY_TIME')) {
$week_to_replenish = (int)GETPOST('week_to_replenish', 'int');
print '<tr class="liste_titre">' .
'<td colspan="' . $colspan . '">' . $langs->trans('NbWeekToReplenish') . '<input type="text" name="week_to_replenish" value="' . $week_to_replenish . '" size="2"> '
. '<input type="submit" value="' . $langs->trans('ReCalculate') . '" /></td>';
print '</tr>';
}
if (isModEnabled('categorie')) {
print '<tr class="liste_titre_filter">';
print '<td colspan="2" >';
print $langs->trans("Categories");
print '</td>';
print '<td colspan="' . ($colspan - 1) . '" >';
print getCatMultiselect('categorie', $TCategories);
print '<a id="clearfilter" href="javascript:;">' . $langs->trans('DeleteFilter') . '</a>';
?>
<script type="text/javascript">
$('a#clearfilter').click(function () {
$('option:selected', $('select#categorie')).prop('selected', false);
$('option[value=-1]', $('select#categorie')).prop('selected', true);
$('form[name=formulaire]').submit();
return false;
})
</script>
<?php
print '</td>';
print '</tr>';
}
$param .= '&fourn_id=' . $fourn_id . '&snom=' . $snom . '&salert=' . $salert;
$param .= '&sref=' . $sref;
$param .= '&group_lines_by_product='.$group_lines_by_product;
// Lignes des titres
print '<tr class="liste_titre_filter">' .
'<th class="liste_titre"><input type="checkbox" onClick="toggle(this)" /></th>';
print_liste_field_titre(
$langs->trans('Ref'),
'ordercustomer.php',
'prod.ref',
$param,
'id=' . GETPOST('id','int'),
'',
$sortfield,
$sortorder
);
print_liste_field_titre(
$langs->trans('Label'),
'ordercustomer.php',
'prod.label',
$param,
'id=' . GETPOST('id','int'),
'',
$sortfield,
$sortorder
);
if (isModEnabled('categorie') && getDolGlobalString('SOFO_DISPLAY_CAT_COLUMN')) {