Test Failed
Branch main (fda838)
by Rafael
50:22
created

AccountingSupplierController   F

Complexity

Total Complexity 324

Size/Duplication

Total Lines 2147
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1456
dl 0
loc 2147
rs 0.8
c 1
b 0
f 0
wmc 324

4 Methods

Rating   Name   Duplication   Size   Complexity  
F list() 0 796 135
F lines() 0 561 86
F card() 0 158 16
F index() 0 603 87

How to fix   Complexity   

Complex Class

Complex classes like AccountingSupplierController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AccountingSupplierController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2004       Rodolphe Quiedeville    <[email protected]>
4
 * Copyright (C) 2005       Simon TOSSER            <[email protected]>
5
 * Copyright (C) 2013-2016  Olivier Geffroy         <[email protected]>
6
 * Copyright (C) 2013-2024	Alexandre Spangaro		<[email protected]>
7
 * Copyright (C) 2014-2015	Ari Elbaz (elarifr)		<[email protected]>
8
 * Copyright (C) 2013-2021	Florian Henry			<[email protected]>
9
 * Copyright (C) 2021      	Gauthier VERDOL         <[email protected]>
10
 * Copyright (C) 2014       Juanjo Menent           <[email protected]>s
11
 * Copyright (C) 2016       Laurent Destailleur     <[email protected]>
12
 * Copyright (C) 2024       Rafael San José         <[email protected]>
13
 *
14
 * This program is free software; you can redistribute it and/or modify
15
 * it under the terms of the GNU General Public License as published by
16
 * the Free Software Foundation; either version 3 of the License, or
17
 * (at your option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful,
20
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22
 * GNU General Public License for more details.
23
 *
24
 * You should have received a copy of the GNU General Public License
25
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26
 */
27
28
namespace DoliModules\Accounting\Controller;
29
30
global $conf;
31
global $db;
32
global $user;
33
global $hookmanager;
34
global $user;
35
global $menumanager;
36
global $langs;
37
global $mysoc;
38
39
// Load Dolibarr environment
40
require BASE_PATH . '/main.inc.php';
41
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formaccounting.class.php';
42
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formcompany.class.php';
43
require_once DOL_DOCUMENT_ROOT . '/core/class/html.formother.class.php';
44
require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
45
require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
46
require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
47
require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
48
require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.product.class.php';
49
require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
50
51
use AccountingAccount;
52
use DoliCore\Base\DolibarrController;
53
use FactureFournisseur;
54
use Form;
55
use FormAccounting;
56
use FormOther;
57
use Product;
58
use Societe;
59
use SupplierInvoiceLine;
60
61
class AccountingSupplierController extends DolibarrController
0 ignored issues
show
Deprecated Code introduced by
The class DoliCore\Base\DolibarrController has been deprecated: This class is only needed for compatibility with Dolibarr. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

61
class AccountingSupplierController extends /** @scrutinizer ignore-deprecated */ DolibarrController
Loading history...
62
{
63
64
    /**
65
     * \file    htdocs/accountancy/supplier/card.php
66
     * \ingroup Accountancy (Double entries)
67
     * \brief   Card supplier ventilation
68
     */
69
    public function card()
70
    {
71
        global $conf;
72
        global $db;
73
        global $user;
74
        global $hookmanager;
75
        global $user;
76
        global $menumanager;
77
        global $langs;
78
79
// Load translation files required by the page
80
        $langs->loadLangs(array("bills", "accountancy"));
81
82
        $action = GETPOST('action', 'aZ09');
83
        $cancel = GETPOST('cancel', 'alpha');
84
        $backtopage = GETPOST('backtopage', 'alpha');
85
86
        $codeventil = GETPOSTINT('codeventil');
87
        $id = GETPOSTINT('id');
88
89
// Security check
90
        if (!isModEnabled('accounting')) {
91
            accessforbidden();
92
        }
93
        if ($user->socid > 0) {
94
            accessforbidden();
95
        }
96
        if (!$user->hasRight('accounting', 'mouvements', 'lire')) {
97
            accessforbidden();
98
        }
99
100
101
        /*
102
         * Actions
103
         */
104
105
        if ($action == 'ventil' && $user->hasRight('accounting', 'bind', 'write')) {
106
            if (!$cancel) {
107
                if ($codeventil < 0) {
108
                    $codeventil = 0;
109
                }
110
111
                $sql = " UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det";
112
                $sql .= " SET fk_code_ventilation = " . ((int) $codeventil);
113
                $sql .= " WHERE rowid = " . ((int) $id);
114
115
                $resql = $db->query($sql);
116
                if (!$resql) {
117
                    setEventMessages($db->lasterror(), null, 'errors');
118
                } else {
119
                    setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
120
                    if ($backtopage) {
121
                        header("Location: " . $backtopage);
122
                        exit();
123
                    }
124
                }
125
            } else {
126
                header("Location: ./lines.php");
127
                exit();
128
            }
129
        }
130
131
132
133
        /*
134
         * View
135
         */
136
        $help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#Liaisons_comptables';
137
138
        llxHeader("", $langs->trans('FicheVentilation'), $help_url);
139
140
        if ($cancel == $langs->trans("Cancel")) {
141
            $action = '';
142
        }
143
144
// Create
145
        $form = new Form($db);
146
        $facturefournisseur_static = new FactureFournisseur($db);
147
        $formaccounting = new FormAccounting($db);
148
149
        if (!empty($id)) {
150
            $sql = "SELECT f.ref as ref, f.rowid as facid, l.fk_product, l.description, l.rowid, l.fk_code_ventilation, ";
151
            $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label,";
152
            if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
153
                $sql .= " ppe.accountancy_code_buy as code_buy,";
154
            } else {
155
                $sql .= " p.accountancy_code_buy as code_buy,";
156
            }
157
            $sql .= " aa.account_number, aa.label";
158
            $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as l";
159
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product";
160
            if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
161
                $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
162
            }
163
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON l.fk_code_ventilation = aa.rowid";
164
            $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture_fourn as f ON f.rowid = l.fk_facture_fourn ";
165
            $sql .= " WHERE f.fk_statut > 0 AND l.rowid = " . ((int) $id);
166
            $sql .= " AND f.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy
167
168
            dol_syslog("/accounting/supplier/card.php", LOG_DEBUG);
169
            $result = $db->query($sql);
170
171
            if ($result) {
172
                $num_lines = $db->num_rows($result);
173
                $i = 0;
174
175
                if ($num_lines) {
176
                    $objp = $db->fetch_object($result);
177
178
                    print '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '" method="post">' . "\n";
179
                    print '<input type="hidden" name="token" value="' . newToken() . '">';
180
                    print '<input type="hidden" name="action" value="ventil">';
181
                    print '<input type="hidden" name="backtopage" value="' . dol_escape_htmltag($backtopage) . '">';
182
183
                    print load_fiche_titre($langs->trans('SuppliersVentilation'), '', 'title_accountancy');
184
185
                    print dol_get_fiche_head();
186
187
                    print '<table class="border centpercent">';
188
189
                    // ref invoice
190
                    print '<tr><td>' . $langs->trans("BillsSuppliers") . '</td>';
191
                    $facturefournisseur_static->ref = $objp->ref;
192
                    $facturefournisseur_static->id = $objp->facid;
193
                    print '<td>' . $facturefournisseur_static->getNomUrl(1) . '</td>';
194
                    print '</tr>';
195
196
                    print '<tr><td width="20%">' . $langs->trans("Line") . '</td>';
197
                    print '<td>' . stripslashes(nl2br($objp->description)) . '</td></tr>';
198
                    print '<tr><td width="20%">' . $langs->trans("ProductLabel") . '</td>';
199
                    print '<td>' . dol_trunc($objp->product_label, 24) . '</td>';
200
                    print '<tr><td width="20%">' . $langs->trans("Account") . '</td><td>';
201
                    print $formaccounting->select_account($objp->fk_code_ventilation, 'codeventil', 1);
202
                    print '</td></tr>';
203
                    print '</table>';
204
205
                    print dol_get_fiche_end();
206
207
                    print '<div class="center">';
208
                    print '<input class="button button-save" type="submit" value="' . $langs->trans("Save") . '">';
209
                    print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
210
                    print '<input class="button button-cancel" type="submit" name="cancel" value="' . $langs->trans("Cancel") . '">';
211
                    print '</div>';
212
213
                    print '</form>';
214
                } else {
215
                    print "Error";
216
                }
217
            } else {
218
                print "Error";
219
            }
220
        } else {
221
            print "Error ID incorrect";
222
        }
223
224
// End of page
225
        llxFooter();
226
        $db->close();
227
    }
228
229
    /**
230
     * \file        htdocs/accountancy/supplier/index.php
231
     * \ingroup     Accountancy (Double entries)
232
     * \brief       Home supplier journalization page
233
     */
234
    public function index()
235
    {
236
        global $conf;
237
        global $db;
238
        global $user;
239
        global $hookmanager;
240
        global $user;
241
        global $menumanager;
242
        global $langs;
243
244
// Load translation files required by the page
245
        $langs->loadLangs(array("compta", "bills", "other", "accountancy"));
246
247
        $validatemonth = GETPOSTINT('validatemonth');
248
        $validateyear = GETPOSTINT('validateyear');
249
250
// Security check
251
        if (!isModEnabled('accounting')) {
252
            accessforbidden();
253
        }
254
        if ($user->socid > 0) {
255
            accessforbidden();
256
        }
257
        if (!$user->hasRight('accounting', 'bind', 'write')) {
258
            accessforbidden();
259
        }
260
261
        $accountingAccount = new AccountingAccount($db);
262
263
        $month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1);
264
        if (GETPOSTINT("year")) {
265
            $year_start = GETPOSTINT("year");
266
        } else {
267
            $year_start = dol_print_date(dol_now(), '%Y');
268
            if (dol_print_date(dol_now(), '%m') < $month_start) {
269
                $year_start--; // If current month is lower that starting fiscal month, we start last year
270
            }
271
        }
272
        $year_end = $year_start + 1;
273
        $month_end = $month_start - 1;
274
        if ($month_end < 1) {
275
            $month_end = 12;
276
            $year_end--;
277
        }
278
        $search_date_start = dol_mktime(0, 0, 0, $month_start, 1, $year_start);
279
        $search_date_end = dol_get_last_day($year_end, $month_end);
280
        $year_current = $year_start;
281
282
// Validate History
283
        $action = GETPOST('action', 'aZ09');
284
285
        $chartaccountcode = dol_getIdFromCode($db, getDolGlobalInt('CHARTOFACCOUNTS'), 'accounting_system', 'rowid', 'pcg_version');
286
287
// Security check
288
        if (!isModEnabled('accounting')) {
289
            accessforbidden();
290
        }
291
        if ($user->socid > 0) {
292
            accessforbidden();
293
        }
294
        if (!$user->hasRight('accounting', 'mouvements', 'lire')) {
295
            accessforbidden();
296
        }
297
298
299
        /*
300
         * Actions
301
         */
302
303
        if (($action == 'clean' || $action == 'validatehistory') && $user->hasRight('accounting', 'bind', 'write')) {
304
            // Clean database
305
            $db->begin();
306
            $sql1 = "UPDATE " . $db->prefix() . "facture_fourn_det as fd";
307
            $sql1 .= " SET fk_code_ventilation = 0";
308
            $sql1 .= ' WHERE fd.fk_code_ventilation NOT IN';
309
            $sql1 .= '	(SELECT accnt.rowid ';
310
            $sql1 .= "	FROM " . $db->prefix() . "accounting_account as accnt";
311
            $sql1 .= "	INNER JOIN " . $db->prefix() . "accounting_system as syst";
312
            $sql1 .= "	ON accnt.fk_pcg_version = syst.pcg_version AND syst.rowid = " . getDolGlobalInt('CHARTOFACCOUNTS') . " AND accnt.entity = " . ((int) $conf->entity) . ")";
313
            $sql1 .= " AND fd.fk_facture_fourn IN (SELECT rowid FROM " . $db->prefix() . "facture_fourn WHERE entity = " . ((int) $conf->entity) . ")";
314
            $sql1 .= " AND fk_code_ventilation <> 0";
315
316
            dol_syslog("htdocs/accountancy/customer/index.php fixaccountancycode", LOG_DEBUG);
317
            $resql1 = $db->query($sql1);
318
            if (!$resql1) {
319
                $error++;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $error seems to be never defined.
Loading history...
320
                $db->rollback();
321
                setEventMessages($db->lasterror(), null, 'errors');
322
            } else {
323
                $db->commit();
324
            }
325
            // End clean database
326
        }
327
328
        if ($action == 'validatehistory') {
329
            $error = 0;
330
            $nbbinddone = 0;
331
            $nbbindfailed = 0;
332
            $notpossible = 0;
333
334
            $db->begin();
335
336
            // Now make the binding. Bind automatically only for product with a dedicated account that exists into chart of account, others need a manual bind
337
            // Supplier Invoice Lines (must be same request than into page list.php for manual binding)
338
            $sql = "SELECT f.rowid as facid, f.ref, f.ref_supplier, f.libelle as invoice_label, f.datef, f.type as ftype, f.fk_facture_source,";
339
            $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,";
340
            $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,";
341
            if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
342
                $sql .= " ppe.accountancy_code_buy as code_buy, ppe.accountancy_code_buy_intra as code_buy_intra, ppe.accountancy_code_buy_export as code_buy_export,";
343
            } else {
344
                $sql .= " p.accountancy_code_buy as code_buy, p.accountancy_code_buy_intra as code_buy_intra, p.accountancy_code_buy_export as code_buy_export,";
345
            }
346
            $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export, aa4.rowid as aarowid_thirdparty,";
347
            $sql .= " co.code as country_code, co.label as country_label,";
348
            $sql .= " s.tva_intra,";
349
            if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
350
                $sql .= " spe.accountancy_code_buy as company_code_buy";
351
            } else {
352
                $sql .= " s.accountancy_code_buy as company_code_buy";
353
            }
354
            $sql .= " FROM " . $db->prefix() . "facture_fourn as f";
355
            $sql .= " INNER JOIN " . $db->prefix() . "societe as s ON s.rowid = f.fk_soc";
356
            if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
357
                $sql .= " LEFT JOIN " . $db->prefix() . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
358
            }
359
            $sql .= " LEFT JOIN " . $db->prefix() . "c_country as co ON co.rowid = s.fk_pays ";
360
            $sql .= " INNER JOIN " . $db->prefix() . "facture_fourn_det as l ON f.rowid = l.fk_facture_fourn";
361
            $sql .= " LEFT JOIN " . $db->prefix() . "product as p ON p.rowid = l.fk_product";
362
            if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
363
                $sql .= " LEFT JOIN " . $db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
364
            }
365
            $alias_societe_perentity = !getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED') ? "s" : "spe";
366
            $alias_product_perentity = !getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED') ? "p" : "ppe";
367
            $sql .= " LEFT JOIN " . $db->prefix() . "accounting_account as aa  ON " . $alias_product_perentity . ".accountancy_code_buy = aa.account_number         AND aa.active = 1  AND aa.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa.entity = " . $conf->entity;
368
            $sql .= " LEFT JOIN " . $db->prefix() . "accounting_account as aa2 ON " . $alias_product_perentity . ".accountancy_code_buy_intra = aa2.account_number  AND aa2.active = 1 AND aa2.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa2.entity = " . $conf->entity;
369
            $sql .= " LEFT JOIN " . $db->prefix() . "accounting_account as aa3 ON " . $alias_product_perentity . ".accountancy_code_buy_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa3.entity = " . $conf->entity;
370
            $sql .= " LEFT JOIN " . $db->prefix() . "accounting_account as aa4 ON " . $alias_product_perentity . ".accountancy_code_buy = aa4.account_number        AND aa4.active = 1 AND aa4.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa4.entity = " . $conf->entity;
371
            $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0";
372
            $sql .= " AND l.product_type <= 2";
373
            $sql .= " AND f.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy
374
            if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
375
                $sql .= " AND f.datef >= '" . $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) . "'";
376
            }
377
            if ($validatemonth && $validateyear) {
378
                $sql .= dolSqlDateFilter('f.datef', 0, $validatemonth, $validateyear);
379
            }
380
381
            dol_syslog('htdocs/accountancy/supplier/index.php');
382
383
            $result = $db->query($sql);
384
            if (!$result) {
385
                $error++;
386
                setEventMessages($db->lasterror(), null, 'errors');
387
            } else {
388
                $num_lines = $db->num_rows($result);
389
390
                $isBuyerInEEC = isInEEC($mysoc);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mysoc seems to be never defined.
Loading history...
391
392
                $thirdpartystatic = new Societe($db);
393
                $facture_static = new FactureFournisseur($db);
394
                $facture_static_det = new SupplierInvoiceLine($db);
395
                $product_static = new Product($db);
396
397
                $i = 0;
398
                while ($i < min($num_lines, 10000)) {   // No more than 10000 at once
399
                    $objp = $db->fetch_object($result);
400
401
                    $thirdpartystatic->id = $objp->socid;
402
                    $thirdpartystatic->name = $objp->name;
403
                    $thirdpartystatic->client = $objp->client;
404
                    $thirdpartystatic->fournisseur = $objp->fournisseur;
405
                    $thirdpartystatic->code_client = $objp->code_client;
406
                    $thirdpartystatic->code_compta_client = $objp->code_compta_client;
407
                    $thirdpartystatic->code_fournisseur = $objp->code_fournisseur;
408
                    $thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur;
409
                    $thirdpartystatic->email = $objp->email;
410
                    $thirdpartystatic->country_code = $objp->country_code;
411
                    $thirdpartystatic->tva_intra = $objp->tva_intra;
412
                    $thirdpartystatic->code_compta_product = $objp->company_code_buy;       // The accounting account for product stored on thirdparty object (for level3 suggestion)
413
414
                    $product_static->ref = $objp->product_ref;
415
                    $product_static->id = $objp->product_id;
416
                    $product_static->type = $objp->type;
417
                    $product_static->label = $objp->product_label;
418
                    $product_static->status = $objp->status;
419
                    $product_static->status_buy = $objp->status_buy;
420
                    $product_static->accountancy_code_sell = $objp->code_sell;
421
                    $product_static->accountancy_code_sell_intra = $objp->code_sell_intra;
422
                    $product_static->accountancy_code_sell_export = $objp->code_sell_export;
423
                    $product_static->accountancy_code_buy = $objp->code_buy;
424
                    $product_static->accountancy_code_buy_intra = $objp->code_buy_intra;
425
                    $product_static->accountancy_code_buy_export = $objp->code_buy_export;
426
                    $product_static->tva_tx = $objp->tva_tx_prod;
427
428
                    $facture_static->ref = $objp->ref;
429
                    $facture_static->id = $objp->facid;
430
                    $facture_static->type = $objp->ftype;
431
                    $facture_static->ref_supplier = $objp->ref_supplier;
432
                    $facture_static->label = $objp->invoice_label;
433
                    $facture_static->date = $db->jdate($objp->datef);
434
                    $facture_static->fk_facture_source = $objp->fk_facture_source;
435
436
                    $facture_static_det->id = $objp->rowid;
437
                    $facture_static_det->total_ht = $objp->total_ht;
438
                    $facture_static_det->tva_tx = $objp->tva_tx_line;
439
                    $facture_static_det->vat_src_code = $objp->vat_src_code;
440
                    $facture_static_det->product_type = $objp->type_l;
441
                    $facture_static_det->desc = $objp->description;
442
443
                    $accountingAccountArray = array(
444
                        'dom' => $objp->aarowid,
445
                        'intra' => $objp->aarowid_intra,
446
                        'export' => $objp->aarowid_export,
447
                        'thirdparty' => $objp->aarowid_thirdparty);
448
449
                    $code_buy_p_notset = '';
450
                    $code_buy_t_notset = '';
451
452
                    $suggestedid = 0;
453
454
                    $return = $accountingAccount->getAccountingCodeToBind($mysoc, $thirdpartystatic, $product_static, $facture_static, $facture_static_det, $accountingAccountArray, 'supplier');
455
                    if (!is_array($return) && $return < 0) {
456
                        setEventMessage($accountingAccount->error, 'errors');
457
                    } else {
458
                        $suggestedid = $return['suggestedid'];
459
                        $suggestedaccountingaccountfor = $return['suggestedaccountingaccountfor'];
460
461
                        if (!empty($suggestedid) && $suggestedaccountingaccountfor != '' && $suggestedaccountingaccountfor != 'eecwithoutvatnumber') {
462
                            $suggestedid = $return['suggestedid'];
463
                        } else {
464
                            $suggestedid = 0;
465
                        }
466
                    }
467
468
                    if ($suggestedid > 0) {
469
                        $sqlupdate = "UPDATE " . $db->prefix() . "facture_fourn_det";
470
                        $sqlupdate .= " SET fk_code_ventilation = " . ((int) $suggestedid);
471
                        $sqlupdate .= " WHERE fk_code_ventilation <= 0 AND product_type <= 2 AND rowid = " . ((int) $facture_static_det->id);
472
473
                        $resqlupdate = $db->query($sqlupdate);
474
                        if (!$resqlupdate) {
475
                            $error++;
476
                            setEventMessages($db->lasterror(), null, 'errors');
477
                            $nbbindfailed++;
478
                            break;
479
                        } else {
480
                            $nbbinddone++;
481
                        }
482
                    } else {
483
                        $notpossible++;
484
                        $nbbindfailed++;
485
                    }
486
487
                    $i++;
488
                }
489
                if ($num_lines > 10000) {
490
                    $notpossible += ($num_lines - 10000);
491
                }
492
            }
493
494
            if ($error) {
495
                $db->rollback();
496
            } else {
497
                $db->commit();
498
                setEventMessages($langs->trans('AutomaticBindingDone', $nbbinddone, $notpossible), null, ($notpossible ? 'warnings' : 'mesgs'));
499
                if ($nbbindfailed) {
500
                    setEventMessages($langs->trans('DoManualBindingForFailedRecord', $nbbindfailed), null, 'warnings');
501
                }
502
            }
503
        }
504
505
506
        /*
507
         * View
508
         */
509
        $help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#Liaisons_comptables';
510
511
        llxHeader('', $langs->trans("SuppliersVentilation"), $help_url);
512
513
        $textprevyear = '<a href="' . $_SERVER['PHP_SELF'] . '?year=' . ($year_current - 1) . '">' . img_previous() . '</a>';
514
        $textnextyear = '&nbsp;<a href="' . $_SERVER['PHP_SELF'] . '?year=' . ($year_current + 1) . '">' . img_next() . '</a>';
515
516
        print load_fiche_titre($langs->trans("SuppliersVentilation") . " " . $textprevyear . "&nbsp;" . $langs->trans("Year") . "&nbsp;" . $year_start . "&nbsp;" . $textnextyear, '', 'title_accountancy');
517
518
        print '<span class="opacitymedium">' . $langs->trans("DescVentilSupplier") . '</span><br>';
519
        print '<span class="opacitymedium hideonsmartphone">' . $langs->trans("DescVentilMore", $langs->transnoentitiesnoconv("ValidateHistory"), $langs->transnoentitiesnoconv("ToBind")) . '<br>';
520
        print '</span><br>';
521
522
        $y = $year_current;
523
524
        $buttonbind = '<a class="button small" href="' . $_SERVER['PHP_SELF'] . '?action=validatehistory&token=' . newToken() . '">' . img_picto('', 'link', 'class="paddingright fa-color-unset smallpaddingimp"') . $langs->trans("ValidateHistory") . '</a>';
525
526
527
        print_barre_liste(img_picto('', 'unlink', 'class="paddingright fa-color-unset"') . $langs->trans("OverviewOfAmountOfLinesNotBound"), '', '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1, 0, $buttonbind);
528
//print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesNotBound"), $buttonbind, '');
529
530
        print '<div class="div-table-responsive-no-min">';
531
        print '<table class="noborder centpercent">';
532
        print '<tr class="liste_titre"><td class="minwidth100">' . $langs->trans("Account") . '</td>';
533
        print '<td>' . $langs->trans("Label") . '</td>';
534
        for ($i = 1; $i <= 12; $i++) {
535
            $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
536
            if ($j > 12) {
537
                $j -= 12;
538
            }
539
            $cursormonth = $j;
540
            if ($cursormonth > 12) {
541
                $cursormonth -= 12;
542
            }
543
            $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
544
            $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
545
546
            print '<td width="60" class="right">';
547
            if (!empty($tmp['mday'])) {
548
                $param = 'search_date_startday=1&search_date_startmonth=' . $cursormonth . '&search_date_startyear=' . $cursoryear;
549
                $param .= '&search_date_endday=' . $tmp['mday'] . '&search_date_endmonth=' . $tmp['mon'] . '&search_date_endyear=' . $tmp['year'];
550
                print '<a href="' . DOL_URL_ROOT . '/accountancy/supplier/list.php?' . $param . '">';
551
            }
552
            print $langs->trans('MonthShort' . str_pad((int) $j, 2, '0', STR_PAD_LEFT));
553
            if (!empty($tmp['mday'])) {
554
                print '</a>';
555
            }
556
            print '</td>';
557
        }
558
        print '<td width="60" class="right"><b>' . $langs->trans("Total") . '</b></td></tr>';
559
560
        $sql = "SELECT " . $db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number') . " AS codecomptable,";
561
        $sql .= "  " . $db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label') . " AS intitule,";
562
        for ($i = 1; $i <= 12; $i++) {
563
            $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
564
            if ($j > 12) {
565
                $j -= 12;
566
            }
567
            $sql .= "  SUM(" . $db->ifsql("MONTH(ff.datef) = " . ((int) $j), "ffd.total_ht", "0") . ") AS month" . str_pad((int) $j, 2, "0", STR_PAD_LEFT) . ",";
568
        }
569
        $sql .= "  SUM(ffd.total_ht) as total";
570
        $sql .= " FROM " . $db->prefix() . "facture_fourn_det as ffd";
571
        $sql .= "  LEFT JOIN " . $db->prefix() . "facture_fourn as ff ON ff.rowid = ffd.fk_facture_fourn";
572
        $sql .= "  LEFT JOIN " . $db->prefix() . "accounting_account as aa ON aa.rowid = ffd.fk_code_ventilation";
573
        $sql .= " WHERE ff.datef >= '" . $db->idate($search_date_start) . "'";
574
        $sql .= "  AND ff.datef <= '" . $db->idate($search_date_end) . "'";
575
// Define begin binding date
576
        if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
577
            $sql .= " AND ff.datef >= '" . $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) . "'";
578
        }
579
        $sql .= "  AND ff.fk_statut > 0";
580
        $sql .= "  AND ffd.product_type <= 2";
581
        $sql .= " AND ff.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy
582
        $sql .= " AND aa.account_number IS NULL";
583
        if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
584
            $sql .= " AND ff.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . ")";
585
        } else {
586
            $sql .= " AND ff.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . "," . FactureFournisseur::TYPE_DEPOSIT . ")";
587
        }
588
        $sql .= " GROUP BY ffd.fk_code_ventilation,aa.account_number,aa.label";
589
590
        dol_syslog('htdocs/accountancy/supplier/index.php', LOG_DEBUG);
591
        $resql = $db->query($sql);
592
        if ($resql) {
593
            $num = $db->num_rows($resql);
594
595
            while ($row = $db->fetch_row($resql)) {
596
                print '<tr class="oddeven">';
597
                print '<td>';
598
                if ($row[0] == 'tobind') {
599
                    print '<span class="opacitymedium">' . $langs->trans("Unknown") . '</span>';
600
                } else {
601
                    print length_accountg($row[0]);
602
                }
603
                print '</td>';
604
                print '<td>';
605
                if ($row[0] == 'tobind') {
606
                    $startmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1);
607
                    if ($startmonth > 12) {
608
                        $startmonth -= 12;
609
                    }
610
                    $startyear = ($startmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
611
                    $endmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + 11;
612
                    if ($endmonth > 12) {
613
                        $endmonth -= 12;
614
                    }
615
                    $endyear = ($endmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
616
                    print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT . '/accountancy/supplier/list.php?search_date_startday=1&search_date_startmonth=' . ((int) $startmonth) . '&search_date_startyear=' . ((int) $startyear) . '&search_date_endday=&search_date_endmonth=' . ((int) $endmonth) . '&search_date_endyear=' . ((int) $endyear), $langs->transnoentitiesnoconv("ToBind"));
617
                } else {
618
                    print $row[1];
619
                }
620
                print '</td>';
621
                for ($i = 2; $i <= 13; $i++) {
622
                    $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2);
623
                    if ($cursormonth > 12) {
624
                        $cursormonth -= 12;
625
                    }
626
                    $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
627
                    $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
628
629
                    print '<td class="right nowraponall amount">';
630
                    print price($row[$i]);
631
                    // Add link to make binding
632
                    if (!empty(price2num($row[$i]))) {
633
                        print '<a href="' . $_SERVER['PHP_SELF'] . '?action=validatehistory&year=' . $y . '&validatemonth=' . ((int) $cursormonth) . '&validateyear=' . ((int) $cursoryear) . '&token=' . newToken() . '">';
634
                        print img_picto($langs->trans("ValidateHistory") . ' (' . $langs->trans('Month' . str_pad($cursormonth, 2, '0', STR_PAD_LEFT)) . ' ' . $cursoryear . ')', 'link', 'class="marginleft2"');
635
                        print '</a>';
636
                    }
637
                    print '</td>';
638
                }
639
                print '<td class="right nowraponall amount"><b>' . price($row[14]) . '</b></td>';
640
                print '</tr>';
641
            }
642
            $db->free($resql);
643
644
            if ($num == 0) {
645
                print '<tr class="oddeven"><td colspan="16">';
646
                print '<span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span>';
647
                print '</td></tr>';
648
            }
649
        } else {
650
            print $db->lasterror(); // Show last sql error
651
        }
652
        print "</table>\n";
653
        print '</div>';
654
655
656
        print '<br>';
657
658
659
        print_barre_liste(img_picto('', 'link', 'class="paddingright fa-color-unset"') . $langs->trans("OverviewOfAmountOfLinesBound"), '', '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1);
660
//print load_fiche_titre($langs->trans("OverviewOfAmountOfLinesBound"), '', '');
661
662
        print '<div class="div-table-responsive-no-min">';
663
        print '<table class="noborder centpercent">';
664
        print '<tr class="liste_titre"><td class="minwidth100">' . $langs->trans("Account") . '</td>';
665
        print '<td>' . $langs->trans("Label") . '</td>';
666
        for ($i = 1; $i <= 12; $i++) {
667
            $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
668
            if ($j > 12) {
669
                $j -= 12;
670
            }
671
            $cursormonth = $j;
672
            if ($cursormonth > 12) {
673
                $cursormonth -= 12;
674
            }
675
            $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y;
676
            $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt');
677
678
            print '<td width="60" class="right">';
679
            if (!empty($tmp['mday'])) {
680
                $param = 'search_date_startday=1&search_date_startmonth=' . $cursormonth . '&search_date_startyear=' . $cursoryear;
681
                $param .= '&search_date_endday=' . $tmp['mday'] . '&search_date_endmonth=' . $tmp['mon'] . '&search_date_endyear=' . $tmp['year'];
682
                print '<a href="' . DOL_URL_ROOT . '/accountancy/supplier/lines.php?' . $param . '">';
683
            }
684
            print $langs->trans('MonthShort' . str_pad($j, 2, '0', STR_PAD_LEFT));
685
            if (!empty($tmp['mday'])) {
686
                print '</a>';
687
            }
688
            print '</td>';
689
        }
690
        print '<td width="60" class="right"><b>' . $langs->trans("Total") . '</b></td></tr>';
691
692
        $sql = "SELECT " . $db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number') . " AS codecomptable,";
693
        $sql .= "  " . $db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label') . " AS intitule,";
694
        for ($i = 1; $i <= 12; $i++) {
695
            $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
696
            if ($j > 12) {
697
                $j -= 12;
698
            }
699
            $sql .= "  SUM(" . $db->ifsql("MONTH(ff.datef) = " . ((int) $j), "ffd.total_ht", "0") . ") AS month" . str_pad((int) $j, 2, "0", STR_PAD_LEFT) . ",";
700
        }
701
        $sql .= "  SUM(ffd.total_ht) as total";
702
        $sql .= " FROM " . $db->prefix() . "facture_fourn_det as ffd";
703
        $sql .= "  LEFT JOIN " . $db->prefix() . "facture_fourn as ff ON ff.rowid = ffd.fk_facture_fourn";
704
        $sql .= "  LEFT JOIN " . $db->prefix() . "accounting_account as aa ON aa.rowid = ffd.fk_code_ventilation";
705
        $sql .= " WHERE ff.datef >= '" . $db->idate($search_date_start) . "'";
706
        $sql .= "  AND ff.datef <= '" . $db->idate($search_date_end) . "'";
707
// Define begin binding date
708
        if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
709
            $sql .= " AND ff.datef >= '" . $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) . "'";
710
        }
711
        $sql .= " AND ff.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy
712
        $sql .= "  AND ff.fk_statut > 0";
713
        $sql .= "  AND ffd.product_type <= 2";
714
        if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
715
            $sql .= " AND ff.type IN (" . FactureFournisseur::TYPE_STANDARD . ", " . FactureFournisseur::TYPE_REPLACEMENT . ", " . FactureFournisseur::TYPE_CREDIT_NOTE . ")";
716
        } else {
717
            $sql .= " AND ff.type IN (" . FactureFournisseur::TYPE_STANDARD . ", " . FactureFournisseur::TYPE_REPLACEMENT . ", " . FactureFournisseur::TYPE_CREDIT_NOTE . ", " . FactureFournisseur::TYPE_DEPOSIT . ")";
718
        }
719
        $sql .= " AND aa.account_number IS NOT NULL";
720
        $sql .= " GROUP BY ffd.fk_code_ventilation,aa.account_number,aa.label";
721
        $sql .= ' ORDER BY aa.account_number';
722
723
        dol_syslog('htdocs/accountancy/supplier/index.php');
724
        $resql = $db->query($sql);
725
        if ($resql) {
726
            $num = $db->num_rows($resql);
727
728
            while ($row = $db->fetch_row($resql)) {
729
                print '<tr class="oddeven">';
730
                print '<td>';
731
                if ($row[0] == 'tobind') {
732
                    print $langs->trans("Unknown");
733
                } else {
734
                    print length_accountg($row[0]);
735
                }
736
                print '</td>';
737
738
                print '<td class="tdoverflowmax300"' . (empty($row[1]) ? '' : ' title="' . dol_escape_htmltag($row[1]) . '"') . '>';
739
                if ($row[0] == 'tobind') {
740
                    print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT . '/accountancy/supplier/list.php?search_year=' . ((int) $y), $langs->transnoentitiesnoconv("ToBind"));
741
                } else {
742
                    print dol_escape_htmltag($row[1]);
743
                }
744
                print '</td>';
745
746
                for ($i = 2; $i <= 13; $i++) {
747
                    print '<td class="right nowraponall amount">';
748
                    print price($row[$i]);
749
                    print '</td>';
750
                }
751
                print '<td class="right nowraponall amount"><b>' . price($row[14]) . '</b></td>';
752
                print '</tr>';
753
            }
754
            $db->free($resql);
755
756
            if ($num == 0) {
757
                print '<tr class="oddeven"><td colspan="16">';
758
                print '<span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span>';
759
                print '</td></tr>';
760
            }
761
        } else {
762
            print $db->lasterror(); // Show last sql error
763
        }
764
        print "</table>\n";
765
        print '</div>';
766
767
768
        if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This part of code looks strange. Why showing a report that should rely on result of this step ?
769
            print '<br>';
770
            print '<br>';
771
772
            print_barre_liste($langs->trans("OtherInfo"), '', '', '', '', '', '', -1, '', '', 0, '', '', 0, 1, 1);
773
            //print load_fiche_titre($langs->trans("OtherInfo"), '', '');
774
775
            print '<div class="div-table-responsive-no-min">';
776
            print '<table class="noborder centpercent">';
777
            print '<tr class="liste_titre"><td>' . $langs->trans("Total") . '</td>';
778
            for ($i = 1; $i <= 12; $i++) {
779
                $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
780
                if ($j > 12) {
781
                    $j -= 12;
782
                }
783
                print '<td width="60" class="right">' . $langs->trans('MonthShort' . str_pad((int) $j, 2, '0', STR_PAD_LEFT)) . '</td>';
784
            }
785
            print '<td width="60" class="right"><b>' . $langs->trans("Total") . '</b></td></tr>';
786
787
            $sql = "SELECT '" . $db->escape($langs->trans("CAHTF")) . "' AS label,";
788
            for ($i = 1; $i <= 12; $i++) {
789
                $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1;
790
                if ($j > 12) {
791
                    $j -= 12;
792
                }
793
                $sql .= "  SUM(" . $db->ifsql("MONTH(ff.datef) = " . ((int) $j), "ffd.total_ht", "0") . ") AS month" . str_pad((int) $j, 2, "0", STR_PAD_LEFT) . ",";
794
            }
795
            $sql .= "  SUM(ffd.total_ht) as total";
796
            $sql .= " FROM " . $db->prefix() . "facture_fourn_det as ffd";
797
            $sql .= "  LEFT JOIN " . $db->prefix() . "facture_fourn as ff ON ff.rowid = ffd.fk_facture_fourn";
798
            $sql .= " WHERE ff.datef >= '" . $db->idate($search_date_start) . "'";
799
            $sql .= "  AND ff.datef <= '" . $db->idate($search_date_end) . "'";
800
            // Define begin binding date
801
            if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
802
                $sql .= " AND ff.datef >= '" . $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) . "'";
803
            }
804
            $sql .= " AND ff.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy
805
            $sql .= "  AND ff.fk_statut > 0";
806
            $sql .= "  AND ffd.product_type <= 2";
807
            if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
808
                $sql .= " AND ff.type IN (" . FactureFournisseur::TYPE_STANDARD . ", " . FactureFournisseur::TYPE_REPLACEMENT . ", " . FactureFournisseur::TYPE_CREDIT_NOTE . ")";
809
            } else {
810
                $sql .= " AND ff.type IN (" . FactureFournisseur::TYPE_STANDARD . ", " . FactureFournisseur::TYPE_REPLACEMENT . ", " . FactureFournisseur::TYPE_CREDIT_NOTE . ", " . FactureFournisseur::TYPE_DEPOSIT . ")";
811
            }
812
813
            dol_syslog('htdocs/accountancy/supplier/index.php');
814
            $resql = $db->query($sql);
815
            if ($resql) {
816
                $num = $db->num_rows($resql);
817
818
                while ($row = $db->fetch_row($resql)) {
819
                    print '<tr><td>' . $row[0] . '</td>';
820
                    for ($i = 1; $i <= 12; $i++) {
821
                        print '<td class="right nowraponall amount">' . price($row[$i]) . '</td>';
822
                    }
823
                    print '<td class="right nowraponall amount"><b>' . price($row[13]) . '</b></td>';
824
                    print '</tr>';
825
                }
826
                $db->free($resql);
827
            } else {
828
                print $db->lasterror(); // Show last sql error
829
            }
830
            print "</table>\n";
831
            print '</div>';
832
        }
833
834
// End of page
835
        llxFooter();
836
        $db->close();
837
    }
838
839
    /**
840
     * \file        htdocs/accountancy/supplier/lines.php
841
     * \ingroup     Accountancy (Double entries)
842
     * \brief       Page of detail of the lines of ventilation of invoices suppliers
843
     */
844
    public function lines()
845
    {
846
        global $conf;
847
        global $db;
848
        global $user;
849
        global $hookmanager;
850
        global $user;
851
        global $menumanager;
852
        global $langs;
853
854
// Load translation files required by the page
855
        $langs->loadLangs(array("compta", "bills", "other", "accountancy", "productbatch", "products"));
856
857
        $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
858
859
        $account_parent = GETPOST('account_parent');
860
        $changeaccount = GETPOST('changeaccount');
861
// Search Getpost
862
        $search_societe = GETPOST('search_societe', 'alpha');
863
        $search_lineid = GETPOSTINT('search_lineid');
864
        $search_ref = GETPOST('search_ref', 'alpha');
865
        $search_invoice = GETPOST('search_invoice', 'alpha');
866
//$search_ref_supplier = GETPOST('search_ref_supplier', 'alpha');
867
        $search_label = GETPOST('search_label', 'alpha');
868
        $search_desc = GETPOST('search_desc', 'alpha');
869
        $search_amount = GETPOST('search_amount', 'alpha');
870
        $search_account = GETPOST('search_account', 'alpha');
871
        $search_vat = GETPOST('search_vat', 'alpha');
872
        $search_date_startday = GETPOSTINT('search_date_startday');
873
        $search_date_startmonth = GETPOSTINT('search_date_startmonth');
874
        $search_date_startyear = GETPOSTINT('search_date_startyear');
875
        $search_date_endday = GETPOSTINT('search_date_endday');
876
        $search_date_endmonth = GETPOSTINT('search_date_endmonth');
877
        $search_date_endyear = GETPOSTINT('search_date_endyear');
878
        $search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear);   // Use tzserver
879
        $search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear);
880
        $search_country = GETPOST('search_country', 'alpha');
881
        $search_tvaintra = GETPOST('search_tvaintra', 'alpha');
882
883
// Load variable for pagination
884
        $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit);
885
        $sortfield = GETPOST('sortfield', 'aZ09comma');
886
        $sortorder = GETPOST('sortorder', 'aZ09comma');
887
        $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
888
        if (empty($page) || $page < 0) {
889
            $page = 0;
890
        }
891
        $offset = $limit * $page;
892
        $pageprev = $page - 1;
893
        $pagenext = $page + 1;
894
        if (!$sortfield) {
895
            $sortfield = "f.datef, f.ref, l.rowid";
896
        }
897
        if (!$sortorder) {
898
            if (getDolGlobalInt('ACCOUNTING_LIST_SORT_VENTILATION_DONE') > 0) {
899
                $sortorder = "DESC";
900
            } else {
901
                $sortorder = "ASC";
902
            }
903
        }
904
905
        $formaccounting = new FormAccounting($db);
906
907
// Security check
908
        if (!isModEnabled('accounting')) {
909
            accessforbidden();
910
        }
911
        if ($user->socid > 0) {
912
            accessforbidden();
913
        }
914
        if (!$user->hasRight('accounting', 'mouvements', 'lire')) {
915
            accessforbidden();
916
        }
917
918
919
        $formaccounting = new FormAccounting($db);
920
921
922
        /*
923
         * Actions
924
         */
925
926
// Purge search criteria
927
        if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
928
            $search_societe = '';
929
            $search_lineid = '';
930
            $search_ref = '';
931
            $search_invoice = '';
932
            //$search_ref_supplier = '';
933
            $search_label = '';
934
            $search_desc = '';
935
            $search_amount = '';
936
            $search_account = '';
937
            $search_vat = '';
938
            $search_date_startday = '';
939
            $search_date_startmonth = '';
940
            $search_date_startyear = '';
941
            $search_date_endday = '';
942
            $search_date_endmonth = '';
943
            $search_date_endyear = '';
944
            $search_date_start = '';
945
            $search_date_end = '';
946
            $search_country = '';
947
            $search_tvaintra = '';
948
        }
949
950
        if (is_array($changeaccount) && count($changeaccount) > 0 && $user->hasRight('accounting', 'bind', 'write')) {
951
            $error = 0;
952
953
            if (!(GETPOSTINT('account_parent') >= 0)) {
954
                $error++;
955
                setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Account")), null, 'errors');
956
            }
957
958
            if (!$error) {
959
                $db->begin();
960
961
                $sql1 = "UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det";
962
                $sql1 .= " SET fk_code_ventilation=" . (GETPOSTINT('account_parent') > 0 ? GETPOSTINT('account_parent') : '0');
963
                $sql1 .= ' WHERE rowid IN (' . $db->sanitize(implode(',', $changeaccount)) . ')';
964
965
                dol_syslog('accountancy/supplier/lines.php::changeaccount sql= ' . $sql1);
966
                $resql1 = $db->query($sql1);
967
                if (!$resql1) {
968
                    $error++;
969
                    setEventMessages($db->lasterror(), null, 'errors');
970
                }
971
                if (!$error) {
972
                    $db->commit();
973
                    setEventMessages($langs->trans("Save"), null, 'mesgs');
974
                } else {
975
                    $db->rollback();
976
                    setEventMessages($db->lasterror(), null, 'errors');
977
                }
978
979
                $account_parent = ''; // Protection to avoid to mass apply it a second time
980
            }
981
        }
982
983
        if (GETPOST('sortfield') == 'f.datef, f.ref, l.rowid') {
984
            $value = (GETPOST('sortorder') == 'asc,asc,asc' ? 0 : 1);
985
            require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
986
            $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_DONE", $value, 'yesno', 0, '', $conf->entity);
987
        }
988
989
990
        /*
991
         * View
992
         */
993
994
        $form = new Form($db);
995
        $formother = new FormOther($db);
996
997
        $help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#Liaisons_comptables';
998
999
        llxHeader('', $langs->trans("SuppliersVentilation") . ' - ' . $langs->trans("Dispatched"), $help_url);
1000
1001
        print '<script type="text/javascript">
1002
			$(function () {
1003
				$(\'#select-all\').click(function(event) {
1004
				    // Iterate each checkbox
1005
				    $(\':checkbox\').each(function() {
1006
				    	this.checked = true;
1007
				    });
1008
			    });
1009
			    $(\'#unselect-all\').click(function(event) {
1010
				    // Iterate each checkbox
1011
				    $(\':checkbox\').each(function() {
1012
				    	this.checked = false;
1013
				    });
1014
			    });
1015
			});
1016
			 </script>';
1017
1018
        /*
1019
         * Supplier Invoice lines
1020
         */
1021
        $sql = "SELECT f.rowid as facid, f.ref as ref, f.ref_supplier, f.type as ftype, f.libelle as invoice_label, f.datef, f.fk_soc,";
1022
        $sql .= " l.rowid, l.fk_product, l.product_type as line_type, l.description, l.total_ht , l.qty, l.tva_tx, l.vat_src_code,";
1023
        $sql .= " aa.rowid as fk_compte, aa.label as label_account, aa.labelshort as labelshort_account, aa.account_number,";
1024
        $sql .= " p.rowid as product_id, p.fk_product_type as product_type, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tobuy, p.tosell,";
1025
        if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1026
            $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export,";
1027
        } else {
1028
            $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export,";
1029
        }
1030
        $sql .= " co.code as country_code, co.label as country,";
1031
        $sql .= " s.rowid as socid, s.nom as name, s.tva_intra, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur";
1032
        if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1033
            $sql .= ", spe.accountancy_code_customer as code_compta_client";
1034
            $sql .= ", spe.accountancy_code_supplier as code_compta_fournisseur";
1035
        } else {
1036
            $sql .= ", s.code_compta as code_compta_client";
1037
            $sql .= ", s.code_compta_fournisseur";
1038
        }
1039
        $parameters = array();
1040
        $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
1041
        $sql .= $hookmanager->resPrint;
1042
        $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn_det as l";
1043
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product";
1044
        if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1045
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
1046
        }
1047
        $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_account as aa ON aa.rowid = l.fk_code_ventilation";
1048
        $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture_fourn as f ON f.rowid = l.fk_facture_fourn";
1049
        $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc";
1050
        if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1051
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
1052
        }
1053
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as co ON co.rowid = s.fk_pays ";
1054
        $sql .= " WHERE f.rowid = l.fk_facture_fourn and f.fk_statut >= 1 AND l.fk_code_ventilation <> 0 ";
1055
// Add search filter like
1056
        if ($search_societe) {
1057
            $sql .= natural_search('s.nom', $search_societe);
1058
        }
1059
        if ($search_lineid) {
1060
            $sql .= natural_search("l.rowid", $search_lineid, 1);
1061
        }
1062
        if (strlen(trim($search_invoice))) {
1063
            $sql .= natural_search(array("f.ref", "f.ref_supplier"), $search_invoice);
1064
        }
1065
        /*if (strlen(trim($search_ref_supplier))) {
1066
            $sql .= natural_search("f.ref_supplier", $search_ref_supplier);
1067
        }*/
1068
        if (strlen(trim($search_label))) {
1069
            $sql .= natural_search("f.libelle", $search_label);
1070
        }
1071
        if (strlen(trim($search_ref))) {
1072
            $sql .= natural_search("p.ref", $search_ref);
1073
        }
1074
        if (strlen(trim($search_desc))) {
1075
            $sql .= natural_search("l.description", $search_desc);
1076
        }
1077
        if (strlen(trim($search_amount))) {
1078
            $sql .= natural_search("l.total_ht", $search_amount, 1);
1079
        }
1080
        if (strlen(trim($search_account))) {
1081
            $sql .= natural_search("aa.account_number", $search_account);
1082
        }
1083
        if (strlen(trim($search_vat))) {
1084
            $sql .= natural_search("l.tva_tx", price2num($search_vat), 1);
1085
        }
1086
        if ($search_date_start) {
1087
            $sql .= " AND f.datef >= '" . $db->idate($search_date_start) . "'";
1088
        }
1089
        if ($search_date_end) {
1090
            $sql .= " AND f.datef <= '" . $db->idate($search_date_end) . "'";
1091
        }
1092
        if (strlen(trim($search_country))) {
1093
            $arrayofcode = getCountriesInEEC();
1094
            $country_code_in_EEC = $country_code_in_EEC_without_me = '';
1095
            foreach ($arrayofcode as $key => $value) {
1096
                $country_code_in_EEC .= ($country_code_in_EEC ? "," : "") . "'" . $value . "'";
1097
                if ($value != $mysoc->country_code) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mysoc seems to be never defined.
Loading history...
1098
                    $country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "") . "'" . $value . "'";
1099
                }
1100
            }
1101
            if ($search_country == 'special_allnotme') {
1102
                $sql .= " AND co.code <> '" . $db->escape($mysoc->country_code) . "'";
1103
            } elseif ($search_country == 'special_eec') {
1104
                $sql .= " AND co.code IN (" . $db->sanitize($country_code_in_EEC, 1) . ")";
1105
            } elseif ($search_country == 'special_eecnotme') {
1106
                $sql .= " AND co.code IN (" . $db->sanitize($country_code_in_EEC_without_me, 1) . ")";
1107
            } elseif ($search_country == 'special_noteec') {
1108
                $sql .= " AND co.code NOT IN (" . $db->sanitize($country_code_in_EEC, 1) . ")";
1109
            } else {
1110
                $sql .= natural_search("co.code", $search_country);
1111
            }
1112
        }
1113
        if (strlen(trim($search_tvaintra))) {
1114
            $sql .= natural_search("s.tva_intra", $search_tvaintra);
1115
        }
1116
        $sql .= " AND f.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy
1117
1118
// Add where from hooks
1119
        $parameters = array();
1120
        $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
1121
        $sql .= $hookmanager->resPrint;
1122
1123
        $sql .= $db->order($sortfield, $sortorder);
1124
1125
// Count total nb of records
1126
        $nbtotalofrecords = '';
1127
        if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
1128
            $result = $db->query($sql);
1129
            $nbtotalofrecords = $db->num_rows($result);
1130
            if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
1131
                $page = 0;
1132
                $offset = 0;
1133
            }
1134
        }
1135
1136
        $sql .= $db->plimit($limit + 1, $offset);
1137
1138
        dol_syslog("accountancy/supplier/lines.php", LOG_DEBUG);
1139
        $result = $db->query($sql);
1140
        if ($result) {
1141
            $num_lines = $db->num_rows($result);
1142
            $i = 0;
1143
1144
            $param = '';
1145
            if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $contextpage seems to never exist and therefore empty should always be true.
Loading history...
1146
                $param .= '&contextpage=' . urlencode($contextpage);
1147
            }
1148
            if ($limit > 0 && $limit != $conf->liste_limit) {
1149
                $param .= '&limit=' . ((int) $limit);
1150
            }
1151
            if ($search_societe) {
1152
                $param .= "&search_societe=" . urlencode($search_societe);
1153
            }
1154
            if ($search_invoice) {
1155
                $param .= "&search_invoice=" . urlencode($search_invoice);
1156
            }
1157
            if ($search_ref) {
1158
                $param .= "&search_ref=" . urlencode($search_ref);
1159
            }
1160
            /*if ($search_ref_supplier) {
1161
                $param .= '&search_ref_supplier='.urlencode($search_ref_supplier);
1162
            }*/
1163
            if ($search_label) {
1164
                $param .= "&search_label=" . urlencode($search_label);
1165
            }
1166
            if ($search_desc) {
1167
                $param .= "&search_desc=" . urlencode($search_desc);
1168
            }
1169
            if ($search_account) {
1170
                $param .= "&search_account=" . urlencode($search_account);
1171
            }
1172
            if ($search_vat) {
1173
                $param .= "&search_vat=" . urlencode($search_vat);
1174
            }
1175
            if ($search_date_startday) {
1176
                $param .= '&search_date_startday=' . urlencode((string) ($search_date_startday));
1177
            }
1178
            if ($search_date_startmonth) {
1179
                $param .= '&search_date_startmonth=' . urlencode((string) ($search_date_startmonth));
1180
            }
1181
            if ($search_date_startyear) {
1182
                $param .= '&search_date_startyear=' . urlencode((string) ($search_date_startyear));
1183
            }
1184
            if ($search_date_endday) {
1185
                $param .= '&search_date_endday=' . urlencode((string) ($search_date_endday));
1186
            }
1187
            if ($search_date_endmonth) {
1188
                $param .= '&search_date_endmonth=' . urlencode((string) ($search_date_endmonth));
1189
            }
1190
            if ($search_date_endyear) {
1191
                $param .= '&search_date_endyear=' . urlencode((string) ($search_date_endyear));
1192
            }
1193
            if ($search_country) {
1194
                $param .= "&search_country=" . urlencode($search_country);
1195
            }
1196
            if ($search_tvaintra) {
1197
                $param .= "&search_tvaintra=" . urlencode($search_tvaintra);
1198
            }
1199
1200
            print '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">' . "\n";
1201
            print '<input type="hidden" name="action" value="ventil">';
1202
            if ($optioncss != '') {
1203
                print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
1204
            }
1205
            print '<input type="hidden" name="token" value="' . newToken() . '">';
1206
            print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
1207
            print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
1208
            print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
1209
            print '<input type="hidden" name="page" value="' . $page . '">';
1210
1211
            // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
1212
            print_barre_liste($langs->trans("InvoiceLinesDone"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit);
1213
            print '<span class="opacitymedium">' . $langs->trans("DescVentilDoneSupplier") . '</span><br>';
1214
1215
            print '<br><div class="inline-block divButAction paddingbottom">' . $langs->trans("ChangeAccount") . ' ';
1216
            print $formaccounting->select_account($account_parent, 'account_parent', 2, array(), 0, 0, 'maxwidth300 maxwidthonsmartphone valignmiddle');
1217
            print '<input type="submit" class="button small valignmiddle" value="' . $langs->trans("ChangeBinding") . '"/></div>';
1218
1219
            $moreforfilter = '';
1220
1221
            print '<div class="div-table-responsive">';
1222
            print '<table class="tagtable liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
1223
1224
            // We add search filter
1225
            print '<tr class="liste_titre_filter">';
1226
            print '<td class="liste_titre"><input type="text" class="flat maxwidth25" name="search_lineid" value="' . dol_escape_htmltag($search_lineid) . '"></td>';
1227
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="' . dol_escape_htmltag($search_invoice) . '"></td>';
1228
            //print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref_supplier" value="'.dol_escape_htmltag($search_ref_supplier).'"></td>';
1229
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="' . dol_escape_htmltag($search_label) . '"></td>';
1230
            print '<td class="liste_titre center">';
1231
            print '<div class="nowrapfordate">';
1232
            print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
1233
            print '</div>';
1234
            print '<div class="nowrapfordate">';
1235
            print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
1236
            print '</div>';
1237
            print '</td>';
1238
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '"></td>';
1239
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_desc" value="' . dol_escape_htmltag($search_desc) . '"></td>';
1240
            print '<td class="liste_titre right"><input type="text" class="right flat maxwidth50" name="search_amount" value="' . dol_escape_htmltag($search_amount) . '"></td>';
1241
            print '<td class="liste_titre right"><input type="text" class="right flat maxwidth50" name="search_vat" placeholder="%" size="1" value="' . dol_escape_htmltag($search_vat) . '"></td>';
1242
            print '<td class="liste_titre"><input type="text" class="flat maxwidth75imp" name="search_societe" value="' . dol_escape_htmltag($search_societe) . '"></td>';
1243
            print '<td class="liste_titre">';
1244
            print $form->select_country($search_country, 'search_country', '', 0, 'maxwidth100', 'code2', 1, 0, 1);
1245
            //  print '<input type="text" class="flat maxwidth50" name="search_country" value="' . dol_escape_htmltag($search_country) . '">';
1246
            print '</td>';
1247
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_tvaintra" value="' . dol_escape_htmltag($search_tvaintra) . '"></td>';
1248
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_account" value="' . dol_escape_htmltag($search_account) . '"></td>';
1249
            print '<td class="liste_titre center">';
1250
            $searchpicto = $form->showFilterButtons();
1251
            print $searchpicto;
1252
            print "</td></tr>\n";
1253
1254
            print '<tr class="liste_titre">';
1255
            print_liste_field_titre("LineId", $_SERVER['PHP_SELF'], "l.rowid", "", $param, '', $sortfield, $sortorder);
1256
            print_liste_field_titre("Invoice", $_SERVER['PHP_SELF'], "f.ref", "", $param, '', $sortfield, $sortorder);
1257
            //print_liste_field_titre("RefSupplier", $_SERVER['PHP_SELF'], "f.ref_supplier", "", $param, '', $sortfield, $sortorder);
1258
            print_liste_field_titre("InvoiceLabel", $_SERVER['PHP_SELF'], "f.libelle", "", $param, '', $sortfield, $sortorder);
1259
            print_liste_field_titre("Date", $_SERVER['PHP_SELF'], "f.datef, f.ref, l.rowid", "", $param, '', $sortfield, $sortorder, 'center ');
1260
            print_liste_field_titre("ProductRef", $_SERVER['PHP_SELF'], "p.ref", "", $param, '', $sortfield, $sortorder);
1261
            //print_liste_field_titre("ProductLabel", $_SERVER['PHP_SELF'], "p.label", "", $param, '', $sortfield, $sortorder);
1262
            print_liste_field_titre("ProductDescription", $_SERVER['PHP_SELF'], "l.description", "", $param, '', $sortfield, $sortorder);
1263
            print_liste_field_titre("Amount", $_SERVER['PHP_SELF'], "l.total_ht", "", $param, '', $sortfield, $sortorder, 'right ');
1264
            print_liste_field_titre("VATRate", $_SERVER['PHP_SELF'], "l.tva_tx", "", $param, '', $sortfield, $sortorder, 'right ');
1265
            print_liste_field_titre("ThirdParty", $_SERVER['PHP_SELF'], "s.nom", "", $param, '', $sortfield, $sortorder);
1266
            print_liste_field_titre("Country", $_SERVER['PHP_SELF'], "co.label", "", $param, '', $sortfield, $sortorder);
1267
            print_liste_field_titre("VATIntraShort", $_SERVER['PHP_SELF'], "s.tva_intra", "", $param, '', $sortfield, $sortorder);
1268
            print_liste_field_titre("AccountAccounting", $_SERVER['PHP_SELF'], "aa.account_number", "", $param, '', $sortfield, $sortorder);
1269
            $checkpicto = $form->showCheckAddButtons();
1270
            print_liste_field_titre($checkpicto, '', '', '', '', '', '', '', 'center ');
1271
            print "</tr>\n";
1272
1273
            $thirdpartystatic = new Societe($db);
1274
            $facturefournisseur_static = new FactureFournisseur($db);
1275
            $productstatic = new ProductFournisseur($db);
0 ignored issues
show
Bug introduced by
The type DoliModules\Accounting\C...ller\ProductFournisseur was not found. Did you mean ProductFournisseur? If so, make sure to prefix the type with \.
Loading history...
1276
            $accountingaccountstatic = new AccountingAccount($db);
1277
1278
            $i = 0;
1279
            while ($i < min($num_lines, $limit)) {
1280
                $objp = $db->fetch_object($result);
1281
1282
                $facturefournisseur_static->ref = $objp->ref;
1283
                $facturefournisseur_static->id = $objp->facid;
1284
                $facturefournisseur_static->type = $objp->ftype;
1285
                $facturefournisseur_static->ref_supplier = $objp->ref_supplier;
1286
                $facturefournisseur_static->label = $objp->invoice_label;
1287
1288
                $thirdpartystatic->id = $objp->socid;
1289
                $thirdpartystatic->name = $objp->name;
1290
                $thirdpartystatic->client = $objp->client;
1291
                $thirdpartystatic->fournisseur = $objp->fournisseur;
1292
                $thirdpartystatic->code_client = $objp->code_client;
1293
                $thirdpartystatic->code_compta_client = $objp->code_compta_client;
1294
                $thirdpartystatic->code_fournisseur = $objp->code_fournisseur;
1295
                $thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur;
1296
                $thirdpartystatic->email = $objp->email;
1297
                $thirdpartystatic->country_code = $objp->country_code;
1298
1299
                $productstatic->ref = $objp->product_ref;
1300
                $productstatic->id = $objp->product_id;
1301
                $productstatic->label = $objp->product_label;
1302
                $productstatic->type = $objp->line_type;
1303
                $productstatic->status = $objp->tosell;
1304
                $productstatic->status_buy = $objp->tobuy;
1305
                $productstatic->accountancy_code_buy = $objp->accountancy_code_buy;
1306
                $productstatic->accountancy_code_buy_intra = $objp->accountancy_code_buy_intra;
1307
                $productstatic->accountancy_code_buy_export = $objp->accountancy_code_buy_export;
1308
1309
                $accountingaccountstatic->rowid = $objp->fk_compte;
1310
                $accountingaccountstatic->label = $objp->label_account;
1311
                $accountingaccountstatic->labelshort = $objp->labelshort_account;
1312
                $accountingaccountstatic->account_number = $objp->account_number;
1313
1314
                print '<tr class="oddeven">';
1315
1316
                // Line id
1317
                print '<td>' . $objp->rowid . '</td>';
1318
1319
                // Ref Invoice
1320
                print '<td class="nowraponall">' . $facturefournisseur_static->getNomUrl(1);
1321
                if ($objp->ref_supplier) {
1322
                    print '<br><span class="opacitymedium small">' . dol_escape_htmltag($objp->ref_supplier) . '</span>';
1323
                }
1324
                print '</td>';
1325
1326
                // Ref supplier invoice
1327
                /*
1328
                print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($objp->ref_supplier).'">';
1329
                print $objp->ref_supplier;
1330
                print '</td>';
1331
                */
1332
1333
                // Supplier invoice label
1334
                print '<td class="tdoverflowonsmartphone small" title="' . dol_escape_htmltag($objp->invoice_label) . '">';
1335
                print $objp->invoice_label;
1336
                print '</td>';
1337
1338
                // Date invoice
1339
                print '<td class="center">' . dol_print_date($db->jdate($objp->datef), 'day') . '</td>';
1340
1341
                // Ref Product
1342
                print '<td class="tdoverflowmax100">';
1343
                if ($productstatic->id > 0) {
1344
                    print $productstatic->getNomUrl(1);
1345
                }
1346
                if ($productstatic->id > 0 && $objp->product_label) {
1347
                    print '<br>';
1348
                }
1349
                if ($objp->product_label) {
1350
                    print '<span class="opacitymedium">' . $objp->product_label . '</span>';
1351
                }
1352
                print '</td>';
1353
1354
                print '<td class="tdoverflowonsmartphone small">';
1355
                $text = dolGetFirstLineOfText(dol_string_nohtmltag($objp->description, 1));
1356
                $trunclength = getDolGlobalInt('ACCOUNTING_LENGTH_DESCRIPTION', 32);
1357
                print $form->textwithtooltip(dol_trunc($text, $trunclength), $objp->description);
1358
                print '</td>';
1359
1360
                print '<td class="right nowraponall amount">' . price($objp->total_ht) . '</td>';
1361
1362
                print '<td class="right">' . vatrate($objp->tva_tx . ($objp->vat_src_code ? ' (' . $objp->vat_src_code . ')' : '')) . '</td>';
1363
1364
                // Thirdparty
1365
                print '<td class="tdoverflowmax100">' . $thirdpartystatic->getNomUrl(1, 'supplier') . '</td>';
1366
1367
                // Country
1368
                print '<td>';
1369
                if ($objp->country_code) {
1370
                    print $langs->trans("Country" . $objp->country_code) . ' (' . $objp->country_code . ')';
1371
                }
1372
                print '</td>';
1373
1374
                print '<td class="tdoverflowmax80" title="' . dol_escape_htmltag($objp->tva_intra) . '">' . dol_escape_htmltag($objp->tva_intra) . '</td>';
1375
1376
                print '<td>';
1377
                print $accountingaccountstatic->getNomUrl(0, 1, 1, '', 1);
1378
                print ' <a class="editfielda" href="./card.php?id=' . $objp->rowid . '&backtopage=' . urlencode($_SERVER['PHP_SELF'] . ($param ? '?' . $param : '')) . '">';
1379
                print img_edit();
1380
                print '</a></td>';
1381
                print '<td class="center"><input type="checkbox" class="checkforaction" name="changeaccount[]" value="' . $objp->rowid . '"/></td>';
1382
1383
                print '</tr>';
1384
                $i++;
1385
            }
1386
            if ($num_lines == 0) {
1387
                print '<tr><td colspan="13"><span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span></td></tr>';
1388
            }
1389
1390
            print '</table>';
1391
            print "</div>";
1392
1393
            if ($nbtotalofrecords > $limit) {
1394
                print_barre_liste('', $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num_lines, $nbtotalofrecords, '', 0, '', '', $limit, 1);
1395
            }
1396
1397
            print '</form>';
1398
        } else {
1399
            print $db->lasterror();
1400
        }
1401
1402
// End of page
1403
        llxFooter();
1404
        $db->close();
1405
    }
1406
1407
    /**
1408
     * \file        htdocs/accountancy/supplier/list.php
1409
     * \ingroup     Accountancy (Double entries)
1410
     * \brief       Ventilation page from suppliers invoices
1411
     */
1412
    public function list()
1413
    {
1414
        global $conf;
1415
        global $db;
1416
        global $user;
1417
        global $hookmanager;
1418
        global $user;
1419
        global $menumanager;
1420
        global $langs;
1421
1422
// Load translation files required by the page
1423
        $langs->loadLangs(array("bills", "companies", "compta", "accountancy", "other", "productbatch", "products"));
1424
1425
        $action = GETPOST('action', 'aZ09');
1426
        $massaction = GETPOST('massaction', 'alpha');
1427
        $confirm = GETPOST('confirm', 'alpha');
1428
        $toselect = GETPOST('toselect', 'array');
1429
        $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'accountancysupplierlist'; // To manage different context of search
1430
        $optioncss = GETPOST('optioncss', 'alpha');
1431
1432
        $default_account = GETPOSTINT('default_account');
1433
1434
// Select Box
1435
        $mesCasesCochees = GETPOST('toselect', 'array');
1436
1437
// Search Getpost
1438
        $search_societe = GETPOST('search_societe', 'alpha');
1439
        $search_lineid = GETPOSTINT('search_lineid');
1440
        $search_ref = GETPOST('search_ref', 'alpha');
1441
        $search_ref_supplier = GETPOST('search_ref_supplier', 'alpha');
1442
        $search_invoice = GETPOST('search_invoice', 'alpha');
1443
        $search_label = GETPOST('search_label', 'alpha');
1444
        $search_desc = GETPOST('search_desc', 'alpha');
1445
        $search_amount = GETPOST('search_amount', 'alpha');
1446
        $search_account = GETPOST('search_account', 'alpha');
1447
        $search_vat = GETPOST('search_vat', 'alpha');
1448
        $search_date_startday = GETPOSTINT('search_date_startday');
1449
        $search_date_startmonth = GETPOSTINT('search_date_startmonth');
1450
        $search_date_startyear = GETPOSTINT('search_date_startyear');
1451
        $search_date_endday = GETPOSTINT('search_date_endday');
1452
        $search_date_endmonth = GETPOSTINT('search_date_endmonth');
1453
        $search_date_endyear = GETPOSTINT('search_date_endyear');
1454
        $search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_startday, $search_date_startyear);   // Use tzserver
1455
        $search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear);
1456
        $search_country = GETPOST('search_country', 'alpha');
1457
        $search_tvaintra = GETPOST('search_tvaintra', 'alpha');
1458
1459
// Load variable for pagination
1460
        $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit);
1461
        $sortfield = GETPOST('sortfield', 'aZ09comma');
1462
        $sortorder = GETPOST('sortorder', 'aZ09comma');
1463
        $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
1464
        if (empty($page) || $page < 0) {
1465
            $page = 0;
1466
        }
1467
        $offset = $limit * $page;
1468
        $pageprev = $page - 1;
1469
        $pagenext = $page + 1;
1470
        if (!$sortfield) {
1471
            $sortfield = "f.datef, f.ref, l.rowid";
1472
        }
1473
        if (!$sortorder) {
1474
            if (getDolGlobalInt('ACCOUNTING_LIST_SORT_VENTILATION_TODO') > 0) {
1475
                $sortorder = "DESC";
1476
            } else {
1477
                $sortorder = "ASC";
1478
            }
1479
        }
1480
1481
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
1482
        $hookmanager->initHooks(array('accountancysupplierlist'));
1483
1484
        $formaccounting = new FormAccounting($db);
1485
        $accountingAccount = new AccountingAccount($db);
1486
1487
        $chartaccountcode = dol_getIdFromCode($db, getDolGlobalInt('CHARTOFACCOUNTS'), 'accounting_system', 'rowid', 'pcg_version');
1488
1489
// Security check
1490
        if (!isModEnabled('accounting')) {
1491
            accessforbidden();
1492
        }
1493
        if ($user->socid > 0) {
1494
            accessforbidden();
1495
        }
1496
        if (!$user->hasRight('accounting', 'mouvements', 'lire')) {
1497
            accessforbidden();
1498
        }
1499
1500
// Define begin binding date
1501
        if (empty($search_date_start) && getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) {
1502
            $search_date_start = $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'));
1503
        }
1504
1505
1506
        /*
1507
         * Actions
1508
         */
1509
1510
        if (GETPOST('cancel', 'alpha')) {
1511
            $action = 'list';
1512
            $massaction = '';
1513
        }
1514
        if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
1515
            $massaction = '';
1516
        }
1517
1518
        $parameters = array();
1519
        $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $object does not exist. Did you maybe mean $objectclass?
Loading history...
1520
        if ($reshook < 0) {
1521
            setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1522
        }
1523
1524
        if (empty($reshook)) {
1525
            // Purge search criteria
1526
            if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All test are required to be compatible with all browsers
1527
                $search_societe = '';
1528
                $search_lineid = '';
1529
                $search_ref = '';
1530
                $search_ref_supplier = '';
1531
                $search_invoice = '';
1532
                $search_label = '';
1533
                $search_desc = '';
1534
                $search_amount = '';
1535
                $search_account = '';
1536
                $search_vat = '';
1537
                $search_date_startday = '';
1538
                $search_date_startmonth = '';
1539
                $search_date_startyear = '';
1540
                $search_date_endday = '';
1541
                $search_date_endmonth = '';
1542
                $search_date_endyear = '';
1543
                $search_date_start = '';
1544
                $search_date_end = '';
1545
                $search_country = '';
1546
                $search_tvaintra = '';
1547
            }
1548
1549
            // Mass actions
1550
            $objectclass = 'AccountingAccount';
1551
            $permissiontoread = $user->hasRight('accounting', 'read');
1552
            $permissiontodelete = $user->hasRight('accounting', 'delete');
1553
            $uploaddir = $conf->accounting->dir_output;
1554
            include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
1555
        }
1556
1557
1558
        if ($massaction == 'ventil' && $user->hasRight('accounting', 'bind', 'write')) {
1559
            $msg = '';
1560
1561
            if (!empty($mesCasesCochees)) {
1562
                $msg = '<div>' . $langs->trans("SelectedLines") . ': ' . count($mesCasesCochees) . '</div>';
1563
                $msg .= '<div class="detail">';
1564
                $cpt = 0;
1565
                $ok = 0;
1566
                $ko = 0;
1567
1568
                foreach ($mesCasesCochees as $maLigneCochee) {
1569
                    $maLigneCourante = explode("_", $maLigneCochee);
1570
                    $monId = $maLigneCourante[0];
1571
                    $monCompte = GETPOST('codeventil' . $monId);
1572
1573
                    if ($monCompte <= 0) {
1574
                        $msg .= '<div><span class="error">' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NoAccountSelected") . '</span></div>';
1575
                        $ko++;
1576
                    } else {
1577
                        $sql = " UPDATE " . MAIN_DB_PREFIX . "facture_fourn_det";
1578
                        $sql .= " SET fk_code_ventilation = " . ((int) $monCompte);
1579
                        $sql .= " WHERE rowid = " . ((int) $monId);
1580
1581
                        $accountventilated = new AccountingAccount($db);
1582
                        $accountventilated->fetch($monCompte, '', 1);
1583
1584
                        dol_syslog('accountancy/supplier/list.php', LOG_DEBUG);
1585
                        if ($db->query($sql)) {
1586
                            $msg .= '<div><span class="green">' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("VentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '</span></div>';
1587
                            $ok++;
1588
                        } else {
1589
                            $msg .= '<div><span class="error">' . $langs->trans("ErrorDB") . ' : ' . $langs->trans("Lineofinvoice") . ' ' . $monId . ' - ' . $langs->trans("NotVentilatedinAccount") . ' : ' . length_accountg($accountventilated->account_number) . '<br> <pre>' . $sql . '</pre></span></div>';
1590
                            $ko++;
1591
                        }
1592
                    }
1593
1594
                    $cpt++;
1595
                }
1596
                $msg .= '</div>';
1597
                $msg .= '<div>' . $langs->trans("EndProcessing") . '</div>';
1598
            }
1599
        }
1600
1601
        if (GETPOST('sortfield') == 'f.datef, f.ref, l.rowid') {
1602
            $value = (GETPOST('sortorder') == 'asc,asc,asc' ? 0 : 1);
1603
            require_once DOL_DOCUMENT_ROOT . '/core/lib/admin.lib.php';
1604
            $res = dolibarr_set_const($db, "ACCOUNTING_LIST_SORT_VENTILATION_TODO", $value, 'yesno', 0, '', $conf->entity);
1605
        }
1606
1607
1608
        /*
1609
         * View
1610
         */
1611
1612
        $form = new Form($db);
1613
        $formother = new FormOther($db);
1614
1615
        $help_url = 'EN:Module_Double_Entry_Accounting|FR:Module_Comptabilit&eacute;_en_Partie_Double#Liaisons_comptables';
1616
1617
        llxHeader('', $langs->trans("SuppliersVentilation"), $help_url);
1618
1619
        if (empty($chartaccountcode)) {
1620
            print $langs->trans("ErrorChartOfAccountSystemNotSelected");
1621
            // End of page
1622
            llxFooter();
1623
            $db->close();
1624
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1625
        }
1626
1627
// Supplier Invoice Lines
1628
        $sql = "SELECT f.rowid as facid, f.ref, f.ref_supplier, f.libelle as invoice_label, f.datef, f.type as ftype, f.fk_facture_source,";
1629
        $sql .= " l.rowid, l.fk_product, l.description, l.total_ht, l.fk_code_ventilation, l.product_type as type_l, l.tva_tx as tva_tx_line, l.vat_src_code,";
1630
        $sql .= " p.rowid as product_id, p.ref as product_ref, p.label as product_label, p.fk_product_type as type, p.tva_tx as tva_tx_prod,";
1631
        if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1632
            $sql .= " ppe.accountancy_code_sell as code_sell, ppe.accountancy_code_sell_intra as code_sell_intra, ppe.accountancy_code_sell_export as code_sell_export,";
1633
            $sql .= " ppe.accountancy_code_buy as code_buy, ppe.accountancy_code_buy_intra as code_buy_intra, ppe.accountancy_code_buy_export as code_buy_export,";
1634
        } else {
1635
            $sql .= " p.accountancy_code_sell as code_sell, p.accountancy_code_sell_intra as code_sell_intra, p.accountancy_code_sell_export as code_sell_export,";
1636
            $sql .= " p.accountancy_code_buy as code_buy, p.accountancy_code_buy_intra as code_buy_intra, p.accountancy_code_buy_export as code_buy_export,";
1637
        }
1638
        $sql .= " p.tosell as status, p.tobuy as status_buy,";
1639
        $sql .= " aa.rowid as aarowid, aa2.rowid as aarowid_intra, aa3.rowid as aarowid_export, aa4.rowid as aarowid_thirdparty,";
1640
        $sql .= " co.code as country_code, co.label as country_label,";
1641
        $sql .= " s.rowid as socid, s.nom as name, s.tva_intra, s.email, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur,";
1642
        if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1643
            $sql .= " spe.accountancy_code_customer as code_compta_client,";
1644
            $sql .= " spe.accountancy_code_supplier as code_compta_fournisseur,";
1645
            $sql .= " spe.accountancy_code_buy as company_code_buy";
1646
        } else {
1647
            $sql .= " s.code_compta as code_compta_client,";
1648
            $sql .= " s.code_compta_fournisseur,";
1649
            $sql .= " s.accountancy_code_buy as company_code_buy";
1650
        }
1651
        $parameters = array();
1652
        $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook
1653
        $sql .= $hookmanager->resPrint;
1654
        $sql .= " FROM " . MAIN_DB_PREFIX . "facture_fourn as f";
1655
        $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "societe as s ON s.rowid = f.fk_soc";
1656
        if (getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED')) {
1657
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_perentity as spe ON spe.fk_soc = s.rowid AND spe.entity = " . ((int) $conf->entity);
1658
        }
1659
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as co ON co.rowid = s.fk_pays ";
1660
        $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "facture_fourn_det as l ON f.rowid = l.fk_facture_fourn";
1661
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product as p ON p.rowid = l.fk_product";
1662
        if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
1663
            $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
1664
        }
1665
        $alias_societe_perentity = !getDolGlobalString('MAIN_COMPANY_PERENTITY_SHARED') ? "s" : "spe";
1666
        $alias_product_perentity = !getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED') ? "p" : "ppe";
1667
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa  ON " . $alias_product_perentity . ".accountancy_code_buy = aa.account_number         AND aa.active = 1  AND aa.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa.entity = " . $conf->entity;
1668
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa2 ON " . $alias_product_perentity . ".accountancy_code_buy_intra = aa2.account_number  AND aa2.active = 1 AND aa2.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa2.entity = " . $conf->entity;
1669
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa3 ON " . $alias_product_perentity . ".accountancy_code_buy_export = aa3.account_number AND aa3.active = 1 AND aa3.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa3.entity = " . $conf->entity;
1670
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_account as aa4 ON " . $alias_societe_perentity . ".accountancy_code_buy = aa4.account_number        AND aa4.active = 1 AND aa4.fk_pcg_version = '" . $db->escape($chartaccountcode) . "' AND aa4.entity = " . $conf->entity;
1671
        $sql .= " WHERE f.fk_statut > 0 AND l.fk_code_ventilation <= 0";
1672
        $sql .= " AND l.product_type <= 2";
1673
// Add search filter like
1674
        if ($search_societe) {
1675
            $sql .= natural_search('s.nom', $search_societe);
1676
        }
1677
        if ($search_lineid) {
1678
            $sql .= natural_search("l.rowid", $search_lineid, 1);
1679
        }
1680
        if (strlen(trim($search_invoice))) {
1681
            $sql .= natural_search(array("f.ref", "f.ref_supplier"), $search_invoice);
1682
        }
1683
        if (strlen(trim($search_ref))) {
1684
            $sql .= natural_search("p.ref", $search_ref);
1685
        }
1686
        /*if (strlen(trim($search_ref_supplier))) {
1687
            $sql .= natural_search("f.ref_supplier", $search_ref_supplier);
1688
        }*/
1689
        if (strlen(trim($search_label))) {
1690
            $sql .= natural_search(array("p.label", "f.libelle"), $search_label);
1691
        }
1692
        if (strlen(trim($search_desc))) {
1693
            $sql .= natural_search("l.description", $search_desc);
1694
        }
1695
        if (strlen(trim($search_amount))) {
1696
            $sql .= natural_search("l.total_ht", $search_amount, 1);
1697
        }
1698
        if (strlen(trim($search_account))) {
1699
            $sql .= natural_search("aa.account_number", $search_account);
1700
        }
1701
        if (strlen(trim($search_vat))) {
1702
            $sql .= natural_search("l.tva_tx", price2num($search_vat), 1);
1703
        }
1704
        if ($search_date_start) {
1705
            $sql .= " AND f.datef >= '" . $db->idate($search_date_start) . "'";
1706
        }
1707
        if ($search_date_end) {
1708
            $sql .= " AND f.datef <= '" . $db->idate($search_date_end) . "'";
1709
        }
1710
        if (strlen(trim($search_country))) {
1711
            $arrayofcode = getCountriesInEEC();
1712
            $country_code_in_EEC = $country_code_in_EEC_without_me = '';
1713
            foreach ($arrayofcode as $key => $value) {
1714
                $country_code_in_EEC .= ($country_code_in_EEC ? "," : "") . "'" . $value . "'";
1715
                if ($value != $mysoc->country_code) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $mysoc seems to be never defined.
Loading history...
1716
                    $country_code_in_EEC_without_me .= ($country_code_in_EEC_without_me ? "," : "") . "'" . $value . "'";
1717
                }
1718
            }
1719
            if ($search_country == 'special_allnotme') {
1720
                $sql .= " AND co.code <> '" . $db->escape($mysoc->country_code) . "'";
1721
            } elseif ($search_country == 'special_eec') {
1722
                $sql .= " AND co.code IN (" . $db->sanitize($country_code_in_EEC, 1) . ")";
1723
            } elseif ($search_country == 'special_eecnotme') {
1724
                $sql .= " AND co.code IN (" . $db->sanitize($country_code_in_EEC_without_me, 1) . ")";
1725
            } elseif ($search_country == 'special_noteec') {
1726
                $sql .= " AND co.code NOT IN (" . $db->sanitize($country_code_in_EEC, 1) . ")";
1727
            } else {
1728
                $sql .= natural_search("co.code", $search_country);
1729
            }
1730
        }
1731
        if (strlen(trim($search_tvaintra))) {
1732
            $sql .= natural_search("s.tva_intra", $search_tvaintra);
1733
        }
1734
        if (getDolGlobalString('FACTURE_SUPPLIER_DEPOSITS_ARE_JUST_PAYMENTS')) {
1735
            $sql .= " AND f.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . "," . FactureFournisseur::TYPE_SITUATION . ")";
1736
        } else {
1737
            $sql .= " AND f.type IN (" . FactureFournisseur::TYPE_STANDARD . "," . FactureFournisseur::TYPE_REPLACEMENT . "," . FactureFournisseur::TYPE_CREDIT_NOTE . "," . FactureFournisseur::TYPE_DEPOSIT . "," . FactureFournisseur::TYPE_SITUATION . ")";
1738
        }
1739
        $sql .= " AND f.entity IN (" . getEntity('facture_fourn', 0) . ")"; // We don't share object for accountancy
1740
1741
// Add where from hooks
1742
        $parameters = array();
1743
        $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
1744
        $sql .= $hookmanager->resPrint;
1745
1746
        $sql .= $db->order($sortfield, $sortorder);
1747
1748
// Count total nb of records
1749
        $nbtotalofrecords = '';
1750
        if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) {
1751
            $result = $db->query($sql);
1752
            $nbtotalofrecords = $db->num_rows($result);
1753
            if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0
1754
                $page = 0;
1755
                $offset = 0;
1756
            }
1757
        }
1758
1759
        $sql .= $db->plimit($limit + 1, $offset);
1760
1761
        dol_syslog('accountancy/supplier/list.php', LOG_DEBUG);
1762
// MAX_JOIN_SIZE can be very low (ex: 300000) on some limited configurations (ex: https://www.online.net/fr/hosting/online-perso)
1763
// This big SELECT command may exceed the MAX_JOIN_SIZE limit => Therefore we use SQL_BIG_SELECTS=1 to disable the MAX_JOIN_SIZE security
1764
        if ($db->type == 'mysqli') {
1765
            $db->query("SET SQL_BIG_SELECTS=1");
1766
        }
1767
1768
        $result = $db->query($sql);
1769
        if ($result) {
1770
            $num_lines = $db->num_rows($result);
1771
            $i = 0;
1772
1773
            $arrayofselected = is_array($toselect) ? $toselect : array();
1774
1775
            $param = '';
1776
            if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) {
1777
                $param .= '&contextpage=' . urlencode($contextpage);
1778
            }
1779
            if ($limit > 0 && $limit != $conf->liste_limit) {
1780
                $param .= '&limit=' . ((int) $limit);
1781
            }
1782
            if ($search_societe) {
1783
                $param .= '&search_societe=' . urlencode($search_societe);
1784
            }
1785
            if ($search_lineid) {
1786
                $param .= '&search_lineid=' . urlencode((string) ($search_lineid));
1787
            }
1788
            if ($search_date_startday) {
1789
                $param .= '&search_date_startday=' . urlencode((string) ($search_date_startday));
1790
            }
1791
            if ($search_date_startmonth) {
1792
                $param .= '&search_date_startmonth=' . urlencode((string) ($search_date_startmonth));
1793
            }
1794
            if ($search_date_startyear) {
1795
                $param .= '&search_date_startyear=' . urlencode((string) ($search_date_startyear));
1796
            }
1797
            if ($search_date_endday) {
1798
                $param .= '&search_date_endday=' . urlencode((string) ($search_date_endday));
1799
            }
1800
            if ($search_date_endmonth) {
1801
                $param .= '&search_date_endmonth=' . urlencode((string) ($search_date_endmonth));
1802
            }
1803
            if ($search_date_endyear) {
1804
                $param .= '&search_date_endyear=' . urlencode((string) ($search_date_endyear));
1805
            }
1806
            if ($search_invoice) {
1807
                $param .= '&search_invoice=' . urlencode($search_invoice);
1808
            }
1809
            if ($search_ref) {
1810
                $param .= '&search_ref=' . urlencode($search_ref);
1811
            }
1812
            if ($search_ref_supplier) {
1813
                $param .= '&search_ref_supplier=' . urlencode($search_ref_supplier);
1814
            }
1815
            if ($search_label) {
1816
                $param .= '&search_label=' . urlencode($search_label);
1817
            }
1818
            if ($search_desc) {
1819
                $param .= '&search_desc=' . urlencode($search_desc);
1820
            }
1821
            if ($search_amount) {
1822
                $param .= '&search_amount=' . urlencode($search_amount);
1823
            }
1824
            if ($search_vat) {
1825
                $param .= '&search_vat=' . urlencode($search_vat);
1826
            }
1827
            if ($search_country) {
1828
                $param .= "&search_country=" . urlencode($search_country);
1829
            }
1830
            if ($search_tvaintra) {
1831
                $param .= "&search_tvaintra=" . urlencode($search_tvaintra);
1832
            }
1833
1834
            $arrayofmassactions = array(
1835
                'ventil' => img_picto('', 'check', 'class="pictofixedwidth"') . $langs->trans("Ventilate")
1836
            ,'set_default_account' => img_picto('', 'check', 'class="pictofixedwidth"') . $langs->trans("ConfirmPreselectAccount")
1837
                //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
1838
                //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
1839
            );
1840
            //if ($user->hasRight('mymodule', 'supprimer')) $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
1841
            //if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array();
1842
            if ($massaction !== 'set_default_account') {
1843
                $massactionbutton = $form->selectMassAction('ventil', $arrayofmassactions, 1);
1844
            }
1845
1846
            print '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">' . "\n";
1847
            print '<input type="hidden" name="action" value="ventil">';
1848
            if ($optioncss != '') {
1849
                print '<input type="hidden" name="optioncss" value="' . $optioncss . '">';
1850
            }
1851
            print '<input type="hidden" name="token" value="' . newToken() . '">';
1852
            print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
1853
            print '<input type="hidden" name="sortfield" value="' . $sortfield . '">';
1854
            print '<input type="hidden" name="sortorder" value="' . $sortorder . '">';
1855
            print '<input type="hidden" name="page" value="' . $page . '">';
1856
1857
            // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
1858
            print_barre_liste($langs->trans("InvoiceLines"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, $massactionbutton, $num_lines, $nbtotalofrecords, 'title_accountancy', 0, '', '', $limit);
1859
1860
            if ($massaction == 'set_default_account') {
1861
                $formquestion = array();
1862
                $formquestion[] = array('type' => 'other',
1863
                    'name' => 'set_default_account',
1864
                    'label' => $langs->trans("AccountancyCode"),
1865
                    'value' => $formaccounting->select_account('', 'default_account', 1, array(), 0, 0, 'maxwidth200 maxwidthonsmartphone', 'cachewithshowemptyone'));
1866
                print $form->formconfirm($_SERVER['PHP_SELF'], $langs->trans("ConfirmPreselectAccount"), $langs->trans("ConfirmPreselectAccountQuestion", count($toselect)), "confirm_set_default_account", $formquestion, 1, 0, 200, 500, 1);
1867
            }
1868
1869
            print '<span class="opacitymedium">' . $langs->trans("DescVentilTodoCustomer") . '</span></br><br>';
1870
1871
            if (!empty($msg)) {
1872
                print $msg . '<br>';
1873
            }
1874
1875
            $moreforfilter = '';
1876
1877
            print '<div class="div-table-responsive">';
1878
            print '<table class="tagtable liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
1879
1880
            // We add search filter
1881
            print '<tr class="liste_titre_filter">';
1882
            print '<td class="liste_titre"><input type="text" class="flat maxwidth25" name="search_lineid" value="' . dol_escape_htmltag($search_lineid) . '"></td>';
1883
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_invoice" value="' . dol_escape_htmltag($search_invoice) . '"></td>';
1884
            //print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref_supplier" value="'.dol_escape_htmltag($search_ref_supplier).'"></td>';
1885
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_label" value="' . dol_escape_htmltag($search_label) . '"></td>';
1886
            print '<td class="liste_titre center">';
1887
            print '<div class="nowrapfordate">';
1888
            print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
1889
            print '</div>';
1890
            print '<div class="nowrapfordate">';
1891
            print $form->selectDate($search_date_end ? $search_date_end : -1, 'search_date_end', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
1892
            print '</div>';
1893
            print '</td>';
1894
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_ref" value="' . dol_escape_htmltag($search_ref) . '"></td>';
1895
            print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_desc" value="' . dol_escape_htmltag($search_desc) . '"></td>';
1896
            print '<td class="liste_titre right"><input type="text" class="flat maxwidth50 right" name="search_amount" value="' . dol_escape_htmltag($search_amount) . '"></td>';
1897
            print '<td class="liste_titre right"><input type="text" class="flat maxwidth50 right" name="search_vat" placeholder="%" size="1" value="' . dol_escape_htmltag($search_vat) . '"></td>';
1898
            print '<td class="liste_titre"><input type="text" class="flat maxwidth75imp" name="search_societe" value="' . dol_escape_htmltag($search_societe) . '"></td>';
1899
            print '<td class="liste_titre">';
1900
            print $form->select_country($search_country, 'search_country', '', 0, 'maxwidth100', 'code2', 1, 0, 1);
1901
            //print '<input type="text" class="flat maxwidth50" name="search_country" value="' . dol_escape_htmltag($search_country) . '">';
1902
            print '</td>';
1903
            print '<td class="liste_titre"><input type="text" class="flat maxwidth50" name="search_tvaintra" value="' . dol_escape_htmltag($search_tvaintra) . '"></td>';
1904
            print '<td class="liste_titre"></td>';
1905
            print '<td class="liste_titre"></td>';
1906
            print '<td class="center liste_titre">';
1907
            $searchpicto = $form->showFilterButtons();
1908
            print $searchpicto;
1909
            print '</td>';
1910
            print "</tr>\n";
1911
1912
            print '<tr class="liste_titre">';
1913
            print_liste_field_titre("LineId", $_SERVER['PHP_SELF'], "l.rowid", "", $param, '', $sortfield, $sortorder);
1914
            print_liste_field_titre("Invoice", $_SERVER['PHP_SELF'], "f.ref", "", $param, '', $sortfield, $sortorder);
1915
            //print_liste_field_titre("RefSupplier", $_SERVER['PHP_SELF'], "f.ref_supplier", "", $param, '', $sortfield, $sortorder);
1916
            print_liste_field_titre("InvoiceLabel", $_SERVER['PHP_SELF'], "f.libelle", "", $param, '', $sortfield, $sortorder);
1917
            print_liste_field_titre("Date", $_SERVER['PHP_SELF'], "f.datef, f.ref, l.rowid", "", $param, '', $sortfield, $sortorder, 'center ');
1918
            print_liste_field_titre("ProductRef", $_SERVER['PHP_SELF'], "p.ref", "", $param, '', $sortfield, $sortorder);
1919
            //print_liste_field_titre("ProductLabel", $_SERVER['PHP_SELF'], "p.label", "", $param, '', $sortfield, $sortorder);
1920
            print_liste_field_titre("ProductDescription", $_SERVER['PHP_SELF'], "l.description", "", $param, '', $sortfield, $sortorder);
1921
            print_liste_field_titre("Amount", $_SERVER['PHP_SELF'], "l.total_ht", "", $param, '', $sortfield, $sortorder, 'right maxwidth50 ');
1922
            print_liste_field_titre("VATRate", $_SERVER['PHP_SELF'], "l.tva_tx", "", $param, '', $sortfield, $sortorder, 'right ', '', 1);
1923
            print_liste_field_titre("ThirdParty", $_SERVER['PHP_SELF'], "s.nom", "", $param, '', $sortfield, $sortorder);
1924
            print_liste_field_titre("Country", $_SERVER['PHP_SELF'], "co.label", "", $param, '', $sortfield, $sortorder);
1925
            print_liste_field_titre("VATIntraShort", $_SERVER['PHP_SELF'], "s.tva_intra", "", $param, '', $sortfield, $sortorder);
1926
            print_liste_field_titre("DataUsedToSuggestAccount", '', '', '', '', '', '', '', 'nowraponall ');
1927
            print_liste_field_titre("AccountAccountingSuggest", '', '', '', '', '', '', '', 'center ');
1928
            $checkpicto = '';
1929
            if ($massactionbutton) {
1930
                $checkpicto = $form->showCheckAddButtons('checkforselect', 1);
1931
            }
1932
            print_liste_field_titre($checkpicto, '', '', '', '', '', '', '', 'center ');
1933
            print "</tr>\n";
1934
1935
            $thirdpartystatic = new Societe($db);
1936
            $facturefourn_static = new FactureFournisseur($db);
1937
            $facturefourn_static_det = new SupplierInvoiceLine($db);
1938
            $product_static = new Product($db);
1939
1940
1941
            $accountingaccount_codetotid_cache = array();
1942
1943
            while ($i < min($num_lines, $limit)) {
1944
                $objp = $db->fetch_object($result);
1945
1946
                // product_type: 0 = service, 1 = product
1947
                // if product does not exist we use the value of product_type provided in facturedet to define if this is a product or service
1948
                // issue : if we change product_type value in product DB it should differ from the value stored in facturedet DB !
1949
                $code_buy_l = '';
1950
                $code_buy_p = '';
1951
                $code_buy_t = '';
1952
1953
                $thirdpartystatic->id = $objp->socid;
1954
                $thirdpartystatic->name = $objp->name;
1955
                $thirdpartystatic->client = $objp->client;
1956
                $thirdpartystatic->fournisseur = $objp->fournisseur;
1957
                $thirdpartystatic->code_client = $objp->code_client;
1958
                $thirdpartystatic->code_compta_client = $objp->code_compta_client;
1959
                $thirdpartystatic->code_fournisseur = $objp->code_fournisseur;
1960
                $thirdpartystatic->code_compta_fournisseur = $objp->code_compta_fournisseur;
1961
                $thirdpartystatic->email = $objp->email;
1962
                $thirdpartystatic->country_code = $objp->country_code;
1963
                $thirdpartystatic->tva_intra = $objp->tva_intra;
1964
                $thirdpartystatic->code_compta_product = $objp->company_code_buy;       // The accounting account for product stored on thirdparty object (for level3 suggestion)
1965
1966
                $product_static->ref = $objp->product_ref;
1967
                $product_static->id = $objp->product_id;
1968
                $product_static->type = $objp->type;
1969
                $product_static->label = $objp->product_label;
1970
                $product_static->status = $objp->status;
1971
                $product_static->status_buy = $objp->status_buy;
1972
                $product_static->accountancy_code_sell = $objp->code_sell;
1973
                $product_static->accountancy_code_sell_intra = $objp->code_sell_intra;
1974
                $product_static->accountancy_code_sell_export = $objp->code_sell_export;
1975
                $product_static->accountancy_code_buy = $objp->code_buy;
1976
                $product_static->accountancy_code_buy_intra = $objp->code_buy_intra;
1977
                $product_static->accountancy_code_buy_export = $objp->code_buy_export;
1978
                $product_static->tva_tx = $objp->tva_tx_prod;
1979
1980
                $facturefourn_static->ref = $objp->ref;
1981
                $facturefourn_static->id = $objp->facid;
1982
                $facturefourn_static->type = $objp->ftype;
1983
                $facturefourn_static->ref_supplier = $objp->ref_supplier;
1984
                $facturefourn_static->label = $objp->invoice_label;
1985
                $facturefourn_static->date = $db->jdate($objp->datef);
1986
                $facturefourn_static->fk_facture_source = $objp->fk_facture_source;
1987
1988
                $facturefourn_static_det->id = $objp->rowid;
1989
                $facturefourn_static_det->total_ht = $objp->total_ht;
1990
                $facturefourn_static_det->tva_tx = $objp->tva_tx_line;
1991
                $facturefourn_static_det->vat_src_code = $objp->vat_src_code;
1992
                $facturefourn_static_det->product_type = $objp->type_l;
1993
                $facturefourn_static_det->desc = $objp->description;
1994
1995
                $accountingAccountArray = array(
1996
                    'dom' => $objp->aarowid,
1997
                    'intra' => $objp->aarowid_intra,
1998
                    'export' => $objp->aarowid_export,
1999
                    'thirdparty' => $objp->aarowid_thirdparty);
2000
2001
                $code_buy_p_notset = '';
2002
                $code_buy_t_notset = '';
2003
2004
                $suggestedid = 0;
2005
2006
                $return = $accountingAccount->getAccountingCodeToBind($mysoc, $thirdpartystatic, $product_static, $facturefourn_static, $facturefourn_static_det, $accountingAccountArray, 'supplier');
2007
                if (!is_array($return) && $return < 0) {
2008
                    setEventMessage($accountingAccount->error, 'errors');
2009
                } else {
2010
                    $suggestedid = $return['suggestedid'];
2011
                    $suggestedaccountingaccountfor = $return['suggestedaccountingaccountfor'];
2012
                    $suggestedaccountingaccountbydefaultfor = $return['suggestedaccountingaccountbydefaultfor'];
2013
                    $code_buy_l = $return['code_l'];
2014
                    $code_buy_p = $return['code_p'];
2015
                    $code_buy_t = $return['code_t'];
2016
                }
2017
                //var_dump($return);
2018
2019
                if (!empty($code_buy_p)) {
2020
                    // Value was defined previously
2021
                } else {
2022
                    $code_buy_p_notset = 'color:orange';
2023
                }
2024
                if (empty($code_buy_l) && empty($code_buy_p)) {
2025
                    $code_buy_p_notset = 'color:red';
2026
                }
2027
                /*if ($suggestedaccountingaccountfor == 'eecwithoutvatnumber' && empty($code_sell_p_notset)) {
2028
                    $code_sell_p_notset = 'color:orange';
2029
                }*/
2030
2031
                // $code_buy_l is now default code of product/service
2032
                // $code_buy_p is now code of product/service
2033
                // $code_buy_t is now code of thirdparty
2034
                //var_dump($code_buy_l.' - '.$code_buy_p.' - '.$code_buy_t.' -> '.$suggestedid.' ('.$suggestedaccountingaccountbydefaultfor.' '.$suggestedaccountingaccountfor.')');
2035
2036
                print '<tr class="oddeven">';
2037
2038
                // Line id
2039
                print '<td>' . $facturefourn_static_det->id . '</td>';
2040
2041
                // Ref Invoice
2042
                print '<td class="nowraponall">' . $facturefourn_static->getNomUrl(1);
2043
                if ($objp->ref_supplier) {
2044
                    print '<br><span class="opacitymedium small">' . dol_escape_htmltag($objp->ref_supplier) . '</span>';
2045
                }
2046
                print '</td>';
2047
2048
                // Ref supplier invoice
2049
                /*print '<td class="tdoverflowmax100" title="'.dol_escape_htmltag($objp->ref_supplier).'">';
2050
                print $objp->ref_supplier;
2051
                print '</td>';*/
2052
2053
                // Supplier invoice label
2054
                print '<td class="tdoverflowmax100 small" title="' . dol_escape_htmltag($objp->invoice_label) . '">';
2055
                print dol_escape_htmltag($objp->invoice_label);
2056
                print '</td>';
2057
2058
                // Date
2059
                print '<td class="center">' . dol_print_date($facturefourn_static->date, 'day') . '</td>';
2060
2061
                // Ref Product
2062
                print '<td class="tdoverflowmax100">';
2063
                if ($product_static->id > 0) {
2064
                    print $product_static->getNomUrl(1);
2065
                }
2066
                if ($product_static->label) {
2067
                    print '<br><span class="opacitymedium small">' . dol_escape_htmltag($product_static->label) . '</span>';
2068
                }
2069
                print '</td>';
2070
2071
                // Description of line
2072
                print '<td class="tdoverflowonsmartphone small">';
2073
                $text = dolGetFirstLineOfText(dol_string_nohtmltag($facturefourn_static_det->desc, 1));
2074
                $trunclength = getDolGlobalInt('ACCOUNTING_LENGTH_DESCRIPTION', 32);
2075
                print $form->textwithtooltip(dol_trunc($text, $trunclength), $facturefourn_static_det->desc);
2076
                print '</td>';
2077
2078
                print '<td class="right nowraponall amount">';
2079
                print price($objp->total_ht);
2080
                print '</td>';
2081
2082
                // Vat rate
2083
                $code_vat_differ = '';
2084
                //if ($objp->vat_tx_l != $objp->vat_tx_p && price2num($objp->vat_tx_p) && price2num($objp->vat_tx_l)) { // Note: having a vat rate of 0 is often the normal case when sells is intra b2b or to export
2085
                //  $code_vat_differ = 'warning bold';
2086
                //}
2087
                print '<td class="right' . ($code_vat_differ ? ' ' . $code_vat_differ : '') . '">';
2088
                print vatrate($facturefourn_static_det->tva_tx . ($facturefourn_static_det->vat_src_code ? ' (' . $facturefourn_static_det->vat_src_code . ')' : ''), false, 0, 0, 1);
2089
                print '</td>';
2090
2091
                // Thirdparty
2092
                print '<td class="tdoverflowmax100">' . $thirdpartystatic->getNomUrl(1, 'supplier') . '</td>';
2093
2094
                // Country
2095
                $labelcountry = ($objp->country_code && ($langs->trans("Country" . $objp->country_code) != "Country" . $objp->country_code)) ? $langs->trans("Country" . $objp->country_code) : $objp->country_label;
2096
                print '<td class="tdoverflowmax100" title="' . dol_escape_htmltag($labelcountry) . '">';
2097
                print dol_escape_htmltag($labelcountry);
2098
                print '</td>';
2099
2100
                // VAT Num
2101
                print '<td class="tdoverflowmax80" title="' . dol_escape_htmltag($objp->tva_intra) . '">' . dol_escape_htmltag($objp->tva_intra) . '</td>';
2102
2103
                // Found accounts
2104
                print '<td class="small">';
2105
                $s = '1. ' . (($facturefourn_static_det->product_type == 1) ? $langs->trans("DefaultForService") : $langs->trans("DefaultForProduct")) . ': ';
2106
                $shelp = '';
2107
                $ttype = 'help';
2108
                if ($suggestedaccountingaccountbydefaultfor == 'eec') {
2109
                    $shelp .= $langs->trans("SaleEEC");
2110
                } elseif ($suggestedaccountingaccountbydefaultfor == 'eecwithvat') {
2111
                    $shelp = $langs->trans("SaleEECWithVAT");
2112
                } elseif ($suggestedaccountingaccountbydefaultfor == 'eecwithoutvatnumber') {
2113
                    $shelp = $langs->trans("SaleEECWithoutVATNumber");
2114
                    $ttype = 'warning';
2115
                } elseif ($suggestedaccountingaccountbydefaultfor == 'export') {
2116
                    $shelp .= $langs->trans("SaleExport");
2117
                }
2118
                $s .= ($code_buy_l > 0 ? length_accountg($code_buy_l) : '<span style="' . $code_buy_p_notset . '">' . $langs->trans("NotDefined") . '</span>');
2119
                print $form->textwithpicto($s, $shelp, 1, $ttype, '', 0, 2, '', 1);
2120
                if ($product_static->id > 0) {
2121
                    print '<br>';
2122
                    $s = '2. ' . (($facturefourn_static_det->product_type == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")) . ': ';
2123
                    $shelp = '';
2124
                    $ttype = 'help';
2125
                    if ($suggestedaccountingaccountfor == 'eec') {
2126
                        $shelp = $langs->trans("SaleEEC");
2127
                    } elseif ($suggestedaccountingaccountfor == 'eecwithvat') {
2128
                        $shelp = $langs->trans("SaleEECWithVAT");
2129
                    } elseif ($suggestedaccountingaccountfor == 'eecwithoutvatnumber') {
2130
                        $shelp = $langs->trans("SaleEECWithoutVATNumber");
2131
                        $ttype = 'warning';
2132
                    } elseif ($suggestedaccountingaccountfor == 'export') {
2133
                        $shelp = $langs->trans("SaleExport");
2134
                    }
2135
                    $s .= (empty($code_buy_p) ? '<span style="' . $code_buy_p_notset . '">' . $langs->trans("NotDefined") . '</span>' : length_accountg($code_buy_p));
2136
                    print $form->textwithpicto($s, $shelp, 1, $ttype, '', 0, 2, '', 1);
2137
                } else {
2138
                    print '<br>';
2139
                    $s = '2. ' . (($objp->type_l == 1) ? $langs->trans("ThisService") : $langs->trans("ThisProduct")) . ': ';
2140
                    $shelp = '';
2141
                    $s .= $langs->trans("NotDefined");
2142
                    print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1);
2143
                }
2144
                if (getDolGlobalString('ACCOUNTANCY_USE_PRODUCT_ACCOUNT_ON_THIRDPARTY')) {
2145
                    print '<br>';
2146
                    $s = '3. ' . (($facturefourn_static_det->product_type == 1) ? $langs->trans("ServiceForThisThirdparty") : $langs->trans("ProductForThisThirdparty")) . ': ';
2147
                    $shelp = '';
2148
                    $s .= ($code_buy_t > 0 ? length_accountg($code_buy_t) : '<span style="' . $code_buy_t_notset . '">' . $langs->trans("NotDefined") . '</span>');
2149
                    print $form->textwithpicto($s, $shelp, 1, 'help', '', 0, 2, '', 1);
2150
                }
2151
                print '</td>';
2152
2153
                // Suggested accounting account
2154
                print '<td>';
2155
                print $formaccounting->select_account(($default_account > 0 && $confirm === 'yes' && in_array($objp->rowid . "_" . $i, $toselect)) ? $default_account : $suggestedid, 'codeventil' . $facturefourn_static_det->id, 1, array(), 0, 0, 'codeventil maxwidth150 maxwidthonsmartphone', 'cachewithshowemptyone');
2156
                print '</td>';
2157
2158
                // Column with checkbox
2159
                print '<td class="center">';
2160
                $ischecked = 0;
2161
                if (!empty($suggestedid) && $suggestedaccountingaccountfor != '' && $suggestedaccountingaccountfor != 'eecwithoutvatnumber') {
2162
                    $ischecked = 1;
2163
                }
2164
2165
                if (!empty($toselect)) {
2166
                    $ischecked = 0;
2167
                    if (in_array($objp->rowid . "_" . $i, $toselect)) {
2168
                        $ischecked = 1;
2169
                    }
2170
                }
2171
2172
                print '<input type="checkbox" class="flat checkforselect checkforselect' . $facturefourn_static_det->id . '" name="toselect[]" value="' . $facturefourn_static_det->id . "_" . $i . '"' . ($ischecked ? " checked" : "") . '/>';
2173
                print '</td>';
2174
2175
                print '</tr>';
2176
                $i++;
2177
            }
2178
            if ($num_lines == 0) {
2179
                print '<tr><td colspan="14"><span class="opacitymedium">' . $langs->trans("NoRecordFound") . '</span></td></tr>';
2180
            }
2181
2182
            print '</table>';
2183
            print "</div>";
2184
2185
            print '</form>';
2186
        } else {
2187
            print $db->error();
2188
        }
2189
        if ($db->type == 'mysqli') {
2190
            $db->query("SET SQL_BIG_SELECTS=0"); // Enable MAX_JOIN_SIZE limitation
2191
        }
2192
2193
// Add code to auto check the box when we select an account
2194
        print '<script type="text/javascript">
2195
jQuery(document).ready(function() {
2196
	jQuery(".codeventil").change(function() {
2197
		var s=$(this).attr("id").replace("codeventil", "")
2198
		console.log(s+" "+$(this).val());
2199
		if ($(this).val() == -1) jQuery(".checkforselect"+s).prop("checked", false);
2200
		else jQuery(".checkforselect"+s).prop("checked", true);
2201
	});
2202
});
2203
</script>';
2204
2205
// End of page
2206
        llxFooter();
2207
        $db->close();
2208
    }
2209
}
2210