Passed
Push — main ( 4b1ce6...7d2b49 )
by Rafael
80:06
created

Facture::__construct()   F

Complexity

Conditions 45
Paths > 20000

Size

Total Lines 711
Code Lines 550

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 45
eloc 550
nc 226492416
nop 1
dl 0
loc 711
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* Copyright (C) 2003-2004  Rodolphe Quiedeville    <[email protected]>
4
 * Copyright (C) 2004-2018	Laurent Destailleur		<[email protected]>
5
 * Copyright (C) 2004		Sebastien Di Cintio		<[email protected]>
6
 * Copyright (C) 2004		Benoit Mortier			<[email protected]>
7
 * Copyright (C) 2005-2012	Regis Houssin			<[email protected]>
8
 * Copyright (C) 2021		Alexandre Spangaro		<[email protected]>
9
 * Copyright (C) 2022       Frédéric France         <[email protected]>
10
 * Copyright (C) 2024		William Mead			<[email protected]>
11
 * Copyright (C) 2024       Rafael San José             <[email protected]>
12
 *
13
 * This program is free software; you can redistribute it and/or modify
14
 * it under the terms of the GNU General Public License as published by
15
 * the Free Software Foundation; either version 3 of the License, or
16
 * (at your option) any later version.
17
 *
18
 * This program is distributed in the hope that it will be useful,
19
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
 * GNU General Public License for more details.
22
 *
23
 * You should have received a copy of the GNU General Public License
24
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25
 */
26
27
/**
28
 *      \defgroup   facture     Module customer invoices
29
 *      \brief      Module to manage customer invoices
30
 *      \file       htdocs/core/modules/modFacture.class.php
31
 *      \ingroup    invoice
32
 *      \brief      Description and activation file for the module customer invoices
33
 */
34
35
namespace Dolibarr\Modules;
36
37
use Dolibarr\Core\Base\DolibarrModules;
38
use DoliDB;
39
40
/**
41
 *  Class to describe module customer invoices
42
 */
43
class Facture extends DolibarrModules
44
{
45
    /**
46
     *   Constructor. Define names, constants, directories, boxes, permissions
47
     *
48
     * @param DoliDB $db Database handler
49
     */
50
    public function __construct($db)
51
    {
52
        global $conf, $langs, $user, $mysoc;
53
54
        $this->db = $db;
0 ignored issues
show
Documentation Bug introduced by
It seems like $db of type DoliDB is incompatible with the declared type Dolibarr\Core\Base\DoliDB of property $db.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
55
        $this->numero = 30;
56
57
        $this->family = "financial";
58
        $this->module_position = '11';
59
        // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
60
        $this->name = preg_replace('/^mod/i', '', get_class($this));
61
        $this->description = "Gestion des factures";
62
63
        // Possible values for version are: 'development', 'experimental', 'dolibarr' or version
64
        $this->version = 'dolibarr';
65
66
        $this->const_name = 'MAIN_MODULE_' . static::getNameOf($this->name); // strtoupper($this->name);
67
        $this->picto = 'bill';
68
69
        // Data directories to create when module is enabled
70
        $this->dirs = array("/facture/temp");
71
72
        // Dependencies
73
        $this->depends = array('always' => "modSociete");
74
        $this->requiredby = array("modComptabilite", "modAccounting");
75
        $this->conflictwith = array();
76
        $this->langfiles = array("bills", "companies", "compta", "products");
77
        $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='text')
78
        $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='text')
79
80
        // Config pages
81
        $this->config_page_url = array("invoice.php");
82
83
        // Constants
84
        $this->const = array();
85
        $r = 0;
86
87
        $this->const[$r][0] = "FACTURE_ADDON";
88
        $this->const[$r][1] = "chaine";
89
        $this->const[$r][2] = "mod_facture_terre";
90
        $this->const[$r][3] = 'Name of numbering numerotation rules of invoice';
91
        $this->const[$r][4] = 0;
92
        $r++;
93
94
        $this->const[$r][0] = "FACTURE_ADDON_PDF";
95
        $this->const[$r][1] = "chaine";
96
        $this->const[$r][2] = "sponge";
97
        $this->const[$r][3] = 'Name of PDF model of invoice';
98
        $this->const[$r][4] = 0;
99
        $r++;
100
101
        $this->const[$r][0] = "FACTURE_ADDON_PDF_ODT_PATH";
102
        $this->const[$r][1] = "chaine";
103
        $this->const[$r][2] = "DOL_DATA_ROOT/doctemplates/invoices";
104
        $this->const[$r][3] = "";
105
        $this->const[$r][4] = 0;
106
        $r++;
107
108
        // Boxes
109
        //$this->boxes = array(0=>array(1=>'box_factures_imp.php'),1=>array(1=>'box_factures.php'));
110
        $this->boxes = array(
111
            0 => array('file' => 'box_factures_imp.php', 'enabledbydefaulton' => 'Home'),
112
            1 => array('file' => 'box_factures.php', 'enabledbydefaulton' => 'Home'),
113
            2 => array('file' => 'box_graph_invoices_permonth.php', 'enabledbydefaulton' => 'Home'),
114
            3 => array('file' => 'box_customers_outstanding_bill_reached.php', 'enabledbydefaulton' => 'Home')
115
        );
116
117
        // Cronjobs
118
        $arraydate = dol_getdate(dol_now());
119
        $datestart = dol_mktime(23, 0, 0, $arraydate['mon'], $arraydate['mday'], $arraydate['year']);
120
        $this->cronjobs = array(
121
            0 => array(
122
                'label' => 'RecurringInvoicesJob',
123
                'jobtype' => 'method',
124
                'class' => 'compta/facture/class/facture-rec.class.php',
125
                'objectname' => 'FactureRec',
126
                'method' => 'createRecurringInvoices',
127
                'parameters' => '',
128
                'comment' => 'Generate recurring invoices',
129
                'frequency' => 1,
130
                'unitfrequency' => 3600 * 24,
131
                'priority' => 51,
132
                'status' => 1,
133
                'test' => '$conf->facture->enabled',
134
                'datestart' => $datestart
135
            ),
136
            1 => array(
137
                'label' => 'SendEmailsRemindersOnInvoiceDueDate',
138
                'jobtype' => 'method',
139
                'class' => 'compta/facture/class/facture.class.php',
140
                'objectname' => 'Facture',
141
                'method' => 'sendEmailsRemindersOnInvoiceDueDate',
142
                'parameters' => "10,all,EmailTemplateCode,duedate",
143
                'comment' => 'Send an email when we reach the invoice due date (or invoice date) - n days. First param is n, the number of days before due date (or invoice date) to send the remind (or after if value is negative), second parameter is "all" or a payment mode code, third parameter is the code of the email template to use (an email template with the EmailTemplateCode must exists. The version of the email template in the language of the thirdparty will be used in priority. Language of the thirdparty will be also used to update the PDF of the sent invoice). The fourth parameter is the string "duedate" (default) or "invoicedate" to define which date of the invoice to use.',
144
                'frequency' => 1,
145
                'unitfrequency' => 3600 * 24,
146
                'priority' => 50,
147
                'status' => 0,
148
                'test' => '$conf->facture->enabled',
149
                'datestart' => $datestart
150
            ),
151
        );
152
153
        // Permissions
154
        $this->rights = array();
155
        $this->rights_class = 'facture';
156
        $r = 0;
157
158
        $r++;
159
        $this->rights[$r][0] = 11;
160
        $this->rights[$r][1] = 'Read invoices';
161
        $this->rights[$r][2] = 'a';
162
        $this->rights[$r][3] = 0;
163
        $this->rights[$r][4] = 'lire';
164
165
        $r++;
166
        $this->rights[$r][0] = 12;
167
        $this->rights[$r][1] = 'Create and update invoices';
168
        $this->rights[$r][2] = 'a';
169
        $this->rights[$r][3] = 0;
170
        $this->rights[$r][4] = 'creer';
171
172
        // There is a particular permission for unvalidate because this may be not forbidden by some laws
173
        $r++;
174
        $this->rights[$r][0] = 13;
175
        $this->rights[$r][1] = 'Devalidate invoices';
176
        $this->rights[$r][2] = 'a';
177
        $this->rights[$r][3] = 0;
178
        $this->rights[$r][4] = 'invoice_advance';
179
        $this->rights[$r][5] = 'unvalidate';
180
181
        $r++;
182
        $this->rights[$r][0] = 14;
183
        $this->rights[$r][1] = 'Validate invoices';
184
        $this->rights[$r][2] = 'a';
185
        $this->rights[$r][3] = 0;
186
        $this->rights[$r][4] = 'invoice_advance';
187
        $this->rights[$r][5] = 'validate';
188
189
        $r++;
190
        $this->rights[$r][0] = 15;
191
        $this->rights[$r][1] = 'Send invoices by email';
192
        $this->rights[$r][2] = 'a';
193
        $this->rights[$r][3] = 0;
194
        $this->rights[$r][4] = 'invoice_advance';
195
        $this->rights[$r][5] = 'send';
196
197
        $r++;
198
        $this->rights[$r][0] = 16;
199
        $this->rights[$r][1] = 'Issue payments on invoices';
200
        $this->rights[$r][2] = 'a';
201
        $this->rights[$r][3] = 0;
202
        $this->rights[$r][4] = 'paiement';
203
204
        $r++;
205
        $this->rights[$r][0] = 19;
206
        $this->rights[$r][1] = 'Delete invoices';
207
        $this->rights[$r][2] = 'a';
208
        $this->rights[$r][3] = 0;
209
        $this->rights[$r][4] = 'supprimer';
210
211
        $r++;
212
        $this->rights[$r][0] = 1321;
213
        $this->rights[$r][1] = 'Export customer invoices, attributes and payments';
214
        $this->rights[$r][2] = 'r';
215
        $this->rights[$r][3] = 0;
216
        $this->rights[$r][4] = 'facture';
217
        $this->rights[$r][5] = 'export';
218
219
        $r++;
220
        $this->rights[$r][0] = 1322;
221
        $this->rights[$r][1] = 'Re-open a fully paid invoice';
222
        $this->rights[$r][2] = 'r';
223
        $this->rights[$r][3] = 0;
224
        $this->rights[$r][4] = 'invoice_advance';
225
        $this->rights[$r][5] = 'reopen';
226
227
228
        // Menus
229
        //-------
230
        $this->menu = 1; // This module add menu entries. They are coded into menu manager.
231
232
233
        // Imports
234
        //--------
235
        $r = 1;
236
237
        $r++;
238
        $this->import_code[$r] = $this->rights_class . '_' . $r;
239
        $this->import_label[$r] = "Invoices"; // Translation key
240
        $this->import_icon[$r] = $this->picto;
241
        $this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
242
        $this->import_tables_array[$r] = array('f' => MAIN_DB_PREFIX . 'facture', 'extra' => MAIN_DB_PREFIX . 'facture_extrafields');
243
        $this->import_tables_creator_array[$r] = array('f' => 'fk_user_author'); // Fields to store import user id
244
        $this->import_fields_array[$r] = array(
245
            'f.ref' => 'InvoiceRef*',
246
            'f.ref_ext' => 'ExternalRef',
247
            'f.ref_client' => 'RefCustomer',
248
            'f.type' => 'Type*',
249
            'f.fk_soc' => 'Customer*',
250
            'f.datec' => 'InvoiceDateCreation',
251
            'f.datef' => 'DateInvoice',
252
            'f.date_valid' => 'Validation Date',
253
            'f.paye' => 'InvoicePaid',
254
            'f.total_tva' => 'TotalVAT',
255
            'f.total_ht' => 'TotalHT',
256
            'f.total_ttc' => 'TotalTTC',
257
            'f.fk_statut' => 'InvoiceStatus',
258
            'f.fk_user_modif' => 'Modifier Id',
259
            'f.fk_user_valid' => 'Validator Id',
260
            'f.fk_user_closing' => 'Closer Id',
261
            'f.fk_facture_source' => 'Invoice Source Id',
262
            'f.fk_projet' => 'Project Id',
263
            'f.fk_account' => 'Bank Account',
264
            'f.fk_currency' => 'Currency*',
265
            'f.fk_cond_reglement' => 'PaymentTerm',
266
            'f.fk_mode_reglement' => 'PaymentMode',
267
            'f.date_lim_reglement' => 'DateMaxPayment',
268
            'f.note_public' => 'InvoiceNote',
269
            'f.note_private' => 'NotePrivate',
270
            'f.model_pdf' => 'Model'
271
        );
272
        if (isModEnabled("multicurrency")) {
273
            $this->import_fields_array[$r]['f.multicurrency_code'] = 'Currency';
274
            $this->import_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate';
275
            $this->import_fields_array[$r]['f.multicurrency_total_ht'] = 'MulticurrencyAmountHT';
276
            $this->import_fields_array[$r]['f.multicurrency_total_tva'] = 'MulticurrencyAmountVAT';
277
            $this->import_fields_array[$r]['f.multicurrency_total_ttc'] = 'MulticurrencyAmountTTC';
278
        }
279
        // Add extra fields
280
        $import_extrafield_sample = array();
281
        $sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'facture' AND entity IN (0, " . $conf->entity . ")";
282
        $resql = $this->db->query($sql);
283
        if ($resql) {
284
            while ($obj = $this->db->fetch_object($resql)) {
285
                $fieldname = 'extra.' . $obj->name;
286
                $fieldlabel = ucfirst($obj->label);
287
                $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
288
                $import_extrafield_sample[$fieldname] = $fieldlabel;
289
            }
290
        }
291
        // End add extra fields
292
        $this->import_fieldshidden_array[$r] = array('extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'facture');
293
        $this->import_regex_array[$r] = array('f.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency');
294
        $import_sample = array(
295
            'f.ref' => '(PROV0001)',
296
            'f.ref_ext' => '',
297
            'f.ref_client' => '',
298
            'f.type' => '0',
299
            'f.fk_soc' => '80LIMIT',
300
            'f.datec' => '2021-11-24',
301
            'f.datef' => '2021-11-24',
302
            'f.date_valid' => '2021-11-24',
303
            'f.paye' => '1',
304
            'f.total_tva' => '21',
305
            'f.total_ht' => '100',
306
            'f.total_ttc' => '121',
307
            'f.fk_statut' => '1',
308
            'f.fk_user_modif' => '',
309
            'f.fk_user_valid' => '',
310
            'f.fk_user_closing' => '',
311
            'f.fk_facture_source' => '',
312
            'f.fk_projet' => '',
313
            'f.fk_account' => '',
314
            'f.fk_currency' => 'EUR',
315
            'f.fk_cond_reglement' => '30D',
316
            'f.fk_mode_reglement' => 'VIR',
317
            'f.date_lim_reglement' => '2021-12-24',
318
            'f.note_public' => '',
319
            'f.note_private' => '',
320
            'f.model_pdf' => 'sponge',
321
            'f.multicurrency_code' => 'EUR',
322
            'f.multicurrency_tx' => '1',
323
            'f.multicurrency_total_ht' => '100',
324
            'f.multicurrency_total_tva' => '21',
325
            'f.multicurrency_total_ttc' => '121'
326
        );
327
        $this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample);
328
        $this->import_updatekeys_array[$r] = array('f.ref' => 'Ref');
329
        $this->import_convertvalue_array[$r] = array(
330
            'f.fk_soc' => array(
331
                'rule' => 'fetchidfromref',
332
                'file' => '/societe/class/societe.class.php',
333
                'class' => 'Societe',
334
                'method' => 'fetch',
335
                'element' => 'ThirdParty'
336
            ),
337
            'f.fk_projet' => array(
338
                'rule' => 'fetchidfromref',
339
                'file' => '/projet/class/project.class.php',
340
                'class' => 'Project',
341
                'method' => 'fetch',
342
                'element' => 'facture'
343
            ),
344
            'f.fk_cond_reglement' => array(
345
                'rule' => 'fetchidfromcodeorlabel',
346
                'file' => '/compta/facture/class/paymentterm.class.php',
347
                'class' => 'PaymentTerm',
348
                'method' => 'fetch',
349
                'element' => 'c_payment_term'
350
            )
351
        );
352
353
        // Import Invoice Lines
354
        $r++;
355
        $this->import_code[$r] = $this->rights_class . '_' . $r;
356
        $this->import_label[$r] = "InvoiceLine"; // Translation key
357
        $this->import_icon[$r] = $this->picto;
358
        $this->import_entities_array[$r] = array(); // We define here only fields that use another icon that the one defined into import_icon
359
        $this->import_tables_array[$r] = array('fd' => MAIN_DB_PREFIX . 'facturedet', 'extra' => MAIN_DB_PREFIX . 'facturedet_extrafields');
360
        $this->import_fields_array[$r] = array(
361
            'fd.fk_facture' => 'InvoiceRef*',
362
            'fd.fk_parent_line' => 'FacParentLine',
363
            'fd.fk_product' => 'IdProduct',
364
            'fd.label' => 'Label',
365
            'fd.description' => 'LineDescription*',
366
            'fd.vat_src_code' => 'Vat Source Code',
367
            'fd.tva_tx' => 'LineVATRate*',
368
            // localtax1_tx
369
            // localtax1_type
370
            // localtax2_tx
371
            // localtax2_type
372
            'fd.qty' => 'LineQty',
373
            'fd.remise_percent' => 'Reduc. (%)',
374
            // remise
375
            // fk_remise_except
376
            'fd.subprice' => 'UnitPriceHT',
377
            // price
378
            'fd.total_ht' => 'LineTotalHT',
379
            'fd.total_tva' => 'LineTotalVAT',
380
            // total_localtax1
381
            // total_localtax2
382
            'fd.total_ttc' => 'LineTotalTTC',
383
            'fd.product_type' => 'TypeOfLineServiceOrProduct',
384
            'fd.date_start' => 'Start Date',
385
            'fd.date_end' => 'End Date',
386
            // info_bits
387
            // buy_price_ht
388
            // fk_product_fournisseur_price
389
            // specia_code
390
            // rang
391
            // fk_contract_line
392
            'fd.fk_unit' => 'Unit',
393
            // fk_code_ventilation
394
            // situation_percent
395
            // fk_prev_id
396
            // fk_user_author
397
            // fk_user_modif
398
            // ref_ext
399
        );
400
        if (isModEnabled("multicurrency")) {
401
            $this->import_fields_array[$r]['fd.multicurrency_code'] = 'Currency';
402
            $this->import_fields_array[$r]['fd.multicurrency_subprice'] = 'CurrencyRate';
403
            $this->import_fields_array[$r]['fd.multicurrency_total_ht'] = 'MulticurrencyAmountHT';
404
            $this->import_fields_array[$r]['fd.multicurrency_total_tva'] = 'MulticurrencyAmountVAT';
405
            $this->import_fields_array[$r]['fd.multicurrency_total_ttc'] = 'MulticurrencyAmountTTC';
406
        }
407
        // Add extra fields
408
        $import_extrafield_sample = array();
409
        $sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'facture_det' AND entity IN (0, " . $conf->entity . ")";
410
        $resql = $this->db->query($sql);
411
        if ($resql) {
412
            while ($obj = $this->db->fetch_object($resql)) {
413
                $fieldname = 'extra.' . $obj->name;
414
                $fieldlabel = ucfirst($obj->label);
415
                $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : '');
416
                $import_extrafield_sample[$fieldname] = $fieldlabel;
417
            }
418
        }
419
        // End add extra fields
420
        $this->import_fieldshidden_array[$r] = array('extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'facturedet');
421
        $this->import_regex_array[$r] = array(
422
            'fd.fk_product' => 'rowid@' . MAIN_DB_PREFIX . 'product',
423
            'fd.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency'
424
        );
425
        $import_sample = array(
426
            'fd.fk_facture' => '(PROV00001)',
427
            'fd.fk_parent_line' => '',
428
            'fd.fk_product' => '',
429
            'fd.label' => '',
430
            'fd.description' => 'Test product',
431
            'fd.vat_src_code' => '',
432
            'fd.tva_tx' => '21',
433
            // localtax1_tx
434
            // localtax1_type
435
            // localtax2_tx
436
            // localtax2_type
437
            'fd.qty' => '1',
438
            'fd.remise_percent' => '0',
439
            // remise
440
            // fk_remise_except
441
            'fd.subprice' => '100',
442
            // price
443
            'fd.total_ht' => '100',
444
            'fd.total_tva' => '21',
445
            // total_localtax1
446
            // total_localtax2
447
            'fd.total_ttc' => '121',
448
            'fd.product_type' => '0',
449
            'fd.date_start' => '',
450
            'fd.date_end' => '',
451
            // info_bits
452
            // buy_price_ht
453
            // fk_product_fournisseur_price
454
            // specia_code
455
            // rang
456
            // fk_contract_line
457
            'fd.fk_unit' => '',
458
            // fk_code_ventilation
459
            // situation_percent
460
            // fk_prev_id
461
            // fk_user_author
462
            // fk_user_modif
463
            // ref_ext
464
            'fd.multicurrency_code' => 'EUR',
465
            'fd.multicurrency_tx' => '21',
466
            'fd.multicurrency_total_ht' => '100',
467
            'fd.multicurrency_total_tva' => '21',
468
            'fd.multicurrency_total_ttc' => '121'
469
        );
470
        $this->import_examplevalues_array[$r] = array_merge($import_sample, $import_extrafield_sample);
471
        $this->import_updatekeys_array[$r] = array(
472
            'fd.rowid' => 'Row Id',
473
            'fd.fk_facture' => 'Invoice Id'
474
        );
475
        $this->import_convertvalue_array[$r] = array(
476
            'fd.fk_facture' => array(
477
                'rule' => 'fetchidfromref',
478
                'file' => '/compta/facture/class/facture.class.php',
479
                'class' => 'Facture',
480
                'method' => 'fetch',
481
                'element' => 'facture'
482
            ),
483
            'fd.fk_projet' => array(
484
                'rule' => 'fetchidfromref',
485
                'file' => '/projet/class/project.class.php',
486
                'class' => 'Project',
487
                'method' => 'fetch',
488
                'element' => 'facture'
489
            ),
490
        );
491
492
493
        // Exports
494
        //--------
495
        $uselocaltax1 = (is_object($mysoc) && $mysoc->localtax1_assuj) ? $mysoc->localtax1_assuj : 0;
496
        $uselocaltax2 = (is_object($mysoc) && $mysoc->localtax2_assuj) ? $mysoc->localtax2_assuj : 0;
497
498
        $r = 0;
499
500
        $langs->loadLangs(array("suppliers", "multicurrency", "bills"));
501
502
        $uselocaltax1 = $mysoc->localtax1_assuj ?? 0;
503
        $uselocaltax2 = $mysoc->localtax2_assuj ?? 0;
504
505
        $alias_product_perentity = !getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED') ? "p" : "ppe";
506
507
        // Invoices and lines
508
        $this->export_code[$r] = $this->rights_class . '_' . $r;
509
        $this->export_label[$r] = 'CustomersInvoicesAndInvoiceLines'; // Translation key (used only if key ExportDataset_xxx_z not found)
510
        $this->export_icon[$r] = 'invoice';
511
        $this->export_permission[$r] = array(array("facture", "facture", "export", "other"));
512
513
        $this->export_fields_array[$r] = array(
514
            's.rowid' => "IdCompany", 's.nom' => 'CompanyName', 'ps.nom' => 'ParentCompany', 's.code_client' => 'CustomerCode', 's.address' => 'Address', 's.zip' => 'Zip', 's.town' => 'Town', 'c.code' => 'CountryCode', 'cd.nom' => 'State',
515
            's.phone' => 'Phone',
516
            's.siren' => 'ProfId1', 's.siret' => 'ProfId2', 's.ape' => 'ProfId3', 's.idprof4' => 'ProfId4',
517
            's.code_compta' => 'CustomerAccountancyCode',
518
            's.code_compta_fournisseur' => 'SupplierAccountancyCode',
519
            's.tva_intra' => 'VATIntra',
520
            't.libelle' => "ThirdPartyType", // 'ce.code'=>"Staff", "cfj.libelle"=>"JuridicalStatus",
521
            'f.rowid' => "InvoiceId", 'f.ref' => "InvoiceRef", 'f.ref_client' => 'RefCustomer', 'f.fk_facture_source' => 'SourceInvoiceId',
522
            'f.type' => "Type", 'f.datec' => "InvoiceDateCreation", 'f.datef' => "DateInvoice", 'f.date_lim_reglement' => "DateDue",
523
            'f.fk_cond_reglement' => 'IdPaymentTerm', 'f.fk_mode_reglement' => 'IdPaymentMode',
524
            'f.total_ht' => "TotalHT", 'f.total_ttc' => "TotalTTC", 'f.total_tva' => "TotalVAT",
525
            'f.localtax1' => "TotalLT1", 'f.localtax2' => "TotalLT2",
526
            'f.paye' => "InvoicePaidCompletely", 'f.fk_statut' => 'InvoiceStatus', 'f.close_code' => 'EarlyClosingReason', 'f.close_note' => 'EarlyClosingComment',
527
            'none.rest' => 'Rest',
528
            'f.note_private' => "NotePrivate", 'f.note_public' => "NotePublic"
529
        );
530
        if (!$uselocaltax1) {
531
            unset($this->export_fields_array[$r]['f.localtax1']);
532
        }
533
        if (!$uselocaltax2) {
534
            unset($this->export_fields_array[$r]['f.localtax2']);
535
        }
536
537
        // Add multicurrency fields
538
        if (isModEnabled("multicurrency")) {
539
            $this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency';
540
            $this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate';
541
            $this->export_fields_array[$r]['f.multicurrency_total_ht'] = 'MulticurrencyAmountHT';
542
            $this->export_fields_array[$r]['f.multicurrency_total_tva'] = 'MulticurrencyAmountVAT';
543
            $this->export_fields_array[$r]['f.multicurrency_total_ttc'] = 'MulticurrencyAmountTTC';
544
        }
545
        // Add POS fields
546
        if (!empty($conf->cashdesk->enabled) || !empty($conf->takepos->enabled) || getDolGlobalString('INVOICE_SHOW_POS')) {
547
            $this->export_fields_array[$r]['f.module_source'] = 'Module';
548
            $this->export_fields_array[$r]['f.pos_source'] = 'POSTerminal';
549
        }
550
        $this->export_fields_array[$r] = $this->export_fields_array[$r] + array(
551
                'f.fk_user_author' => 'CreatedById', 'uc.login' => 'CreatedByLogin',
552
                'f.fk_user_valid' => 'ValidatedById', 'uv.login' => 'ValidatedByLogin',
553
                'pj.ref' => 'ProjectRef', 'pj.title' => 'ProjectLabel'
554
            );
555
        // Add multicompany field
556
        if (getDolGlobalString('MULTICOMPANY_ENTITY_IN_EXPORT_IF_SHARED')) {
557
            $nbofallowedentities = count(explode(',', getEntity('invoice')));
558
            if (isModEnabled('multicompany') && $nbofallowedentities > 1) {
559
                $this->export_fields_array[$r]['f.entity'] = 'Entity';
560
            }
561
        }
562
        $this->export_fields_array[$r] = $this->export_fields_array[$r] + array(
563
                'fd.rowid' => 'LineId', 'fd.description' => "LineDescription",
564
                'fd.subprice' => "LineUnitPrice", 'fd.qty' => "LineQty",
565
                'fd.tva_tx' => "LineVATRate",
566
                'fd.total_ht' => "LineTotalHT", 'fd.total_tva' => "LineTotalVAT", 'fd.total_ttc' => "LineTotalTTC",
567
                'fd.localtax1_tx' => "LineLT1Rate", 'fd.localtax1_type' => "LineLT1Type", 'fd.total_localtax1' => "LineTotalLT1",
568
                'fd.localtax2_tx' => "LineLT2Rate", 'fd.localtax2_type' => "LineLT2Type", 'fd.total_localtax2' => "LineTotalLT2",
569
                'fd.buy_price_ht' => 'BuyingPrice', 'fd.date_start' => "DateStart", 'fd.date_end' => "DateEnd", 'fd.special_code' => 'SpecialCode',
570
                'fd.product_type' => "TypeOfLineServiceOrProduct", 'fd.fk_product' => 'ProductId', 'p.ref' => 'ProductRef', 'p.label' => 'ProductLabel',
571
                $alias_product_perentity . '.accountancy_code_sell' => 'ProductAccountancySellCode',
572
                'aa.account_number' => 'AccountingAffectation'
573
            );
574
        if (!$uselocaltax1) {
575
            unset($this->export_fields_array[$r]['fd.localtax1_tx']);
576
            unset($this->export_fields_array[$r]['fd.localtax1_type']);
577
            unset($this->export_fields_array[$r]['fd.total_localtax1']);
578
        }
579
        if (!$uselocaltax2) {
580
            unset($this->export_fields_array[$r]['fd.localtax2_tx']);
581
            unset($this->export_fields_array[$r]['fd.localtax2_type']);
582
            unset($this->export_fields_array[$r]['fd.total_localtax2']);
583
        }
584
585
        $this->export_TypeFields_array[$r] = array(
586
            's.rowid' => 'Numeric', 's.nom' => 'Text', 'ps.nom' => 'Text', 's.code_client' => 'Text', 's.address' => 'Text', 's.zip' => 'Text', 's.town' => 'Text', 'c.code' => 'Text', 'cd.nom' => 'Text', 's.phone' => 'Text', 's.siren' => 'Text',
587
            's.siret' => 'Text', 's.ape' => 'Text', 's.idprof4' => 'Text', 's.code_compta' => 'Text', 's.code_compta_fournisseur' => 'Text', 's.tva_intra' => 'Text',
588
            't.libelle' => "Text", // 'ce.code'=>"List:c_effectif:libelle:code", "cfj.libelle"=>"Text",
589
            'f.rowid' => 'Numeric', 'f.ref' => "Text", 'f.ref_client' => 'Text', 'f.fk_facture_source' => 'Numeric', 'f.type' => "Numeric", 'f.datec' => "Date", 'f.datef' => "Date", 'f.date_lim_reglement' => "Date",
590
            'f.fk_cond_reglement' => 'Numeric', 'f.fk_mode_reglement' => 'Numeric',
591
            'f.total_ht' => "Numeric", 'f.total_ttc' => "Numeric", 'f.total_tva' => "Numeric", 'f.localtax1' => 'Numeric', 'f.localtax2' => 'Numeric', 'f.paye' => "Boolean", 'f.fk_statut' => 'Numeric', 'f.close_code' => 'Text', 'f.close_note' => 'Text',
592
            'none.rest' => "NumericCompute",
593
            'f.note_private' => "Text", 'f.note_public' => "Text",
594
            'f.module_source' => 'Text',
595
            'f.pos_source' => 'Text',
596
            'f.entity' => 'List:entity:label:rowid',
597
            'f.fk_user_author' => 'Numeric', 'uc.login' => 'Text', 'f.fk_user_valid' => 'Numeric', 'uv.login' => 'Text',
598
            'pj.ref' => 'Text', 'pj.title' => 'Text', 'fd.rowid' => 'Numeric', 'fd.description' => "Text", 'fd.subprice' => "Numeric", 'fd.tva_tx' => "Numeric",
599
            'fd.qty' => "Numeric", 'fd.buy_price_ht' => "Numeric", 'fd.date_start' => "Date", 'fd.date_end' => "Date",
600
            'fd.total_ht' => "Numeric", 'fd.total_tva' => "Numeric", 'fd.total_ttc' => "Numeric", 'fd.total_localtax1' => "Numeric", 'fd.total_localtax2' => "Numeric",
601
            'fd.localtax1_tx' => 'Numeric', 'fd.localtax2_tx' => 'Numeric', 'fd.localtax1_type' => 'Numeric', 'fd.localtax2_type' => 'Numeric',
602
            'fd.special_code' => 'Numeric', 'fd.product_type' => "Numeric", 'fd.fk_product' => 'List:product:label', 'p.ref' => 'Text', 'p.label' => 'Text',
603
            $alias_product_perentity . '.accountancy_code_sell' => 'Text',
604
            'aa.account_number' => 'Text',
605
            'f.multicurrency_code' => 'Text',
606
            'f.multicurrency_tx' => 'Number', 'f.multicurrency_total_ht' => 'Number', 'f.multicurrency_total_tva' => 'Number', 'f.multicurrency_total_ttc' => 'Number'
607
        );
608
        $this->export_entities_array[$r] = array(
609
            's.rowid' => "company", 's.nom' => 'company', 'ps.nom' => 'company', 's.code_client' => 'company', 's.address' => 'company', 's.zip' => 'company', 's.town' => 'company', 'c.code' => 'company', 'cd.nom' => 'company', 's.phone' => 'company',
610
            's.siren' => 'company', 's.siret' => 'company', 's.ape' => 'company', 's.idprof4' => 'company', 's.code_compta' => 'company', 's.code_compta_fournisseur' => 'company', 's.tva_intra' => 'company',
611
            't.libelle' => 'company', // 'ce.code'=>'company', 'cfj.libelle'=>'company'
612
            'pj.ref' => 'project', 'pj.title' => 'project', 'fd.rowid' => 'invoice_line', 'fd.description' => "invoice_line",
613
            'fd.subprice' => "invoice_line", 'fd.buy_price_ht' => 'invoice_line',
614
            'fd.total_ht' => "invoice_line", 'fd.total_tva' => "invoice_line", 'fd.total_ttc' => "invoice_line", 'fd.total_localtax1' => "invoice_line", 'fd.total_localtax2' => "invoice_line",
615
            'fd.tva_tx' => "invoice_line", 'fd.localtax1_tx' => "invoice_line", 'fd.localtax2_tx' => "invoice_line", 'fd.localtax1_type' => "invoice_line", 'fd.localtax2_type' => "invoice_line",
616
            'fd.qty' => "invoice_line", 'fd.date_start' => "invoice_line", 'fd.date_end' => "invoice_line", 'fd.special_code' => 'invoice_line',
617
            'fd.product_type' => 'invoice_line', 'fd.fk_product' => 'product', 'p.ref' => 'product', 'p.label' => 'product', $alias_product_perentity . '.accountancy_code_sell' => 'product',
618
            'f.fk_user_author' => 'user', 'uc.login' => 'user', 'f.fk_user_valid' => 'user', 'uv.login' => 'user',
619
            'aa.account_number' => "invoice_line",
620
        );
621
        $this->export_help_array[$r] = array('fd.buy_price_ht' => 'CostPriceUsage');
622
        $this->export_special_array[$r] = array('none.rest' => 'getRemainToPay');
623
        $this->export_dependencies_array[$r] = array('invoice_line' => 'fd.rowid', 'product' => 'fd.rowid', 'none.rest' => array('f.rowid', 'f.total_ttc', 'f.close_code')); // To add unique key if we ask a field of a child to avoid the DISTINCT to discard them
624
        $keyforselect = 'facture';
625
        $keyforelement = 'invoice';
626
        $keyforaliasextra = 'extra';
627
        include DOL_DOCUMENT_ROOT . '/core/extrafieldsinexport.inc.php';
628
        $keyforselect = 'facturedet';
629
        $keyforelement = 'invoice_line';
630
        $keyforaliasextra = 'extra2';
631
        include DOL_DOCUMENT_ROOT . '/core/extrafieldsinexport.inc.php';
632
        $keyforselect = 'product';
633
        $keyforelement = 'product';
634
        $keyforaliasextra = 'extra3';
635
        include DOL_DOCUMENT_ROOT . '/core/extrafieldsinexport.inc.php';
636
        $keyforselect = 'societe';
637
        $keyforelement = 'company';
638
        $keyforaliasextra = 'extra4';
639
        include DOL_DOCUMENT_ROOT . '/core/extrafieldsinexport.inc.php';
640
        $this->export_sql_start[$r] = 'SELECT DISTINCT ';
641
        $this->export_sql_end[$r] = ' FROM ' . MAIN_DB_PREFIX . 'societe as s';
642
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe_extrafields as extra4 ON s.rowid = extra4.fk_object';
643
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe as ps ON ps.rowid = s.parent';
644
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_typent as t ON s.fk_typent = t.id';
645
        if (!empty($user) && !$user->hasRight('societe', 'client', 'voir')) {
646
            $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe_commerciaux as sc ON sc.fk_soc = s.rowid';
647
        }
648
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_country as c on s.fk_pays = c.rowid';
649
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_departements as cd on s.fk_departement = cd.rowid,';
650
        $this->export_sql_end[$r] .= ' ' . MAIN_DB_PREFIX . 'facture as f';
651
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'projet as pj ON f.fk_projet = pj.rowid';
652
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'user as uc ON f.fk_user_author = uc.rowid';
653
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'user as uv ON f.fk_user_valid = uv.rowid';
654
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'facture_extrafields as extra ON f.rowid = extra.fk_object';
655
        $this->export_sql_end[$r] .= ' , ' . MAIN_DB_PREFIX . 'facturedet as fd';
656
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'facturedet_extrafields as extra2 on fd.rowid = extra2.fk_object';
657
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'product as p on (fd.fk_product = p.rowid)';
658
        if (getDolGlobalString('MAIN_PRODUCT_PERENTITY_SHARED')) {
659
            $this->export_sql_end[$r] .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int)$conf->entity);
660
        }
661
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'product_extrafields as extra3 on p.rowid = extra3.fk_object';
662
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'accounting_account as aa on fd.fk_code_ventilation = aa.rowid';
663
        $this->export_sql_end[$r] .= ' WHERE f.fk_soc = s.rowid AND f.rowid = fd.fk_facture';
664
        $this->export_sql_end[$r] .= ' AND f.entity IN (' . getEntity('invoice') . ')';
665
        if (!empty($user) && !$user->hasRight('societe', 'client', 'voir')) {
666
            $this->export_sql_end[$r] .= ' AND sc.fk_user = ' . (empty($user) ? 0 : $user->id);
667
        }
668
        $r++;
669
670
        // Invoices and payments
671
        $this->export_code[$r] = $this->rights_class . '_' . $r;
672
        $this->export_label[$r] = 'CustomersInvoicesAndPayments'; // Translation key (used only if key ExportDataset_xxx_z not found)
673
        $this->export_icon[$r] = 'invoice';
674
        $this->export_permission[$r] = array(array("facture", "facture", "export"));
675
        $this->export_fields_array[$r] = array(
676
            's.rowid' => "IdCompany", 's.nom' => 'CompanyName', 's.code_client' => 'CustomerCode', 's.address' => 'Address', 's.zip' => 'Zip', 's.town' => 'Town', 'c.code' => 'CountryCode', 'cd.nom' => 'State',
677
            's.phone' => 'Phone',
678
            's.siren' => 'ProfId1', 's.siret' => 'ProfId2', 's.ape' => 'ProfId3', 's.idprof4' => 'ProfId4', 's.code_compta' => 'CustomerAccountancyCode',
679
            's.code_compta_fournisseur' => 'SupplierAccountancyCode', 's.tva_intra' => 'VATIntra',
680
            'f.rowid' => "InvoiceId", 'f.ref' => "InvoiceRef", 'f.ref_client' => 'RefCustomer', 'f.fk_facture_source' => 'SourceInvoiceId',
681
            'f.type' => "Type", 'f.datec' => "InvoiceDateCreation", 'f.datef' => "DateInvoice", 'f.date_lim_reglement' => "DateDue",
682
            'f.fk_cond_reglement' => 'IdPaymentTerm', 'f.fk_mode_reglement' => 'IdPaymentMode',
683
            'f.total_ht' => "TotalHT", 'f.total_ttc' => "TotalTTC", 'f.total_tva' => "TotalVAT", 'f.localtax1' => 'LT1', 'f.localtax2' => 'LT2', 'f.paye' => "InvoicePaidCompletely", 'f.fk_statut' => 'InvoiceStatus', 'f.close_code' => 'EarlyClosingReason', 'f.close_note' => 'EarlyClosingComment',
684
            'none.rest' => 'Rest',
685
            'f.note_private' => "NotePrivate", 'f.note_public' => "NotePublic", 'f.fk_user_author' => 'CreatedById', 'uc.login' => 'CreatedByLogin',
686
            'f.fk_user_valid' => 'ValidatedById', 'uv.login' => 'ValidatedByLogin', 'pj.ref' => 'ProjectRef', 'pj.title' => 'ProjectLabel', 'p.rowid' => 'PaymentId', 'p.ref' => 'PaymentRef',
687
            'p.amount' => 'AmountPayment', 'pf.amount' => 'AmountPaymentDistributedOnInvoice', 'p.datep' => 'DatePayment', 'p.num_paiement' => 'PaymentNumber',
688
            'pt.code' => 'CodePaymentMode', 'pt.libelle' => 'LabelPaymentMode', 'p.note' => 'PaymentNote', 'p.fk_bank' => 'IdTransaction', 'ba.ref' => 'AccountRef'
689
        );
690
        if (!$uselocaltax1) {
691
            unset($this->export_fields_array[$r]['f.localtax1']);
692
        }
693
        if (!$uselocaltax2) {
694
            unset($this->export_fields_array[$r]['f.localtax2']);
695
        }
696
697
        $this->export_help_array[$r] = array('f.paye' => 'InvoicePaidCompletelyHelp');
698
        if (isModEnabled("multicurrency")) {
699
            $this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency';
700
            $this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate';
701
            $this->export_fields_array[$r]['f.multicurrency_total_ht'] = 'MulticurrencyAmountHT';
702
            $this->export_fields_array[$r]['f.multicurrency_total_tva'] = 'MulticurrencyAmountVAT';
703
            $this->export_fields_array[$r]['f.multicurrency_total_ttc'] = 'MulticurrencyAmountTTC';
704
            $this->export_examplevalues_array[$r]['f.multicurrency_code'] = 'EUR';
705
        }
706
        if (!empty($conf->cashdesk->enabled) || !empty($conf->takepos->enabled) || getDolGlobalString('INVOICE_SHOW_POS')) {
707
            $this->export_fields_array[$r]['f.module_source'] = 'POSModule';
708
            $this->export_fields_array[$r]['f.pos_source'] = 'POSTerminal';
709
        }
710
        $this->export_TypeFields_array[$r] = array(
711
            's.rowid' => 'Numeric', 's.nom' => 'Text', 's.code_client' => 'Text', 's.address' => 'Text', 's.zip' => 'Text', 's.town' => 'Text', 'c.code' => 'Text', 'cd.nom' => 'Text', 's.phone' => 'Text', 's.siren' => 'Text',
712
            's.siret' => 'Text', 's.ape' => 'Text', 's.idprof4' => 'Text', 's.code_compta' => 'Text', 's.code_compta_fournisseur' => 'Text', 's.tva_intra' => 'Text',
713
            'f.rowid' => "Numeric", 'f.ref' => "Text", 'f.ref_client' => 'Text', 'f.fk_facture_source' => 'Numeric', 'f.type' => "Numeric", 'f.datec' => "Date", 'f.datef' => "Date", 'f.date_lim_reglement' => "Date",
714
            'f.fk_cond_reglement' => 'Numeric', 'f.fk_mode_reglement' => 'Numeric',
715
            'f.total_ht' => "Numeric", 'f.total_ttc' => "Numeric", 'f.total_tva' => "Numeric", 'f.localtax1' => 'Numeric', 'f.localtax2' => 'Numeric', 'f.paye' => "Boolean", 'f.fk_statut' => 'Status', 'f.close_code' => 'Text', 'f.close_note' => 'Text',
716
            'none.rest' => 'NumericCompute',
717
            'f.note_private' => "Text", 'f.note_public' => "Text", 'f.fk_user_author' => 'Numeric', 'uc.login' => 'Text', 'f.fk_user_valid' => 'Numeric', 'uv.login' => 'Text',
718
            'pj.ref' => 'Text', 'pj.title' => 'Text', 'p.amount' => 'Numeric', 'pf.amount' => 'Numeric', 'p.rowid' => 'Numeric', 'p.ref' => 'Text', 'p.title' => 'Text', 'p.datep' => 'Date', 'p.num_paiement' => 'Numeric',
719
            'p.fk_bank' => 'Numeric', 'p.note' => 'Text', 'pt.code' => 'Text', 'pt.libelle' => 'text', 'ba.ref' => 'Text'
720
        );
721
        if (!empty($conf->cashdesk->enabled) || !empty($conf->takepos->enabled) || getDolGlobalString('INVOICE_SHOW_POS')) {
722
            $this->export_fields_array[$r]['f.module_source'] = 'POSModule';
723
            $this->export_fields_array[$r]['f.pos_source'] = 'POSTerminal';
724
        }
725
        $this->export_entities_array[$r] = array(
726
            's.rowid' => "company", 's.nom' => 'company', 's.code_client' => 'company', 's.address' => 'company', 's.zip' => 'company', 's.town' => 'company', 'c.code' => 'company', 'cd.nom' => 'company', 's.phone' => 'company',
727
            's.siren' => 'company', 's.siret' => 'company', 's.ape' => 'company', 's.idprof4' => 'company', 's.code_compta' => 'company', 's.code_compta_fournisseur' => 'company',
728
            's.tva_intra' => 'company', 'pj.ref' => 'project', 'pj.title' => 'project', 'p.rowid' => 'payment', 'p.ref' => 'payment', 'p.amount' => 'payment', 'pf.amount' => 'payment', 'p.datep' => 'payment',
729
            'p.num_paiement' => 'payment', 'pt.code' => 'payment', 'pt.libelle' => 'payment', 'p.note' => 'payment', 'f.fk_user_author' => 'user', 'uc.login' => 'user',
730
            'f.fk_user_valid' => 'user', 'uv.login' => 'user', 'p.fk_bank' => 'account', 'ba.ref' => 'account'
731
        );
732
        $this->export_special_array[$r] = array('none.rest' => 'getRemainToPay');
733
        $this->export_dependencies_array[$r] = array('payment' => 'p.rowid', 'none.rest' => array('f.rowid', 'f.total_ttc', 'f.close_code')); // To add unique key if we ask a field of a child to avoid the DISTINCT to discard them, or just to have field we need
734
        $keyforselect = 'facture';
735
        $keyforelement = 'invoice';
736
        $keyforaliasextra = 'extra';
737
        include DOL_DOCUMENT_ROOT . '/core/extrafieldsinexport.inc.php';
738
        $this->export_sql_start[$r] = 'SELECT DISTINCT ';
739
        $this->export_sql_end[$r] = ' FROM ' . MAIN_DB_PREFIX . 'societe as s';
740
        if (!empty($user) && !$user->hasRight('societe', 'client', 'voir')) {
741
            $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'societe_commerciaux as sc ON sc.fk_soc = s.rowid';
742
        }
743
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_country as c on s.fk_pays = c.rowid';
744
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_departements as cd on s.fk_departement = cd.rowid,';
745
        $this->export_sql_end[$r] .= ' ' . MAIN_DB_PREFIX . 'facture as f';
746
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'projet as pj ON f.fk_projet = pj.rowid';
747
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'user as uc ON f.fk_user_author = uc.rowid';
748
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'user as uv ON f.fk_user_valid = uv.rowid';
749
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'facture_extrafields as extra ON f.rowid = extra.fk_object';
750
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'paiement_facture as pf ON pf.fk_facture = f.rowid';
751
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'paiement as p ON pf.fk_paiement = p.rowid';
752
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_paiement as pt ON pt.id = p.fk_paiement';
753
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank as b ON b.rowid = p.fk_bank';
754
        $this->export_sql_end[$r] .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'bank_account as ba ON ba.rowid = b.fk_account';
755
        $this->export_sql_end[$r] .= ' WHERE f.fk_soc = s.rowid';
756
        $this->export_sql_end[$r] .= ' AND f.entity IN (' . getEntity('invoice') . ')';
757
        if (!empty($user) && !$user->hasRight('societe', 'client', 'voir')) {
758
            $this->export_sql_end[$r] .= ' AND sc.fk_user = ' . (empty($user) ? 0 : $user->id);
759
        }
760
        $r++;
761
    }
762
763
764
    /**
765
     *  Function called when module is enabled.
766
     *  The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
767
     *  It also creates data directories
768
     *
769
     * @param string $options Options when enabling module ('', 'newboxdefonly', 'noboxes')
770
     * @return     int                 1 if OK, 0 if KO
771
     */
772
    public function init($options = '')
773
    {
774
        global $conf, $langs;
775
776
        // Remove permissions and default values
777
        $this->remove($options);
778
779
        //ODT template
780
        $src = DOL_DOCUMENT_ROOT . '/install/doctemplates/invoices/template_invoice.odt';
781
        $dirodt = DOL_DATA_ROOT . '/doctemplates/invoices';
782
        $dest = $dirodt . '/template_invoice.odt';
783
784
        if (file_exists($src) && !file_exists($dest)) {
785
            require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/files.lib.php';
786
            dol_mkdir($dirodt);
787
            $result = dol_copy($src, $dest, 0, 0);
788
            if ($result < 0) {
789
                $langs->load("errors");
790
                $this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest);
791
                return 0;
792
            }
793
        }
794
795
        $sql = array(
796
            "DELETE FROM " . MAIN_DB_PREFIX . "document_model WHERE nom = '" . $this->db->escape($this->const[1][2]) . "' AND type = 'invoice' AND entity = " . ((int)$conf->entity),
797
            "INSERT INTO " . MAIN_DB_PREFIX . "document_model (nom, type, entity) VALUES('" . $this->db->escape($this->const[1][2]) . "','invoice'," . ((int)$conf->entity) . ")"
798
        );
799
800
        return $this->_init($sql, $options);
801
    }
802
}
803