Passed
Push — master ( 284492...2c3033 )
by Alxarafe
27:10
created

Company::getSalesRepresentatives()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 43
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 34
nc 8
nop 2
dl 0
loc 43
rs 8.7537
c 0
b 0
f 0
1
<?php
2
3
4
namespace Alixar\Models;
5
6
use Alixar\Base\AlixarModel;
7
8
class Company extends AlixarModel
9
{
10
11
    /**
12
     * @var string ID to identify managed object
13
     */
14
    public $element = 'societe';
15
16
    /**
17
     * @var string Name of table without prefix where object is stored
18
     */
19
    public $table_element = 'societe';
20
21
    /**
22
     * @var int Field with ID of parent key if this field has a parent
23
     */
24
    public $fk_element = 'fk_soc';
25
    public $fieldsforcombobox = 'nom,name_alias';
26
    public $picto = 'company';    // To test if we can delete object
27
    /**
28
     * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
29
     * @var int
30
     */
31
    public $ismultientitymanaged = 1;
32
    /**
33
     * 0=Default, 1=View may be restricted to sales representative only if no permission to see all or to company of external user if external user
34
     * @var integer
35
     */
36
    public $restrictiononfksoc = 1;
37
    /**
38
     * @var int Entity
39
     */
40
    public $entity;
41
    /**
42
     * Thirdparty name
43
     * @var string
44
     * @deprecated Use $name instead
45
     * @see $name
46
     */
47
    public $nom;
48
    // BEGIN MODULEBUILDER PROPERTIES
49
    /**
50
     * @var string name
51
     */
52
    public $name;
53
    /**
54
     * Alias names (commercial, trademark or alias names)
55
     * @var string
56
     */
57
    public $name_alias;
58
    public $particulier;
59
    /**
60
     * @var string Address
61
     */
62
    public $address;
63
    public $zip;
64
    public $town;
65
    /**
66
     * Thirdparty status : 0=activity ceased, 1= in activity
67
     * @var int
68
     */
69
    public $status = 1;
70
    /**
71
     * Id of department
72
     * @var int
73
     */
74
    public $state_id;
75
    public $state_code;
76
    public $state;
77
    /**
78
     * Id of region
79
     * @var int
80
     */
81
    public $region_code;
82
    public $region;
83
    /**
84
     * State code
85
     * @var string
86
     * @deprecated Use state_code instead
87
     * @see $state_code
88
     */
89
    public $departement_code;
90
    /**
91
     * @var string
92
     * @deprecated Use state instead
93
     * @see $state
94
     */
95
    public $departement;
96
    /**
97
     * @var string
98
     * @deprecated Use country instead
99
     * @see $country
100
     */
101
    public $pays;
102
    /**
103
     * Phone number
104
     * @var string
105
     */
106
    public $phone;
107
    /**
108
     * Fax number
109
     * @var string
110
     */
111
    public $fax;
112
    /**
113
     * Email
114
     * @var string
115
     */
116
    public $email;
117
    /**
118
     * Skype username
119
     * @var string
120
     */
121
    public $skype;
122
    /**
123
     * Twitter username
124
     * @var string
125
     */
126
    public $twitter;
127
    /**
128
     * Facebook username
129
     * @var string
130
     */
131
    public $facebook;
132
    /**
133
     * Webpage
134
     * @var string
135
     */
136
    public $url;
137
    /**
138
     * Barcode value
139
     * @var string
140
     */
141
    public $barcode;
142
    /**
143
     * Professional ID 1 (Ex: Siren in France)
144
     * @var string
145
     */
146
    public $idprof1;
147
    //! barcode
148
    /**
149
     * Professional ID 2 (Ex: Siret in France)
150
     * @var string
151
     */
152
    public $idprof2;
153
154
    // 6 professional id (usage depends on country)
155
    /**
156
     * Professional ID 3 (Ex: Ape in France)
157
     * @var string
158
     */
159
    public $idprof3;
160
    /**
161
     * Professional ID 4 (Ex: RCS in France)
162
     * @var string
163
     */
164
    public $idprof4;
165
    /**
166
     * Professional ID 5
167
     * @var string
168
     */
169
    public $idprof5;
170
    /**
171
     * Professional ID 6
172
     * @var string
173
     */
174
    public $idprof6;
175
    public $prefix_comm;
176
    public $tva_assuj = 1;
177
    /**
178
     * Intracommunitary VAT ID
179
     * @var string
180
     */
181
    public $tva_intra;
182
    public $localtax1_assuj;
183
    public $localtax1_value;
184
    // Local taxes
185
    public $localtax2_assuj;
186
    public $localtax2_value;
187
    public $managers;
188
    public $capital;
189
    public $typent_id = 0;
190
    public $typent_code;
191
    public $effectif;
192
    public $effectif_id = 0;
193
    public $forme_juridique_code;
194
    public $forme_juridique = 0;
195
    public $remise_percent;
196
    public $remise_supplier_percent;
197
    public $mode_reglement_supplier_id;
198
    public $cond_reglement_supplier_id;
199
    /**
200
     * @var int ID
201
     */
202
    public $fk_prospectlevel;
203
    public $name_bis;
204
    /**
205
     * Date of last update
206
     * @var string
207
     */
208
    public $date_modification;
209
    /**
210
     * User that made last update
211
     * @var string
212
     */
213
    public $user_modification;
214
215
    //Log data
216
    /**
217
     * Date of creation
218
     * @var string
219
     */
220
    public $date_creation;
221
    /**
222
     * User that created the thirdparty
0 ignored issues
show
Bug introduced by
The type Alixar\Models\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
223
     * @var User
224
     */
225
    public $user_creation;
226
    public $specimen;
227
    /**
228
     * 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
229
     * @var int
230
     */
231
    public $client = 0;
232
    /**
233
     * 0=no prospect, 1=prospect
234
     * @var int
235
     */
236
    public $prospect = 0;
237
    /**
238
     * 0=no supplier, 1=supplier
239
     * @var int
240
     */
241
    public $fournisseur;
242
    /**
243
     * Client code. E.g: CU2014-003
244
     * @var string
245
     */
246
    public $code_client;
247
    /**
248
     * Supplier code. E.g: SU2014-003
249
     * @var string
250
     */
251
    public $code_fournisseur;
252
    /**
253
     * Accounting code for client
254
     * @var string
255
     */
256
    public $code_compta;
257
    /**
258
     * Accounting code for client
259
     * @var string
260
     */
261
    public $code_compta_client;
262
    /**
263
     * Accounting code for suppliers
264
     * @var string
265
     */
266
    public $code_compta_fournisseur;
267
    /**
268
     * @var string
269
     * @deprecated Note is split in public and private notes
270
     * @see $note_public, $note_private
271
     */
272
    public $note;
273
    /**
274
     * Private note
275
     * @var string
276
     */
277
    public $note_private;
278
    /**
279
     * Public note
280
     * @var string
281
     */
282
    public $note_public;
283
    public $stcomm_id;
284
    public $statut_commercial;
285
    //! code statut prospect
286
    /**
287
     * Assigned price level
288
     * @var int
289
     */
290
    public $price_level;
291
    public $outstanding_limit;
292
    /**
293
     * Min order amounts
294
     */
295
    public $order_min_amount;
296
    public $supplier_order_min_amount;
297
    /**
298
     * Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
299
     * @var int
300
     */
301
    public $commercial_id;
302
    /**
303
     * Id of parent thirdparty (if one)
304
     * @var int
305
     */
306
    public $parent;
307
    /**
308
     * Default language code of thirdparty (en_US, ...)
309
     * @var string
310
     */
311
    public $default_lang;
312
    /**
313
     * @var string Ref
314
     */
315
    public $ref;
316
    public $ref_int;
317
    /**
318
     * External user reference.
319
     * This is to allow external systems to store their id and make self-developed synchronizing functions easier to
320
     * build.
321
     * @var string
322
     */
323
    public $ref_ext;
324
    /**
325
     * Import key.
326
     * Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
327
     * to an import process
328
     * @var string
329
     */
330
    public $import_key;
331
    /**
332
     * Supplier WebServices URL
333
     * @var string
334
     */
335
    public $webservices_url;
336
    /**
337
     * Supplier WebServices Key
338
     * @var string
339
     */
340
    public $webservices_key;
341
    public $logo;
342
    public $logo_small;
343
    public $logo_mini;
344
    public $array_options;
345
    /**
346
     * @var int ID
347
     */
348
    public $fk_incoterms;
349
    public $location_incoterms;
350
    // Incoterms
351
    public $libelle_incoterms;
352
    /**
353
     * @var int ID
354
     */
355
    public $fk_multicurrency;
356
    public $multicurrency_code;  //Used into tooltip
357
    // Multicurrency
358
    protected $childtables = array("supplier_proposal" => 'SupplierProposal', "propal" => 'Proposal', "commande" => 'Order', "facture" => 'Invoice', "facture_rec" => 'RecurringInvoiceTemplate', "contrat" => 'Contract', "fichinter" => 'Fichinter', "facture_fourn" => 'SupplierInvoice', "commande_fournisseur" => 'SupplierOrder', "projet" => 'Project', "expedition" => 'Shipment', "prelevement_lignes" => 'DirectDebitRecord');
359
    protected $childtablesoncascade = array("societe_prices", "societe_log", "societe_address", "product_fournisseur_price", "product_customer_price_log", "product_customer_price", "socpeople", "adherent", "societe_rib", "societe_remise", "societe_remise_except", "societe_commerciaux", "categorie", "notify", "notify_def", "actioncomm");
360
361
    // END MODULEBUILDER PROPERTIES
362
363
    /**
364
     *    Constructor
365
     *
366
     * @param DoliDB $db Database handler
0 ignored issues
show
Bug introduced by
The type Alixar\Models\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
367
     */
368
    public function __construct($db)
369
    {
370
        $this->db = $db;
371
372
        $this->client = 0;
373
        $this->prospect = 0;
374
        $this->fournisseur = 0;
375
        $this->typent_id = 0;
376
        $this->effectif_id = 0;
377
        $this->forme_juridique_code = 0;
378
        $this->tva_assuj = 1;
379
        $this->status = 1;
380
    }
381
382
    /**
383
     * Function used to replace a thirdparty id with another one.
384
     * It must be used within a transaction to avoid trouble
385
     *
386
     * @param DoliDB $db Database handler
387
     * @param int $origin_id Old thirdparty id (will be removed)
388
     * @param int $dest_id New thirdparty id
389
     * @return    bool                True if success, False if error
390
     */
391
    public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
392
    {
393
        if ($origin_id == $dest_id) {
394
            dol_syslog('Error: Try to merge a thirdparty into itself');
395
            return false;
396
        }
397
398
        /**
399
         * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some to avoid duplicate.
400
         * Because this function is meant to be executed within a transaction, we won't take care of begin/commit.
401
         */
402
        $sql = 'SELECT rowid FROM ' . MAIN_DB_PREFIX . 'societe_commerciaux ';
403
        $sql .= ' WHERE fk_soc = ' . (int)$dest_id . ' AND fk_user IN ( ';
404
        $sql .= ' SELECT fk_user ';
405
        $sql .= ' FROM ' . MAIN_DB_PREFIX . 'societe_commerciaux ';
406
        $sql .= ' WHERE fk_soc = ' . (int)$origin_id . ') ';
407
408
        $query = $db->query($sql);
409
410
        while ($result = $db->fetch_object($query)) {
411
            $db->query('DELETE FROM ' . MAIN_DB_PREFIX . 'societe_commerciaux WHERE rowid = ' . $result->rowid);
412
        }
413
414
        /**
415
         * llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
416
         * Do not include llx_societe because it will be replaced later
417
         */
418
        $tables = array(
419
            'societe_address',
420
            'societe_commerciaux',
421
            'societe_log',
422
            'societe_prices',
423
            'societe_remise',
424
            'societe_remise_except',
425
            'societe_rib'
426
        );
427
428
        return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\CommonObject was not found. Did you mean CommonObject? If so, make sure to prefix the type with \.
Loading history...
429
    }
430
431
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
432
433
    /**
434
     * Create a contact/address from thirdparty
435
     *
436
     * @param User $user Object user
437
     * @return    int                    <0 if KO, >0 if OK
438
     */
439
    function create_individual(User $user)
440
    {
441
        // phpcs:enable
442
        require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
443
        $contact = new Contact($this->db);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Contact was not found. Did you mean Contact? If so, make sure to prefix the type with \.
Loading history...
444
445
        $contact->name = $this->name_bis;
446
        $contact->firstname = $this->firstname;
447
        $contact->civility_id = $this->civility_id;
448
        $contact->socid = $this->id; // fk_soc
449
        $contact->statut = 1;
450
        $contact->priv = 0;
451
        $contact->country_id = $this->country_id;
452
        $contact->state_id = $this->state_id;
453
        $contact->address = $this->address;
454
        $contact->email = $this->email;
455
        $contact->zip = $this->zip;
456
        $contact->town = $this->town;
457
        $contact->phone_pro = $this->phone;
458
459
        $result = $contact->create($user);
460
        if ($result < 0) {
461
            $this->error = $contact->error;
462
            $this->errors = $contact->errors;
463
            dol_syslog(get_class($this) . "::create_individual ERROR:" . $this->error, LOG_ERR);
464
        }
465
466
        return $result;
467
    }
468
469
    /**
470
     *    Load a third party from database into memory
471
     *
472
     * @param int $rowid Id of third party to load
473
     * @param string $ref Reference of third party, name (Warning, this can return several records)
474
     * @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr)
475
     * @param string $ref_int Internal reference of third party (not used by dolibarr)
476
     * @param string $idprof1 Prof id 1 of third party (Warning, this can return several records)
477
     * @param string $idprof2 Prof id 2 of third party (Warning, this can return several records)
478
     * @param string $idprof3 Prof id 3 of third party (Warning, this can return several records)
479
     * @param string $idprof4 Prof id 4 of third party (Warning, this can return several records)
480
     * @param string $idprof5 Prof id 5 of third party (Warning, this can return several records)
481
     * @param string $idprof6 Prof id 6 of third party (Warning, this can return several records)
482
     * @param string $email Email of third party (Warning, this can return several records)
483
     * @param string $ref_alias Name_alias of third party (Warning, this can return several records)
484
     * @return   int                        >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
485
     */
486
    function fetch($rowid, $ref = '', $ref_ext = '', $ref_int = '', $idprof1 = '', $idprof2 = '', $idprof3 = '', $idprof4 = '', $idprof5 = '', $idprof6 = '', $email = '', $ref_alias = '')
487
    {
488
        global $langs;
489
        global $conf;
490
491
        if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6) && empty($email))
492
            return -1;
493
494
        $sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
495
        $sql .= ', s.status';
496
        $sql .= ', s.price_level';
497
        $sql .= ', s.tms as date_modification, s.fk_user_creat, s.fk_user_modif';
498
        $sql .= ', s.phone, s.fax, s.email, s.skype, s.twitter, s.facebook, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
499
        $sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
500
        $sql .= ', s.capital, s.tva_intra';
501
        $sql .= ', s.fk_typent as typent_id';
502
        $sql .= ', s.fk_effectif as effectif_id';
503
        $sql .= ', s.fk_forme_juridique as forme_juridique_code';
504
        $sql .= ', s.webservices_url, s.webservices_key';
505
        $sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
506
        $sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.remise_supplier, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
507
        $sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
508
        $sql .= ', s.fk_shipping_method';
509
        $sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
510
        $sql .= ', s.order_min_amount, s.supplier_order_min_amount';
511
        $sql .= ', s.fk_multicurrency, s.multicurrency_code';
512
        $sql .= ', fj.libelle as forme_juridique';
513
        $sql .= ', e.libelle as effectif';
514
        $sql .= ', c.code as country_code, c.label as country';
515
        $sql .= ', d.code_departement as state_code, d.nom as state';
516
        $sql .= ', st.libelle as stcomm';
517
        $sql .= ', te.code as typent_code';
518
        $sql .= ', i.libelle as libelle_incoterms';
519
        $sql .= ' FROM ' . MAIN_DB_PREFIX . 'societe as s';
520
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_effectif as e ON s.fk_effectif = e.id';
521
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_country as c ON s.fk_pays = c.rowid';
522
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_stcomm as st ON s.fk_stcomm = st.id';
523
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
524
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_departements as d ON s.fk_departement = d.rowid';
525
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_typent as te ON s.fk_typent = te.id';
526
        $sql .= ' LEFT JOIN ' . MAIN_DB_PREFIX . 'c_incoterms as i ON s.fk_incoterms = i.rowid';
527
528
        $sql .= ' WHERE s.entity IN (' . getEntity($this->element) . ')';
529
        if ($rowid)
530
            $sql .= ' AND s.rowid = ' . $rowid;
531
        if ($ref)
532
            $sql .= " AND s.nom = '" . $this->db->escape($ref) . "'";
533
        if ($ref_alias)
534
            $sql .= " AND s.nom_alias = '" . $this->db->escape($ref_alias) . "'";
535
        if ($ref_ext)
536
            $sql .= " AND s.ref_ext = '" . $this->db->escape($ref_ext) . "'";
537
        if ($ref_int)
538
            $sql .= " AND s.ref_int = '" . $this->db->escape($ref_int) . "'";
539
        if ($idprof1)
540
            $sql .= " AND s.siren = '" . $this->db->escape($idprof1) . "'";
541
        if ($idprof2)
542
            $sql .= " AND s.siret = '" . $this->db->escape($idprof2) . "'";
543
        if ($idprof3)
544
            $sql .= " AND s.ape = '" . $this->db->escape($idprof3) . "'";
545
        if ($idprof4)
546
            $sql .= " AND s.idprof4 = '" . $this->db->escape($idprof4) . "'";
547
        if ($idprof5)
548
            $sql .= " AND s.idprof5 = '" . $this->db->escape($idprof5) . "'";
549
        if ($idprof6)
550
            $sql .= " AND s.idprof6 = '" . $this->db->escape($idprof6) . "'";
551
        if ($email)
552
            $sql .= " AND s.email = '" . $this->db->escape($email) . "'";
553
554
        $resql = $this->db->query($sql);
555
        if ($resql) {
556
            $num = $this->db->num_rows($resql);
557
            if ($num > 1) {
558
                $this->error = 'Fetch found several records. Rename one of tirdparties to avoid duplicate.';
559
                dol_syslog($this->error, LOG_ERR);
560
                $result = -2;
561
            } elseif ($num) {   // $num = 1
562
                $obj = $this->db->fetch_object($resql);
563
564
                $this->id = $obj->rowid;
565
                $this->entity = $obj->entity;
566
                $this->canvas = $obj->canvas;
567
568
                $this->ref = $obj->rowid;
569
                $this->name = $obj->name;
570
                $this->nom = $obj->name;  // deprecated
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

570
                /** @scrutinizer ignore-deprecated */ $this->nom = $obj->name;  // deprecated

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
571
                $this->name_alias = $obj->name_alias;
572
                $this->ref_ext = $obj->ref_ext;
573
                $this->ref_int = $obj->ref_int;
574
575
                $this->date_creation = $this->db->jdate($obj->date_creation);
576
                $this->date_modification = $this->db->jdate($obj->date_modification);
577
                $this->user_creation = $obj->fk_user_creat;
578
                $this->user_modification = $obj->fk_user_modif;
579
580
                $this->address = $obj->address;
581
                $this->zip = $obj->zip;
582
                $this->town = $obj->town;
583
584
                $this->country_id = $obj->country_id;
585
                $this->country_code = $obj->country_id ? $obj->country_code : '';
586
                $this->country = $obj->country_id ? ($langs->trans('Country' . $obj->country_code) != 'Country' . $obj->country_code ? $langs->transnoentities('Country' . $obj->country_code) : $obj->country) : '';
587
588
                $this->state_id = $obj->fk_departement;
589
                $this->state_code = $obj->state_code;
590
                $this->state = ($obj->state != '-' ? $obj->state : '');
591
592
                $transcode = $langs->trans('StatusProspect' . $obj->fk_stcomm);
593
                $libelle = ($transcode != 'StatusProspect' . $obj->fk_stcomm ? $transcode : $obj->stcomm);
594
                $this->stcomm_id = $obj->fk_stcomm;     // id statut commercial
595
                $this->statut_commercial = $libelle;    // libelle statut commercial
596
597
                $this->email = $obj->email;
598
                $this->skype = $obj->skype;
599
                $this->twitter = $obj->twitter;
600
                $this->facebook = $obj->facebook;
601
                $this->url = $obj->url;
602
                $this->phone = $obj->phone;
603
                $this->fax = $obj->fax;
604
605
                $this->parent = $obj->parent;
606
607
                $this->idprof1 = $obj->idprof1;
608
                $this->idprof2 = $obj->idprof2;
609
                $this->idprof3 = $obj->idprof3;
610
                $this->idprof4 = $obj->idprof4;
611
                $this->idprof5 = $obj->idprof5;
612
                $this->idprof6 = $obj->idprof6;
613
614
                $this->capital = $obj->capital;
615
616
                $this->code_client = $obj->code_client;
617
                $this->code_fournisseur = $obj->code_fournisseur;
618
619
                $this->code_compta = $obj->code_compta;
620
                $this->code_compta_fournisseur = $obj->code_compta_fournisseur;
621
622
                $this->barcode = $obj->barcode;
623
624
                $this->tva_assuj = $obj->tva_assuj;
625
                $this->tva_intra = $obj->tva_intra;
626
                $this->status = $obj->status;
627
628
                // Local Taxes
629
                $this->localtax1_assuj = $obj->localtax1_assuj;
630
                $this->localtax2_assuj = $obj->localtax2_assuj;
631
632
                $this->localtax1_value = $obj->localtax1_value;
633
                $this->localtax2_value = $obj->localtax2_value;
634
635
                $this->typent_id = $obj->typent_id;
636
                $this->typent_code = $obj->typent_code;
637
638
                $this->effectif_id = $obj->effectif_id;
639
                $this->effectif = $obj->effectif_id ? $obj->effectif : '';
640
641
                $this->forme_juridique_code = $obj->forme_juridique_code;
642
                $this->forme_juridique = $obj->forme_juridique_code ? $obj->forme_juridique : '';
643
644
                $this->fk_prospectlevel = $obj->fk_prospectlevel;
645
646
                $this->prefix_comm = $obj->prefix_comm;
647
648
                $this->remise_percent = $obj->remise_client;
649
                $this->remise_supplier_percent = $obj->remise_supplier;
650
                $this->mode_reglement_id = $obj->mode_reglement;
651
                $this->cond_reglement_id = $obj->cond_reglement;
652
                $this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
653
                $this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
654
                $this->shipping_method_id = ($obj->fk_shipping_method > 0) ? $obj->fk_shipping_method : null;
655
                $this->fk_account = $obj->fk_account;
656
657
                $this->client = $obj->client;
658
                $this->fournisseur = $obj->fournisseur;
659
660
                $this->note = $obj->note_private; // TODO Deprecated for backward comtability
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$note has been deprecated: Note is split in public and private notes ( Ignorable by Annotation )

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

660
                /** @scrutinizer ignore-deprecated */ $this->note = $obj->note_private; // TODO Deprecated for backward comtability

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
661
                $this->note_private = $obj->note_private;
662
                $this->note_public = $obj->note_public;
663
                $this->modelpdf = $obj->model_pdf;
664
                $this->default_lang = $obj->default_lang;
665
                $this->logo = $obj->logo;
666
667
                $this->webservices_url = $obj->webservices_url;
668
                $this->webservices_key = $obj->webservices_key;
669
670
                $this->outstanding_limit = $obj->outstanding_limit;
671
                $this->order_min_amount = $obj->order_min_amount;
672
                $this->supplier_order_min_amount = $obj->supplier_order_min_amount;
673
674
                // multiprix
675
                $this->price_level = $obj->price_level;
676
677
                $this->import_key = $obj->import_key;
678
679
                //Incoterms
680
                $this->fk_incoterms = $obj->fk_incoterms;
681
                $this->location_incoterms = $obj->location_incoterms;
682
                $this->libelle_incoterms = $obj->libelle_incoterms;
683
684
                // multicurrency
685
                $this->fk_multicurrency = $obj->fk_multicurrency;
686
                $this->multicurrency_code = $obj->multicurrency_code;
687
688
                $result = 1;
689
690
                // fetch optionals attributes and labels
691
                $this->fetch_optionals();
692
            } else {
693
                $result = 0;
694
            }
695
696
            $this->db->free($resql);
697
        } else {
698
            $this->error = $this->db->lasterror();
699
            $result = -3;
700
        }
701
702
        // Use first price level if level not defined for third party
703
        if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level))
704
            $this->price_level = 1;
705
706
        return $result;
707
    }
708
709
    /**
710
     *    Delete a third party from database and all its dependencies (contacts, rib...)
711
     *
712
     * @param int $id Id of third party to delete
713
     * @param User $fuser User who ask to delete thirparty
714
     * @param int $call_trigger 0=No, 1=yes
715
     * @return    int                        <0 if KO, 0 if nothing done, >0 if OK
716
     */
717
    function delete($id, User $fuser = null, $call_trigger = 1)
718
    {
719
        global $langs, $conf, $user;
720
721
        if (empty($fuser))
722
            $fuser = $user;
723
724
        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
725
726
        $entity = isset($this->entity) ? $this->entity : $conf->entity;
727
728
        dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
729
        $error = 0;
730
731
        // Test if child exists
732
        $objectisused = $this->isObjectUsed($id);
733
        if (empty($objectisused)) {
734
            $this->db->begin();
735
736
            // User is mandatory for trigger call
737
            if (!$error && $call_trigger) {
738
                // Call trigger
739
                $result = $this->call_trigger('COMPANY_DELETE', $fuser);
740
                if ($result < 0)
741
                    $error++;
742
                // End call triggers
743
            }
744
745
            if (!$error) {
746
                require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
747
                $static_cat = new Categorie($this->db);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Categorie was not found. Did you mean Categorie? If so, make sure to prefix the type with \.
Loading history...
748
                $toute_categs = array();
749
750
                // Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
751
                if ($this->client || $this->prospect) {
752
                    $toute_categs['customer'] = $static_cat->containing($this->id, Categorie::TYPE_CUSTOMER);
753
                }
754
                if ($this->fournisseur) {
755
                    $toute_categs['supplier'] = $static_cat->containing($this->id, Categorie::TYPE_SUPPLIER);
756
                }
757
758
                // Remove each "Categorie"
759
                foreach ($toute_categs as $type => $categs_type) {
760
                    foreach ($categs_type as $cat) {
761
                        $cat->del_type($this, $type);
762
                    }
763
                }
764
            }
765
766
            foreach ($this->childtablesoncascade as $tabletodelete) {
767
                if (!$error) {
768
                    $sql = "DELETE FROM " . MAIN_DB_PREFIX . $tabletodelete;
769
                    $sql .= " WHERE fk_soc = " . $id;
770
                    if (!$this->db->query($sql)) {
771
                        $error++;
772
                        $this->errors[] = $this->db->lasterror();
773
                    }
774
                }
775
            }
776
777
            // Removed extrafields
778
            if ((!$error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) { // For avoid conflicts if trigger used
779
                $result = $this->deleteExtraFields();
780
                if ($result < 0) {
781
                    $error++;
782
                    dol_syslog(get_class($this) . "::delete error -3 " . $this->error, LOG_ERR);
783
                }
784
            }
785
786
            // Remove links to subsidiaries companies
787
            if (!$error) {
788
                $sql = "UPDATE " . MAIN_DB_PREFIX . "societe";
789
                $sql .= " SET parent = NULL";
790
                $sql .= " WHERE parent = " . $id;
791
                if (!$this->db->query($sql)) {
792
                    $error++;
793
                    $this->errors[] = $this->db->lasterror();
794
                }
795
            }
796
797
            // Remove third party
798
            if (!$error) {
799
                $sql = "DELETE FROM " . MAIN_DB_PREFIX . "societe";
800
                $sql .= " WHERE rowid = " . $id;
801
                if (!$this->db->query($sql)) {
802
                    $error++;
803
                    $this->errors[] = $this->db->lasterror();
804
                }
805
            }
806
807
            if (!$error) {
808
                $this->db->commit();
809
810
                // Delete directory
811
                if (!empty($conf->societe->multidir_output[$entity])) {
812
                    $docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
813
                    if (dol_is_dir($docdir)) {
814
                        dol_delete_dir_recursive($docdir);
815
                    }
816
                }
817
818
                return 1;
819
            } else {
820
                dol_syslog($this->error, LOG_ERR);
821
                $this->db->rollback();
822
                return -1;
823
            }
824
        } else
825
            dol_syslog("Can't remove thirdparty with id " . $id . ". There is " . $objectisused . " childs", LOG_WARNING);
826
        return 0;
827
    }
828
829
    /**
830
     *  Define third party as a customer
831
     *
832
     * @return        int        <0 if KO, >0 if OK
833
     */
834
    function set_as_client()
835
    {
836
        // phpcs:enable
837
        if ($this->id) {
838
            $newclient = 1;
839
            if ($this->client == 2 || $this->client == 3)
840
                $newclient = 3; //If prospect, we keep prospect tag
841
            $sql = "UPDATE " . MAIN_DB_PREFIX . "societe";
842
            $sql .= " SET client = " . $newclient;
843
            $sql .= " WHERE rowid = " . $this->id;
844
845
            $resql = $this->db->query($sql);
846
            if ($resql) {
847
                $this->client = $newclient;
848
                return 1;
849
            } else
850
                return -1;
851
        }
852
        return 0;
853
    }
854
855
    /**
856
     *  Definit la societe comme un client
857
     *
858
     * @param float $remise Valeur en % de la remise
859
     * @param string $note Note/Motif de modification de la remise
860
     * @param User $user Utilisateur qui definie la remise
861
     * @return    int                    <0 if KO, >0 if OK
862
     */
863
    function set_remise_client($remise, $note, User $user)
864
    {
865
        // phpcs:enable
866
        global $conf, $langs;
867
868
        // Nettoyage parametres
869
        $note = trim($note);
870
        if (!$note) {
871
            $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("NoteReason"));
872
            return -2;
873
        }
874
875
        dol_syslog(get_class($this) . "::set_remise_client " . $remise . ", " . $note . ", " . $user->id);
876
877
        if ($this->id) {
878
            $this->db->begin();
879
880
            $now = dol_now();
881
882
            // Positionne remise courante
883
            $sql = "UPDATE " . MAIN_DB_PREFIX . "societe ";
884
            $sql .= " SET remise_client = '" . $this->db->escape($remise) . "'";
885
            $sql .= " WHERE rowid = " . $this->id;
886
            $resql = $this->db->query($sql);
887
            if (!$resql) {
888
                $this->db->rollback();
889
                $this->error = $this->db->error();
890
                return -1;
891
            }
892
893
            // Ecrit trace dans historique des remises
894
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_remise";
895
            $sql .= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
896
            $sql .= " VALUES (" . $conf->entity . ", '" . $this->db->idate($now) . "', " . $this->id . ", '" . $this->db->escape($remise) . "',";
897
            $sql .= " '" . $this->db->escape($note) . "',";
898
            $sql .= " " . $user->id;
899
            $sql .= ")";
900
901
            $resql = $this->db->query($sql);
902
            if (!$resql) {
903
                $this->db->rollback();
904
                $this->error = $this->db->lasterror();
905
                return -1;
906
            }
907
908
            $this->db->commit();
909
            return 1;
910
        }
911
    }
912
913
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
914
915
    /**
916
     *  Definit la societe comme un client
917
     *
918
     * @param float $remise Valeur en % de la remise
919
     * @param string $note Note/Motif de modification de la remise
920
     * @param User $user Utilisateur qui definie la remise
921
     * @return    int                    <0 if KO, >0 if OK
922
     */
923
    function set_remise_supplier($remise, $note, User $user)
924
    {
925
        // phpcs:enable
926
        global $conf, $langs;
927
928
        // Nettoyage parametres
929
        $note = trim($note);
930
        if (!$note) {
931
            $this->error = $langs->trans("ErrorFieldRequired", $langs->trans("NoteReason"));
932
            return -2;
933
        }
934
935
        dol_syslog(get_class($this) . "::set_remise_supplier " . $remise . ", " . $note . ", " . $user->id);
936
937
        if ($this->id) {
938
            $this->db->begin();
939
940
            $now = dol_now();
941
942
            // Positionne remise courante
943
            $sql = "UPDATE " . MAIN_DB_PREFIX . "societe ";
944
            $sql .= " SET remise_supplier = '" . $this->db->escape($remise) . "'";
945
            $sql .= " WHERE rowid = " . $this->id;
946
            $resql = $this->db->query($sql);
947
            if (!$resql) {
948
                $this->db->rollback();
949
                $this->error = $this->db->error();
950
                return -1;
951
            }
952
953
            // Ecrit trace dans historique des remises
954
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_remise_supplier";
955
            $sql .= " (entity, datec, fk_soc, remise_supplier, note, fk_user_author)";
956
            $sql .= " VALUES (" . $conf->entity . ", '" . $this->db->idate($now) . "', " . $this->id . ", '" . $this->db->escape($remise) . "',";
957
            $sql .= " '" . $this->db->escape($note) . "',";
958
            $sql .= " " . $user->id;
959
            $sql .= ")";
960
961
            $resql = $this->db->query($sql);
962
            if (!$resql) {
963
                $this->db->rollback();
964
                $this->error = $this->db->lasterror();
965
                return -1;
966
            }
967
968
            $this->db->commit();
969
            return 1;
970
        }
971
    }
972
973
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
974
975
    /**
976
     *        Add a discount for third party
977
     *
978
     * @param float $remise Amount of discount
979
     * @param User $user User adding discount
980
     * @param string $desc Reason of discount
981
     * @param float $tva_tx VAT rate
982
     * @param int $discount_type 0 => customer discount, 1 => supplier discount
983
     * @return    int                    <0 if KO, id of discount record if OK
984
     */
985
    function set_remise_except($remise, User $user, $desc, $tva_tx = 0, $discount_type = 0)
986
    {
987
        // phpcs:enable
988
        global $langs;
989
990
        // Clean parameters
991
        $remise = price2num($remise);
992
        $desc = trim($desc);
993
994
        // Check parameters
995
        if (!$remise > 0) {
996
            $this->error = $langs->trans("ErrorWrongValueForParameter", "1");
997
            return -1;
998
        }
999
        if (!$desc) {
1000
            $this->error = $langs->trans("ErrorWrongValueForParameter", "3");
1001
            return -2;
1002
        }
1003
1004
        if ($this->id) {
1005
            require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
1006
1007
            $discount = new DiscountAbsolute($this->db);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\DiscountAbsolute was not found. Did you mean DiscountAbsolute? If so, make sure to prefix the type with \.
Loading history...
1008
            $discount->fk_soc = $this->id;
1009
1010
            $discount->discount_type = $discount_type;
1011
1012
            $discount->amount_ht = $discount->multicurrency_amount_ht = price2num($remise, 'MT');
1013
            $discount->amount_tva = $discount->multicurrency_amount_tva = price2num($remise * $tva_tx / 100, 'MT');
1014
            $discount->amount_ttc = $discount->multicurrency_amount_ttc = price2num($discount->amount_ht + $discount->amount_tva, 'MT');
1015
1016
            $discount->tva_tx = price2num($tva_tx, 'MT');
1017
            $discount->description = $desc;
1018
1019
            $result = $discount->create($user);
1020
            if ($result > 0) {
1021
                return $result;
1022
            } else {
1023
                $this->error = $discount->error;
1024
                return -3;
1025
            }
1026
        } else
1027
            return 0;
1028
    }
1029
1030
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1031
1032
    /**
1033
     *  Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
1034
     *
1035
     * @param User $user Filtre sur un user auteur des remises
1036
     * @param string $filter Filtre autre
1037
     * @param integer $maxvalue Filter on max value for discount
1038
     * @param int $discount_type 0 => customer discount, 1 => supplier discount
1039
     * @return    int                    <0 if KO, Credit note amount otherwise
1040
     */
1041
    function getAvailableDiscounts($user = '', $filter = '', $maxvalue = 0, $discount_type = 0)
1042
    {
1043
        require_once DOL_DOCUMENT_ROOT . '/core/class/discount.class.php';
1044
1045
        $discountstatic = new DiscountAbsolute($this->db);
1046
        $result = $discountstatic->getAvailableDiscounts($this, $user, $filter, $maxvalue, $discount_type);
1047
        if ($result >= 0) {
1048
            return $result;
1049
        } else {
1050
            $this->error = $discountstatic->error;
1051
            return -1;
1052
        }
1053
    }
1054
1055
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1056
1057
    /**
1058
     * Set the price level
1059
     *
1060
     * @param int $price_level Level of price
1061
     * @param User $user Use making change
1062
     * @return    int                        <0 if KO, >0 if OK
1063
     */
1064
    function set_price_level($price_level, User $user)
1065
    {
1066
        // phpcs:enable
1067
        if ($this->id) {
1068
            $now = dol_now();
1069
1070
            $sql = "UPDATE " . MAIN_DB_PREFIX . "societe";
1071
            $sql .= " SET price_level = '" . $this->db->escape($price_level) . "'";
1072
            $sql .= " WHERE rowid = " . $this->id;
1073
1074
            if (!$this->db->query($sql)) {
1075
                dol_print_error($this->db);
1076
                return -1;
1077
            }
1078
1079
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_prices";
1080
            $sql .= " (datec, fk_soc, price_level, fk_user_author)";
1081
            $sql .= " VALUES ('" . $this->db->idate($now) . "', " . $this->id . ", '" . $this->db->escape($price_level) . "', " . $user->id . ")";
1082
1083
            if (!$this->db->query($sql)) {
1084
                dol_print_error($this->db);
1085
                return -1;
1086
            }
1087
            return 1;
1088
        }
1089
        return -1;
1090
    }
1091
1092
    /**
1093
     *        Return a link on thirdparty (with picto)
1094
     *
1095
     * @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
1096
     * @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project')
1097
     * @param int $maxlen Max length of name
1098
     * @param int $notooltip 1=Disable tooltip
1099
     * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1100
     * @return    string                              String with URL
1101
     */
1102
    function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $save_lastsearch_value = -1)
1103
    {
1104
        global $conf, $langs, $hookmanager;
1105
1106
        if (!empty($conf->dol_no_mouse_hover))
1107
            $notooltip = 1;   // Force disable tooltips
1108
1109
        $name = $this->name ? $this->name : $this->nom;
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

1109
        $name = $this->name ? $this->name : /** @scrutinizer ignore-deprecated */ $this->nom;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1110
1111
        if (!empty($conf->global->SOCIETE_ON_SEARCH_AND_LIST_GO_ON_CUSTOMER_OR_SUPPLIER_CARD)) {
1112
1113
            if (empty($option) && $this->client > 0)
1114
                $option = 'customer';
1115
            if (empty($option) && $this->fournisseur > 0)
1116
                $option = 'supplier';
1117
        }
1118
1119
1120
        if (!empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto))) {
1121
            $code = '';
1122
            if (($this->client) && (!empty($this->code_client)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 2
1123
                )
1124
            ) {
1125
                $code = $this->code_client . ' - ';
1126
            }
1127
1128
            if (($this->fournisseur) && (!empty($this->code_fournisseur)) && ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1 || $conf->global->SOCIETE_ADD_REF_IN_LIST == 3
1129
                )
1130
            ) {
1131
                $code .= $this->code_fournisseur . ' - ';
1132
            }
1133
1134
            if ($conf->global->SOCIETE_ADD_REF_IN_LIST == 1) {
1135
                $name = $code . ' ' . $name;
1136
            } else {
1137
                $name = $code;
1138
            }
1139
        }
1140
1141
        if (!empty($this->name_alias))
1142
            $name .= ' (' . $this->name_alias . ')';
1143
1144
        $result = '';
1145
        $label = '';
1146
        $linkstart = '';
1147
        $linkend = '';
1148
1149
        if (!empty($this->logo) && class_exists('Form')) {
1150
            $label .= '<div class="photointooltip">';
1151
            $label .= Form::showphoto('societe', $this, 0, 40, 0, 'photowithmargin', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip.
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Form was not found. Did you mean Form? If so, make sure to prefix the type with \.
Loading history...
1152
            $label .= '</div><div style="clear: both;"></div>';
1153
        }
1154
1155
        $label .= '<div class="centpercent">';
1156
1157
        if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier') {
1158
            $label .= '<u>' . $langs->trans("ShowCustomer") . '</u>';
1159
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/comm/card.php?socid=' . $this->id;
1160
            $linkstart = '<a href="' . BASE_URI . '?controller=comm&method=card&socid=' . $this->id;
0 ignored issues
show
Bug introduced by
The constant Alixar\Models\BASE_URI was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
1161
        } elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS)) {
1162
            $label .= '<u>' . $langs->trans("ShowProspect") . '</u>';
1163
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/comm/card.php?socid=' . $this->id;
1164
            $linkstart = '<a href="' . BASE_URI . '?controller=comm&method=card&socid=' . $this->id;
1165
        } elseif ($option == 'supplier') {
1166
            $label .= '<u>' . $langs->trans("ShowSupplier") . '</u>';
1167
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/fourn/card.php?socid=' . $this->id;
1168
            $linkstart = '<a href="' . BASE_URI . '?controller=fourn&method=card&socid=' . $this->id;
1169
        } elseif ($option == 'agenda') {
1170
            $label .= '<u>' . $langs->trans("ShowAgenda") . '</u>';
1171
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/societe/agenda.php?socid=' . $this->id;
1172
            $linkstart = '<a href="' . BASE_URI . '?controller=societe&method=agenda&socid=' . $this->id;
1173
        } elseif ($option == 'project') {
1174
            $label .= '<u>' . $langs->trans("ShowProject") . '</u>';
1175
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/societe/project.php?socid=' . $this->id;
1176
            $linkstart = '<a href="' . BASE_URI . '?controller=societe&method=project&socid=' . $this->id;
1177
        } elseif ($option == 'margin') {
1178
            $label .= '<u>' . $langs->trans("ShowMargin") . '</u>';
1179
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/margin/tabs/thirdpartyMargins.php?socid=' . $this->id . '&type=1';
1180
            $linkstart = '<a href="' . BASE_URI . '?controller=margin/tabs&method=thirdpartyMargins&socid=' . $this->id . '&type=1';
1181
        } elseif ($option == 'contact') {
1182
            $label .= '<u>' . $langs->trans("ShowContacts") . '</u>';
1183
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/societe/contact.php?socid=' . $this->id;
1184
            $linkstart = '<a href="' . BASE_URI . '?controller=societe&method=contact&socid=' . $this->id;
1185
        } elseif ($option == 'ban') {
1186
            $label .= '<u>' . $langs->trans("ShowBan") . '</u>';
1187
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/societe/paymentmodes.php?socid=' . $this->id;
1188
            $linkstart = '<a href="' . BASE_URI . '?controller=societe&method=paymentmodes&socid=' . $this->id;
1189
        }
1190
1191
        // By default
1192
        if (empty($linkstart)) {
1193
            $label .= '<u>' . $langs->trans("ShowCompany") . '</u>';
1194
            // $linkstart = '<a href="' . DOL_URL_ROOT . '/societe/card.php?socid=' . $this->id;
1195
            $linkstart = '<a href="' . BASE_URI . '?controller=societe&method=card&socid=' . $this->id;
1196
        }
1197
1198
        if (!empty($this->name)) {
1199
            $label .= '<br><b>' . $langs->trans('Name') . ':</b> ' . $this->name;
1200
            if (!empty($this->name_alias))
1201
                $label .= ' (' . $this->name_alias . ')';
1202
            $label .= '<br><b>' . $langs->trans('Email') . ':</b> ' . $this->email;
1203
        }
1204
        if (!empty($this->country_code))
1205
            $label .= '<br><b>' . $langs->trans('Country') . ':</b> ' . $this->country_code;
1206
        if (!empty($this->tva_intra) || (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP) && strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'vatnumber') !== false))
1207
            $label .= '<br><b>' . $langs->trans('VATIntra') . ':</b> ' . $this->tva_intra;
1208
        if (!empty($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP)) {
1209
            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid1') !== false)
1210
                $label .= '<br><b>' . $langs->trans('ProfId1' . $this->country_code) . ':</b> ' . $this->idprof1;
1211
            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid2') !== false)
1212
                $label .= '<br><b>' . $langs->trans('ProfId2' . $this->country_code) . ':</b> ' . $this->idprof2;
1213
            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid3') !== false)
1214
                $label .= '<br><b>' . $langs->trans('ProfId3' . $this->country_code) . ':</b> ' . $this->idprof3;
1215
            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid4') !== false)
1216
                $label .= '<br><b>' . $langs->trans('ProfId4' . $this->country_code) . ':</b> ' . $this->idprof4;
1217
            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid5') !== false)
1218
                $label .= '<br><b>' . $langs->trans('ProfId5' . $this->country_code) . ':</b> ' . $this->idprof5;
1219
            if (strpos($conf->global->SOCIETE_SHOW_FIELD_IN_TOOLTIP, 'profid6') !== false)
1220
                $label .= '<br><b>' . $langs->trans('ProfId6' . $this->country_code) . ':</b> ' . $this->idprof6;
1221
        }
1222
        if (!empty($this->code_client) && ($this->client == 1 || $this->client == 3))
1223
            $label .= '<br><b>' . $langs->trans('CustomerCode') . ':</b> ' . $this->code_client;
1224
        if (!empty($this->code_fournisseur) && $this->fournisseur)
1225
            $label .= '<br><b>' . $langs->trans('SupplierCode') . ':</b> ' . $this->code_fournisseur;
1226
        if (!empty($conf->accounting->enabled) && ($this->client == 1 || $this->client == 3))
1227
            $label .= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> ' . ($this->code_compta ? $this->code_compta : $this->code_compta_client);
1228
        if (!empty($conf->accounting->enabled) && $this->fournisseur)
1229
            $label .= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> ' . $this->code_compta_fournisseur;
1230
1231
        $label .= '</div>';
1232
1233
        // Add type of canvas
1234
        $linkstart .= (!empty($this->canvas) ? '&canvas=' . $this->canvas : '');
1235
        // Add param to save lastsearch_values or not
1236
        $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1237
        if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"]))
1238
            $add_save_lastsearch_values = 1;
1239
        if ($add_save_lastsearch_values)
1240
            $linkstart .= '&save_lastsearch_values=1';
1241
        $linkstart .= '"';
1242
1243
        $linkclose = '';
1244
        if (empty($notooltip)) {
1245
            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1246
                $label = $langs->trans("ShowCompany");
1247
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
1248
            }
1249
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
1250
            $linkclose .= ' class="classfortooltip refurl"';
1251
1252
            /*
1253
              $hookmanager->initHooks(array('thirdpartydao'));
1254
              $parameters=array('id'=>$this->id);
1255
              $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
1256
              if ($reshook > 0) $linkclose = $hookmanager->resPrint;
1257
             */
1258
        }
1259
        $linkstart .= $linkclose . '>';
1260
        $linkend = '</a>';
1261
1262
        global $user;
1263
        if (!$user->rights->societe->client->voir && $user->societe_id > 0 && $this->id != $user->societe_id) {
1264
            $linkstart = '';
1265
            $linkend = '';
1266
        }
1267
1268
        $result .= $linkstart;
1269
        if ($withpicto)
1270
            $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip valigntextbottom"'), 0, 0, $notooltip ? 0 : 1);
1271
        if ($withpicto != 2)
1272
            $result .= ($maxlen ? dol_trunc($name, $maxlen) : $name);
1273
        $result .= $linkend;
1274
1275
        global $action;
1276
        $hookmanager->initHooks(array('thirdpartydao'));
1277
        $parameters = array('id' => $this->id, 'getnomurl' => $result);
1278
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
1279
        if ($reshook > 0)
1280
            $result = $hookmanager->resPrint;
1281
        else
1282
            $result .= $hookmanager->resPrint;
1283
1284
        return $result;
1285
    }
1286
1287
    /**
1288
     *    Return label of status (activity, closed)
1289
     *
1290
     * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
1291
     * @return   string                Libelle
1292
     */
1293
    function getLibStatut($mode = 0)
1294
    {
1295
        return $this->LibStatut($this->status, $mode);
1296
    }
1297
1298
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1299
1300
    /**
1301
     *  Renvoi le libelle d'un statut donne
1302
     *
1303
     * @param int $statut Id statut
1304
     * @param int $mode 0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
1305
     * @return    string                Libelle du statut
1306
     */
1307
    function LibStatut($statut, $mode = 0)
1308
    {
1309
        // phpcs:enable
1310
        global $langs;
1311
        $langs->load('companies');
1312
1313
        if ($mode == 0) {
1314
            if ($statut == 0)
1315
                return $langs->trans("ActivityCeased");
1316
            elseif ($statut == 1)
1317
                return $langs->trans("InActivity");
1318
        } elseif ($mode == 1) {
1319
            if ($statut == 0)
1320
                return $langs->trans("ActivityCeased");
1321
            elseif ($statut == 1)
1322
                return $langs->trans("InActivity");
1323
        } elseif ($mode == 2) {
1324
            if ($statut == 0)
1325
                return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"') . ' ' . $langs->trans("ActivityCeased");
1326
            elseif ($statut == 1)
1327
                return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"') . ' ' . $langs->trans("InActivity");
1328
        } elseif ($mode == 3) {
1329
            if ($statut == 0)
1330
                return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
1331
            elseif ($statut == 1)
1332
                return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
1333
        } elseif ($mode == 4) {
1334
            if ($statut == 0)
1335
                return img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"') . ' ' . $langs->trans("ActivityCeased");
1336
            elseif ($statut == 1)
1337
                return img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"') . ' ' . $langs->trans("InActivity");
1338
        } elseif ($mode == 5) {
1339
            if ($statut == 0)
1340
                return '<span class="hideonsmartphone">' . $langs->trans("ActivityCeased") . '</span> ' . img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
1341
            elseif ($statut == 1)
1342
                return '<span class="hideonsmartphone">' . $langs->trans("InActivity") . '</span> ' . img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
1343
        } elseif ($mode == 6) {
1344
            if ($statut == 0)
1345
                return '<span class="hideonsmartphone">' . $langs->trans("ActivityCeased") . '</span> ' . img_picto($langs->trans("ActivityCeased"), 'statut5', 'class="pictostatus"');
1346
            elseif ($statut == 1)
1347
                return '<span class="hideonsmartphone">' . $langs->trans("InActivity") . '</span> ' . img_picto($langs->trans("InActivity"), 'statut4', 'class="pictostatus"');
1348
        }
1349
    }
1350
1351
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1352
1353
    /**
1354
     *    Return list of contacts emails existing for third party
1355
     *
1356
     * @param int $addthirdparty 1=Add also a record for thirdparty email
1357
     * @return     array                        Array of contacts emails
1358
     */
1359
    function thirdparty_and_contact_email_array($addthirdparty = 0)
1360
    {
1361
        // phpcs:enable
1362
        global $langs;
1363
1364
        $contact_emails = $this->contact_property_array('email', 1);
1365
        if ($this->email && $addthirdparty) {
1366
            if (empty($this->name))
1367
                $this->name = $this->nom;
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

1367
                $this->name = /** @scrutinizer ignore-deprecated */ $this->nom;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1368
            $contact_emails['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty") . ': ' . dol_trunc($this->name, 16) . " <" . $this->email . ">";
1369
        }
1370
        //var_dump($contact_emails)
1371
        return $contact_emails;
1372
    }
1373
1374
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1375
1376
    /**
1377
     *  Return list of contacts emails or mobile existing for third party
1378
     *
1379
     * @param string $mode 'email' or 'mobile'
1380
     * @param int $hidedisabled 1=Hide contact if disabled
1381
     * @return array                    Array of contacts emails or mobile. Example: array(id=>'Name <email>')
1382
     */
1383
    function contact_property_array($mode = 'email', $hidedisabled = 0)
1384
    {
1385
        // phpcs:enable
1386
        global $langs;
1387
1388
        $contact_property = array();
1389
1390
1391
        $sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
1392
        $sql .= " FROM " . MAIN_DB_PREFIX . "socpeople";
1393
        $sql .= " WHERE fk_soc = " . $this->id;
1394
1395
        $resql = $this->db->query($sql);
1396
        if ($resql) {
1397
            $nump = $this->db->num_rows($resql);
1398
            if ($nump) {
1399
                $sepa = "(";
1400
                $sepb = ")";
1401
                if ($mode == 'email') {
1402
                    //$sepa="&lt;"; $sepb="&gt;";
1403
                    $sepa = "<";
1404
                    $sepb = ">";
1405
                }
1406
                $i = 0;
1407
                while ($i < $nump) {
1408
                    $obj = $this->db->fetch_object($resql);
1409
                    if ($mode == 'email')
1410
                        $property = $obj->email;
1411
                    else if ($mode == 'mobile')
1412
                        $property = $obj->phone_mobile;
1413
                    else
1414
                        $property = $obj->$mode;
1415
1416
                    // Show all contact. If hidedisabled is 1, showonly contacts with status = 1
1417
                    if ($obj->statut == 1 || empty($hidedisabled)) {
1418
                        if (empty($property)) {
1419
                            if ($mode == 'email')
1420
                                $property = $langs->transnoentitiesnoconv("NoEMail");
1421
                            else if ($mode == 'mobile')
1422
                                $property = $langs->transnoentitiesnoconv("NoMobilePhone");
1423
                        }
1424
1425
                        if (!empty($obj->poste)) {
1426
                            $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)) . ($obj->poste ? " - " . $obj->poste : "") . (($mode != 'poste' && $property) ? " " . $sepa . $property . $sepb : '');
1427
                        } else {
1428
                            $contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname, $obj->lastname)) . (($mode != 'poste' && $property) ? " " . $sepa . $property . $sepb : '');
1429
                        }
1430
                    }
1431
                    $i++;
1432
                }
1433
            }
1434
        } else {
1435
            dol_print_error($this->db);
1436
        }
1437
        return $contact_property;
1438
    }
1439
1440
    /**
1441
     *    Return list of contacts mobile phone existing for third party
1442
     *
1443
     * @return     array       Array of contacts emails
1444
     */
1445
    function thirdparty_and_contact_phone_array()
1446
    {
1447
        // phpcs:enable
1448
        global $langs;
1449
1450
        $contact_phone = $this->contact_property_array('mobile');
1451
1452
        if (!empty($this->phone)) { // If a phone of thirdparty is defined, we add it ot mobile of contacts
1453
            if (empty($this->name))
1454
                $this->name = $this->nom;
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

1454
                $this->name = /** @scrutinizer ignore-deprecated */ $this->nom;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
1455
            // TODO: Tester si tel non deja present dans tableau contact
1456
            $contact_phone['thirdparty'] = $langs->transnoentitiesnoconv("ThirdParty") . ': ' . dol_trunc($this->name, 16) . " <" . $this->phone . ">";
1457
        }
1458
        return $contact_phone;
1459
    }
1460
1461
    /**
1462
     *    Renvoie la liste des contacts de cette societe
1463
     *
1464
     * @return     array      tableau des contacts
1465
     */
1466
    function contact_array()
1467
    {
1468
        // phpcs:enable
1469
        $contacts = array();
1470
1471
        $sql = "SELECT rowid, lastname, firstname FROM " . MAIN_DB_PREFIX . "socpeople WHERE fk_soc = " . $this->id;
1472
        $resql = $this->db->query($sql);
1473
        if ($resql) {
1474
            $nump = $this->db->num_rows($resql);
1475
            if ($nump) {
1476
                $i = 0;
1477
                while ($i < $nump) {
1478
                    $obj = $this->db->fetch_object($resql);
1479
                    $contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname, $obj->lastname);
1480
                    $i++;
1481
                }
1482
            }
1483
        } else {
1484
            dol_print_error($this->db);
1485
        }
1486
        return $contacts;
1487
    }
1488
1489
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1490
1491
    /**
1492
     *    Renvoie la liste des contacts de cette societe
1493
     *
1494
     * @return    array    $contacts    tableau des contacts
1495
     */
1496
    function contact_array_objects()
1497
    {
1498
        // phpcs:enable
1499
        require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
1500
        $contacts = array();
1501
1502
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "socpeople WHERE fk_soc = " . $this->id;
1503
        $resql = $this->db->query($sql);
1504
        if ($resql) {
1505
            $nump = $this->db->num_rows($resql);
1506
            if ($nump) {
1507
                $i = 0;
1508
                while ($i < $nump) {
1509
                    $obj = $this->db->fetch_object($resql);
1510
                    $contact = new Contact($this->db);
1511
                    $contact->fetch($obj->rowid);
1512
                    $contacts[] = $contact;
1513
                    $i++;
1514
                }
1515
            }
1516
        } else {
1517
            dol_print_error($this->db);
1518
        }
1519
        return $contacts;
1520
    }
1521
1522
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1523
1524
    /**
1525
     *  Return property of contact from its id
1526
     *
1527
     * @param int $rowid id of contact
1528
     * @param string $mode 'email' or 'mobile'
1529
     * @return string            Email of contact with format: "Full name <email>"
1530
     */
1531
    function contact_get_property($rowid, $mode)
1532
    {
1533
        // phpcs:enable
1534
        $contact_property = '';
1535
1536
        if (empty($rowid))
1537
            return '';
1538
1539
        $sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
1540
        $sql .= " FROM " . MAIN_DB_PREFIX . "socpeople";
1541
        $sql .= " WHERE rowid = '" . $rowid . "'";
1542
1543
        $resql = $this->db->query($sql);
1544
        if ($resql) {
1545
            $nump = $this->db->num_rows($resql);
1546
1547
            if ($nump) {
1548
                $obj = $this->db->fetch_object($resql);
1549
1550
                if ($mode == 'email')
1551
                    $contact_property = dol_string_nospecial(dolGetFirstLastname($obj->firstname, $obj->lastname), ' ', array(",")) . " <" . $obj->email . ">";
1552
                else if ($mode == 'mobile')
1553
                    $contact_property = $obj->phone_mobile;
1554
            }
1555
            return $contact_property;
1556
        } else {
1557
            dol_print_error($this->db);
1558
        }
1559
    }
1560
1561
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1562
1563
    /**
1564
     *  Return bank number property of thirdparty (label or rum)
1565
     *
1566
     * @param string $mode 'label' or 'rum' or 'format'
1567
     * @return    string            Bank number
1568
     */
1569
    function display_rib($mode = 'label')
1570
    {
1571
        // phpcs:enable
1572
        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
1573
1574
        $bac = new CompanyBankAccount($this->db);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\CompanyBankAccount was not found. Did you mean CompanyBankAccount? If so, make sure to prefix the type with \.
Loading history...
1575
        $bac->fetch(0, $this->id);
1576
1577
        if ($mode == 'label') {
1578
            return $bac->getRibLabel(true);
1579
        } elseif ($mode == 'rum') {
1580
            if (empty($bac->rum)) {
1581
                require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
1582
                $prelevement = new BonPrelevement($this->db);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\BonPrelevement was not found. Did you mean BonPrelevement? If so, make sure to prefix the type with \.
Loading history...
1583
                $bac->fetch_thirdparty();
1584
                $bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
1585
            }
1586
            return $bac->rum;
1587
        } elseif ($mode == 'format') {
1588
            return $bac->frstrecur;
1589
        }
1590
1591
        return 'BadParameterToFunctionDisplayRib';
1592
    }
1593
1594
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1595
1596
    /**
1597
     * Return Array of RIB
1598
     *
1599
     * @return     array|int        0 if KO, Array of CompanyBanckAccount if OK
1600
     */
1601
    function get_all_rib()
1602
    {
1603
        // phpcs:enable
1604
        require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
1605
        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "societe_rib WHERE type='ban' AND fk_soc = " . $this->id;
1606
        $result = $this->db->query($sql);
1607
        if (!$result) {
1608
            $this->error++;
1609
            $this->errors[] = $this->db->lasterror;
1610
            return 0;
1611
        } else {
1612
            $num_rows = $this->db->num_rows($result);
1613
            $rib_array = array();
1614
            if ($num_rows) {
1615
                while ($obj = $this->db->fetch_object($result)) {
1616
                    $rib = new CompanyBankAccount($this->db);
1617
                    $rib->fetch($obj->rowid);
1618
                    $rib_array[] = $rib;
1619
                }
1620
            }
1621
            return $rib_array;
1622
        }
1623
    }
1624
1625
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1626
1627
    /**
1628
     *    Verifie si un code client est modifiable en fonction des parametres
1629
     *    du module de controle des codes.
1630
     *
1631
     * @return     int        0=No, 1=Yes
1632
     */
1633
    function codeclient_modifiable()
1634
    {
1635
        // phpcs:enable
1636
        global $conf;
1637
        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
1638
            $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
1639
1640
            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
1641
            foreach ($dirsociete as $dirroot) {
1642
                $res = dol_include_once($dirroot . $module . '.php');
1643
                if ($res)
1644
                    break;
1645
            }
1646
1647
            $mod = new $module();
1648
1649
            dol_syslog(get_class($this) . "::codeclient_modifiable code_client=" . $this->code_client . " module=" . $module);
1650
            if ($mod->code_modifiable_null && !$this->code_client)
1651
                return 1;
1652
            if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0)
1653
                return 1;
1654
            if ($mod->code_modifiable)
1655
                return 1; // A mettre en dernier
1656
            return 0;
1657
        } else {
1658
            return 0;
1659
        }
1660
    }
1661
1662
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1663
1664
    /**
1665
     *  Check customer code
1666
     *
1667
     * @return     int                0 if OK
1668
     *                                -1 ErrorBadCustomerCodeSyntax
1669
     *                                -2 ErrorCustomerCodeRequired
1670
     *                                -3 ErrorCustomerCodeAlreadyUsed
1671
     *                                -4 ErrorPrefixRequired
1672
     */
1673
    function check_codeclient()
1674
    {
1675
        // phpcs:enable
1676
        global $conf;
1677
        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
1678
            $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
1679
1680
            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
1681
            foreach ($dirsociete as $dirroot) {
1682
                $res = dol_include_once($dirroot . $module . '.php');
1683
                if ($res)
1684
                    break;
1685
            }
1686
1687
            $mod = new $module();
1688
1689
            dol_syslog(get_class($this) . "::check_codeclient code_client=" . $this->code_client . " module=" . $module);
1690
            $result = $mod->verif($this->db, $this->code_client, $this, 0);
1691
            return $result;
1692
        } else {
1693
            return 0;
1694
        }
1695
    }
1696
1697
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1698
1699
    /**
1700
     *    Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
1701
     *
1702
     * @return     int        0=No, 1=Yes
1703
     */
1704
    function codefournisseur_modifiable()
1705
    {
1706
        // phpcs:enable
1707
        global $conf;
1708
        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
1709
            $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
1710
1711
            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
1712
            foreach ($dirsociete as $dirroot) {
1713
                $res = dol_include_once($dirroot . $module . '.php');
1714
                if ($res)
1715
                    break;
1716
            }
1717
1718
            $mod = new $module();
1719
1720
            dol_syslog(get_class($this) . "::codefournisseur_modifiable code_founisseur=" . $this->code_fournisseur . " module=" . $module);
1721
            if ($mod->code_modifiable_null && !$this->code_fournisseur)
1722
                return 1;
1723
            if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0)
1724
                return 1;
1725
            if ($mod->code_modifiable)
1726
                return 1; // A mettre en dernier
1727
            return 0;
1728
        } else {
1729
            return 0;
1730
        }
1731
    }
1732
1733
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1734
1735
    /**
1736
     *    Check supplier code
1737
     *
1738
     * @return     int        0 if OK
1739
     *                            -1 ErrorBadCustomerCodeSyntax
1740
     *                            -2 ErrorCustomerCodeRequired
1741
     *                            -3 ErrorCustomerCodeAlreadyUsed
1742
     *                            -4 ErrorPrefixRequired
1743
     */
1744
    function check_codefournisseur()
1745
    {
1746
        // phpcs:enable
1747
        global $conf;
1748
        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
1749
            $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
1750
1751
            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
1752
            foreach ($dirsociete as $dirroot) {
1753
                $res = dol_include_once($dirroot . $module . '.php');
1754
                if ($res)
1755
                    break;
1756
            }
1757
1758
            $mod = new $module();
1759
1760
            dol_syslog(get_class($this) . "::check_codefournisseur code_fournisseur=" . $this->code_fournisseur . " module=" . $module);
1761
            $result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
1762
            return $result;
1763
        } else {
1764
            return 0;
1765
        }
1766
    }
1767
1768
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1769
1770
    /**
1771
     *    Define parent commany of current company
1772
     *
1773
     * @param int $id Id of thirdparty to set or '' to remove
1774
     * @return    int            <0 if KO, >0 if OK
1775
     */
1776
    function set_parent($id)
1777
    {
1778
        // phpcs:enable
1779
        if ($this->id) {
1780
            $sql = "UPDATE " . MAIN_DB_PREFIX . "societe";
1781
            $sql .= " SET parent = " . ($id > 0 ? $id : "null");
1782
            $sql .= " WHERE rowid = " . $this->id;
1783
            dol_syslog(get_class($this) . '::set_parent', LOG_DEBUG);
1784
            $resql = $this->db->query($sql);
1785
            if ($resql) {
1786
                $this->parent = $id;
1787
                return 1;
1788
            } else {
1789
                return -1;
1790
            }
1791
        } else
1792
            return -1;
1793
    }
1794
1795
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1796
1797
    /**
1798
     *  Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
1799
     *
1800
     * @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
1801
     * @param Societe $soc Objet societe
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Societe was not found. Did you mean Societe? If so, make sure to prefix the type with \.
Loading history...
1802
     * @return int                        <=0 if KO, >0 if OK
1803
     *  TODO better to have this in a lib than into a business class
1804
     */
1805
    function id_prof_check($idprof, $soc)
1806
    {
1807
        // phpcs:enable
1808
        global $conf;
1809
1810
        $ok = 1;
1811
1812
        if (!empty($conf->global->MAIN_DISABLEPROFIDRULES))
1813
            return 1;
1814
1815
        // Verifie SIREN si pays FR
1816
        if ($idprof == 1 && $soc->country_code == 'FR') {
1817
            $chaine = trim($this->idprof1);
1818
            $chaine = preg_replace('/(\s)/', '', $chaine);
1819
1820
            if (!is_numeric($chaine))
1821
                return -1;
1822
            if (dol_strlen($chaine) != 9)
1823
                return -1;
1824
1825
            // on prend chaque chiffre un par un
1826
            // si son index (position dans la chaîne en commence à 0 au premier caractère) est impair
1827
            // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
1828
            // on ajoute cette valeur à la somme totale
1829
1830
            for ($index = 0; $index < 9; $index++) {
1831
                $number = (int)$siren[$index];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $siren seems to be never defined.
Loading history...
1832
                if (($index % 2) != 0) {
1833
                    if (($number *= 2) > 9)
1834
                        $number -= 9;
1835
                }
1836
                $sum += $number;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sum seems to be never defined.
Loading history...
1837
            }
1838
1839
            // le numéro est valide si la somme des chiffres est multiple de 10
1840
            if (($sum % 10) != 0)
1841
                return -1;
1842
        }
1843
1844
        // Verifie SIRET si pays FR
1845
        if ($idprof == 2 && $soc->country_code == 'FR') {
1846
            $chaine = trim($this->idprof2);
1847
            $chaine = preg_replace('/(\s)/', '', $chaine);
1848
1849
            if (!is_numeric($chaine))
1850
                return -1;
1851
            if (dol_strlen($chaine) != 14)
1852
                return -1;
1853
1854
            // on prend chaque chiffre un par un
1855
            // si son index (position dans la chaîne en commence à 0 au premier caractère) est pair
1856
            // on double sa valeur et si cette dernière est supérieure à 9, on lui retranche 9
1857
            // on ajoute cette valeur à la somme totale
1858
1859
            for ($index = 0; $index < 14; $index++) {
1860
                $number = (int)$chaine[$index];
1861
                if (($index % 2) == 0) {
1862
                    if (($number *= 2) > 9)
1863
                        $number -= 9;
1864
                }
1865
                $sum += $number;
1866
            }
1867
1868
            // le numéro est valide si la somme des chiffres est multiple de 10
1869
            if (($sum % 10) != 0)
1870
                return -1;
1871
        }
1872
1873
        //Verify CIF/NIF/NIE if pays ES
1874
        //Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
1875
        if ($idprof == 1 && $soc->country_code == 'ES') {
1876
            $string = trim($this->idprof1);
1877
            $string = preg_replace('/(\s)/', '', $string);
1878
            $string = strtoupper($string);
1879
1880
            for ($i = 0; $i < 9; $i++)
1881
                $num[$i] = substr($string, $i, 1);
1882
1883
            //Check format
1884
            if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
1885
                return 0;
1886
1887
            //Check NIF
1888
            if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
1889
                if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
1890
                    return 1;
1891
                else
1892
                    return -1;
1893
1894
            //algorithm checking type code CIF
1895
            $sum = $num[2] + $num[4] + $num[6];
1896
            for ($i = 1; $i < 8; $i += 2)
1897
                $sum += intval(substr((2 * $num[$i]), 0, 1)) + intval(substr((2 * $num[$i]), 1, 1));
1898
            $n = 10 - substr($sum, strlen($sum) - 1, 1);
1899
1900
            //Chek special NIF
1901
            if (preg_match('/^[KLM]{1}/', $string))
1902
                if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
1903
                    return 1;
1904
                else
1905
                    return -1;
1906
1907
            //Check CIF
1908
            if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
1909
                if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
1910
                    return 2;
1911
                else
1912
                    return -2;
1913
1914
            //Check NIE T
1915
            if (preg_match('/^[T]{1}/', $string))
1916
                if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
1917
                    return 3;
1918
                else
1919
                    return -3;
1920
1921
            //Check NIE XYZ
1922
            if (preg_match('/^[XYZ]{1}/', $string))
1923
                if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X', 'Y', 'Z'), array('0', '1', '2'), $string), 0, 8) % 23, 1))
1924
                    return 3;
1925
                else
1926
                    return -3;
1927
1928
            //Can not be verified
1929
            return -4;
1930
        }
1931
1932
        //Verify NIF if country is PT
1933
        //Returns: 1 if NIF ok, -1 if NIF bad, 0 if unexpected bad
1934
        if ($idprof == 1 && $soc->country_code == 'PT') {
1935
            $string = trim($this->idprof1);
1936
            $string = preg_replace('/(\s)/', '', $string);
1937
1938
            for ($i = 0; $i < 9; $i++) {
1939
                $num[$i] = substr($string, $i, 1);
1940
            }
1941
1942
            //Check NIF
1943
            if (preg_match('/(^[0-9]{9}$)/', $string)) {
1944
                return 1;
1945
            } else {
1946
                return -1;
1947
            }
1948
        }
1949
1950
        return $ok;
1951
    }
1952
1953
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1954
1955
    /**
1956
     *   Return an url to check online a professional id or empty string
1957
     *
1958
     * @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
1959
     * @param Societe $thirdparty Object thirdparty
1960
     * @return    string                Url or empty string if no URL known
1961
     *   TODO better in a lib than into business class
1962
     */
1963
    function id_prof_url($idprof, $thirdparty)
1964
    {
1965
        // phpcs:enable
1966
        global $conf, $langs, $hookmanager;
1967
1968
        $url = '';
1969
        $action = '';
1970
1971
        $hookmanager->initHooks(array('idprofurl'));
1972
        $parameters = array('idprof' => $idprof, 'company' => $thirdparty);
1973
        $reshook = $hookmanager->executeHooks('getIdProfUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
1974
        if (empty($reshook)) {
1975
            if (!empty($conf->global->MAIN_DISABLEPROFIDRULES)) {
1976
                return '';
1977
            }
1978
1979
            // TODO Move links to validate professional ID into a dictionary table "country" + "link"
1980
            $strippedIdProf1 = str_replace(' ', '', $thirdparty->idprof1);
1981
            if ($idprof == 1 && $thirdparty->country_code == 'FR') {
1982
                $url = 'http://www.societe.com/cgi-bin/search?champs=' . $strippedIdProf1;    // See also http://avis-situation-sirene.insee.fr/
1983
            }
1984
            if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) {
1985
                $url = 'https://beta.companieshouse.gov.uk/company/' . $strippedIdProf1;
1986
            }
1987
            if ($idprof == 1 && $thirdparty->country_code == 'ES') {
1988
                $url = 'http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/' . $strippedIdProf1;
1989
            }
1990
            if ($idprof == 1 && $thirdparty->country_code == 'IN') {
1991
                $url = 'http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber=' . $strippedIdProf1 . ';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
1992
            }
1993
            if ($idprof == 1 && $thirdparty->country_code == 'PT') {
1994
                $url = 'http://www.nif.pt/' . $strippedIdProf1;
1995
            }
1996
1997
            if ($url) {
1998
                return '<a target="_blank" href="' . $url . '">' . $langs->trans("Check") . '</a>';
1999
            }
2000
        } else {
2001
            return $hookmanager->resPrint;
2002
        }
2003
2004
        return '';
2005
    }
2006
2007
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2008
2009
    /**
2010
     *   Indique si la societe a des projets
2011
     *
2012
     * @return     bool       true si la societe a des projets, false sinon
2013
     */
2014
    function has_projects()
2015
    {
2016
        // phpcs:enable
2017
        $sql = 'SELECT COUNT(*) as numproj FROM ' . MAIN_DB_PREFIX . 'projet WHERE fk_soc = ' . $this->id;
2018
        $resql = $this->db->query($sql);
2019
        if ($resql) {
2020
            $obj = $this->db->fetch_object($resql);
2021
            $count = $obj->numproj;
2022
        } else {
2023
            $count = 0;
2024
            print $this->db->error();
2025
        }
2026
        $this->db->free($resql);
2027
        return ($count > 0);
2028
    }
2029
2030
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2031
2032
    /**
2033
     *  Load information for tab info
2034
     *
2035
     * @param int $id Id of thirdparty to load
2036
     * @return    void
2037
     */
2038
    function info($id)
2039
    {
2040
        $sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
2041
        $sql .= " fk_user_creat, fk_user_modif";
2042
        $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s";
2043
        $sql .= " WHERE s.rowid = " . $id;
2044
2045
        $result = $this->db->query($sql);
2046
        if ($result) {
2047
            if ($this->db->num_rows($result)) {
2048
                $obj = $this->db->fetch_object($result);
2049
2050
                $this->id = $obj->rowid;
2051
2052
                if ($obj->fk_user_creat) {
2053
                    $cuser = new User($this->db);
2054
                    $cuser->fetch($obj->fk_user_creat);
2055
                    $this->user_creation = $cuser;
2056
                }
2057
2058
                if ($obj->fk_user_modif) {
2059
                    $muser = new User($this->db);
2060
                    $muser->fetch($obj->fk_user_modif);
2061
                    $this->user_modification = $muser;
2062
                }
2063
2064
                $this->ref = $obj->name;
2065
                $this->date_creation = $this->db->jdate($obj->date_creation);
2066
                $this->date_modification = $this->db->jdate($obj->date_modification);
2067
            }
2068
2069
            $this->db->free($result);
2070
        } else {
2071
            dol_print_error($this->db);
2072
        }
2073
    }
2074
2075
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2076
2077
    /**
2078
     *  Return if a company is inside the EEC (European Economic Community)
2079
     *
2080
     * @return     boolean        true = country inside EEC, false = country outside EEC
2081
     */
2082
    function isInEEC()
2083
    {
2084
        require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
2085
        return isInEEC($this);
2086
    }
2087
2088
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2089
2090
    /**
2091
     *  Charge la liste des categories fournisseurs
2092
     *
2093
     * @return    int      0 if success, <> 0 if error
2094
     */
2095
    function LoadSupplierCateg()
2096
    {
2097
        // phpcs:enable
2098
        $this->SupplierCategories = array();
2099
        $sql = "SELECT rowid, label";
2100
        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie";
2101
        $sql .= " WHERE type = " . Categorie::TYPE_SUPPLIER;
2102
2103
        $resql = $this->db->query($sql);
2104
        if ($resql) {
2105
            while ($obj = $this->db->fetch_object($resql)) {
2106
                $this->SupplierCategories[$obj->rowid] = $obj->label;
2107
            }
2108
            return 0;
2109
        } else {
2110
            return -1;
2111
        }
2112
    }
2113
2114
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2115
2116
    /**
2117
     *  Insert link supplier - category
2118
     *
2119
     * @param int $categorie_id Id of category
2120
     * @return int                        0 if success, <> 0 if error
2121
     */
2122
    function AddFournisseurInCategory($categorie_id)
2123
    {
2124
        // phpcs:enable
2125
        if ($categorie_id > 0 && $this->id > 0) {
2126
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "categorie_fournisseur (fk_categorie, fk_soc) ";
2127
            $sql .= " VALUES (" . $categorie_id . ", " . $this->id . ")";
2128
2129
            if ($resql = $this->db->query($sql))
2130
                return 0;
2131
        } else {
2132
            return 0;
2133
        }
2134
        return -1;
2135
    }
2136
2137
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2138
2139
    /**
2140
     *  Create a third party into database from a member object
2141
     *
2142
     * @param Adherent $member Object member
2143
     * @param string $socname Name of third party to force
2144
     * @param string $socalias Alias name of third party to force
2145
     * @param string $customercode Customer code
2146
     * @return int                            <0 if KO, id of created account if OK
2147
     */
2148
    function create_from_member(Adherent $member, $socname = '', $socalias = '', $customercode = '')
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Adherent was not found. Did you mean Adherent? If so, make sure to prefix the type with \.
Loading history...
2149
    {
2150
        // phpcs:enable
2151
        global $user, $langs;
2152
2153
        dol_syslog(get_class($this) . "::create_from_member", LOG_DEBUG);
2154
2155
        $name = $socname ? $socname : $member->societe;
2156
        if (empty($name))
2157
            $name = $member->getFullName($langs);
2158
2159
        $alias = $socalias ? $socalias : '';
2160
2161
        // Positionne parametres
2162
        $this->nom = $name;    // TODO deprecated
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

2162
        /** @scrutinizer ignore-deprecated */ $this->nom = $name;    // TODO deprecated

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2163
        $this->name = $name;
2164
        $this->name_alias = $alias;
2165
        $this->address = $member->address;
2166
        $this->zip = $member->zip;
2167
        $this->town = $member->town;
2168
        $this->country_code = $member->country_code;
2169
        $this->country_id = $member->country_id;
2170
        $this->phone = $member->phone;       // Prof phone
2171
        $this->email = $member->email;
2172
        $this->skype = $member->skype;
2173
        $this->twitter = $member->twitter;
2174
        $this->facebook = $member->facebook;
2175
2176
        $this->client = 1;    // A member is a customer by default
2177
        $this->code_client = ($customercode ? $customercode : -1);
2178
        $this->code_fournisseur = -1;
2179
2180
        $this->db->begin();
2181
2182
        // Cree et positionne $this->id
2183
        $result = $this->create($user);
2184
        if ($result >= 0) {
2185
            $sql = "UPDATE " . MAIN_DB_PREFIX . "adherent";
2186
            $sql .= " SET fk_soc=" . $this->id;
2187
            $sql .= " WHERE rowid=" . $member->id;
2188
2189
            $resql = $this->db->query($sql);
2190
            if ($resql) {
2191
                $this->db->commit();
2192
                return $this->id;
2193
            } else {
2194
                $this->error = $this->db->error();
2195
2196
                $this->db->rollback();
2197
                return -1;
2198
            }
2199
        } else {
2200
            // $this->error deja positionne
2201
            dol_syslog(get_class($this) . "::create_from_member - 2 - " . $this->error . " - " . join(',', $this->errors), LOG_ERR);
2202
2203
            $this->db->rollback();
2204
            return $result;
2205
        }
2206
    }
2207
2208
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2209
2210
    /**
2211
     *    Create third party in database.
2212
     *    $this->code_client = -1 and $this->code_fournisseur = -1 means automatic assignement.
2213
     *
2214
     * @param User $user Object of user that ask creation
2215
     * @return   int                >= 0 if OK, < 0 if KO
2216
     */
2217
    function create(User $user)
2218
    {
2219
        global $langs, $conf, $mysoc;
2220
2221
        $error = 0;
2222
2223
        // Clean parameters
2224
        if (empty($this->status)) {
2225
            $this->status = 0;
2226
        }
2227
        $this->name = $this->name ? trim($this->name) : trim($this->nom);
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

2227
        $this->name = $this->name ? trim($this->name) : trim(/** @scrutinizer ignore-deprecated */ $this->nom);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2228
        if (!empty($conf->global->MAIN_FIRST_TO_UPPER)) {
2229
            $this->name = ucwords($this->name);
2230
        }
2231
        $this->nom = $this->name; // For backward compatibility
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

2231
        /** @scrutinizer ignore-deprecated */ $this->nom = $this->name; // For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2232
        if (empty($this->client)) {
2233
            $this->client = 0;
2234
        }
2235
        if (empty($this->fournisseur)) {
2236
            $this->fournisseur = 0;
2237
        }
2238
        $this->import_key = trim($this->import_key);
2239
2240
        if (!empty($this->multicurrency_code)) {
2241
            $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\MultiCurrency was not found. Did you mean MultiCurrency? If so, make sure to prefix the type with \.
Loading history...
2242
        }
2243
        if (empty($this->fk_multicurrency)) {
2244
            $this->multicurrency_code = '';
2245
            $this->fk_multicurrency = 0;
2246
        }
2247
2248
        dol_syslog(get_class($this) . "::create " . $this->name);
2249
2250
        $now = dol_now();
2251
2252
        $this->db->begin();
2253
2254
        // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
2255
        if ($this->code_client == -1 || $this->code_client === 'auto') {
2256
            $this->get_codeclient($this, 0);
2257
        }
2258
        if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto') {
2259
            $this->get_codefournisseur($this, 1);
2260
        }
2261
2262
        // Check more parameters (including mandatory setup
2263
        // If error, this->errors[] is filled
2264
        $result = $this->verify();
2265
2266
        if ($result >= 0) {
2267
            {
2268
                $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
2269
            }
2270
2271
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
2272
            $sql .= " VALUES ('" . $this->db->escape($this->name) . "', '" . $this->db->escape($this->name_alias) . "', " . $this->db->escape($this->entity) . ", '" . $this->db->idate($now) . "'";
2273
            $sql .= ", " . (!empty($user->id) ? "'" . $user->id . "'" : "null");
2274
            $sql .= ", " . (!empty($this->canvas) ? "'" . $this->db->escape($this->canvas) . "'" : "null");
2275
            $sql .= ", " . $this->status;
2276
            $sql .= ", " . (!empty($this->ref_int) ? "'" . $this->db->escape($this->ref_int) . "'" : "null");
2277
            $sql .= ", " . (!empty($this->ref_ext) ? "'" . $this->db->escape($this->ref_ext) . "'" : "null");
2278
            $sql .= ", 0";
2279
            $sql .= ", " . (int)$this->fk_incoterms;
2280
            $sql .= ", '" . $this->db->escape($this->location_incoterms) . "'";
2281
            $sql .= ", " . (!empty($this->import_key) ? "'" . $this->db->escape($this->import_key) . "'" : "null");
2282
            $sql .= ", " . (int)$this->fk_multicurrency;
2283
            $sql .= ", '" . $this->db->escape($this->multicurrency_code) . "')";
2284
2285
            dol_syslog(get_class($this) . "::create", LOG_DEBUG);
2286
            $result = $this->db->query($sql);
2287
            if ($result) {
2288
                $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . "societe");
2289
2290
                $ret = $this->update($this->id, $user, 0, 1, 1, 'add');
2291
2292
                // Ajout du commercial affecte
2293
                if ($this->commercial_id != '' && $this->commercial_id != -1) {
2294
                    $this->add_commercial($user, $this->commercial_id);
2295
                } // si un commercial cree un client il lui est affecte automatiquement
2296
                elseif (empty($user->rights->societe->client->voir)) {
2297
                    $this->add_commercial($user, $user->id);
2298
                }
2299
2300
                if ($ret >= 0) {
2301
                    // Call trigger
2302
                    $result = $this->call_trigger('COMPANY_CREATE', $user);
2303
                    if ($result < 0)
2304
                        $error++;
2305
                    // End call triggers
2306
                } else
2307
                    $error++;
2308
2309
                if (!$error) {
2310
                    dol_syslog(get_class($this) . "::Create success id=" . $this->id);
2311
                    $this->db->commit();
2312
                    return $this->id;
2313
                } else {
2314
                    dol_syslog(get_class($this) . "::Create echec update " . $this->error . " " . join(',', $this->errors), LOG_ERR);
2315
                    $this->db->rollback();
2316
                    return -4;
2317
                }
2318
            } else {
2319
                if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2320
                    $this->error = $langs->trans("ErrorCompanyNameAlreadyExists", $this->name);    // duplicate on a field (code or profid or ...)
2321
                    $result = -1;
2322
                } else {
2323
                    $this->error = $this->db->lasterror();
2324
                    $result = -2;
2325
                }
2326
                $this->db->rollback();
2327
                return $result;
2328
            }
2329
        } else {
2330
            $this->db->rollback();
2331
            dol_syslog(get_class($this) . "::Create fails verify " . join(',', $this->errors), LOG_WARNING);
2332
            return -3;
2333
        }
2334
    }
2335
2336
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2337
2338
    /**
2339
     *  Attribut un code client a partir du module de controle des codes.
2340
     *  Return value is stored into this->code_client
2341
     *
2342
     * @param Societe $objsoc Object thirdparty
2343
     * @param int $type Should be 0 to say customer
2344
     * @return void
2345
     */
2346
    function get_codeclient($objsoc = 0, $type = 0)
2347
    {
2348
        // phpcs:enable
2349
        global $conf;
2350
        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
2351
            $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2352
2353
            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2354
            foreach ($dirsociete as $dirroot) {
2355
                $res = dol_include_once($dirroot . $module . '.php');
2356
                if ($res)
2357
                    break;
2358
            }
2359
            $mod = new $module();
2360
2361
            $this->code_client = $mod->getNextValue($objsoc, $type);
2362
            $this->prefixCustomerIsRequired = $mod->prefixIsRequired;
2363
2364
            dol_syslog(get_class($this) . "::get_codeclient code_client=" . $this->code_client . " module=" . $module);
2365
        }
2366
    }
2367
2368
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2369
2370
    /**
2371
     *  Attribut un code fournisseur a partir du module de controle des codes.
2372
     *  Return value is stored into this->code_fournisseur
2373
     *
2374
     * @param Societe $objsoc Object thirdparty
2375
     * @param int $type Should be 1 to say supplier
2376
     * @return void
2377
     */
2378
    function get_codefournisseur($objsoc = 0, $type = 1)
2379
    {
2380
        // phpcs:enable
2381
        global $conf;
2382
        if (!empty($conf->global->SOCIETE_CODECLIENT_ADDON)) {
2383
            $module = $conf->global->SOCIETE_CODECLIENT_ADDON;
2384
2385
            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
2386
            foreach ($dirsociete as $dirroot) {
2387
                $res = dol_include_once($dirroot . $module . '.php');
2388
                if ($res)
2389
                    break;
2390
            }
2391
            $mod = new $module();
2392
2393
            $this->code_fournisseur = $mod->getNextValue($objsoc, $type);
2394
2395
            dol_syslog(get_class($this) . "::get_codefournisseur code_fournisseur=" . $this->code_fournisseur . " module=" . $module);
2396
        }
2397
    }
2398
2399
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2400
2401
    /**
2402
     *    Check properties of third party are ok (like name, third party codes, ...)
2403
     *    Used before an add or update.
2404
     *
2405
     * @return     int        0 if OK, <0 if KO
2406
     */
2407
    function verify()
2408
    {
2409
        global $conf, $langs, $mysoc;
2410
2411
        $error = 0;
2412
        $this->errors = array();
2413
2414
        $result = 0;
2415
        $this->name = trim($this->name);
2416
        $this->nom = $this->name; // For backward compatibility
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

2416
        /** @scrutinizer ignore-deprecated */ $this->nom = $this->name; // For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2417
2418
        if (!$this->name) {
2419
            $this->errors[] = 'ErrorBadThirdPartyName';
2420
            $result = -2;
2421
        }
2422
2423
        if ($this->client) {
2424
            $rescode = $this->check_codeclient();
2425
            if ($rescode <> 0) {
2426
                if ($rescode == -1) {
2427
                    $this->errors[] = 'ErrorBadCustomerCodeSyntax';
2428
                } elseif ($rescode == -2) {
2429
                    $this->errors[] = 'ErrorCustomerCodeRequired';
2430
                } elseif ($rescode == -3) {
2431
                    $this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
2432
                } elseif ($rescode == -4) {
2433
                    $this->errors[] = 'ErrorPrefixRequired';
2434
                }
2435
                $result = -3;
2436
            }
2437
        }
2438
2439
        if ($this->fournisseur) {
2440
            $rescode = $this->check_codefournisseur();
2441
            if ($rescode <> 0) {
2442
                if ($rescode == -1) {
2443
                    $this->errors[] = 'ErrorBadSupplierCodeSyntax';
2444
                } elseif ($rescode == -2) {
2445
                    $this->errors[] = 'ErrorSupplierCodeRequired';
2446
                } elseif ($rescode == -3) {
2447
                    $this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
2448
                } elseif ($rescode == -5) {
2449
                    $this->errors[] = 'ErrorprefixRequired';
2450
                }
2451
                $result = -3;
2452
            }
2453
        }
2454
2455
        // Check for duplicate or mandatory fields defined into setup
2456
        $array_to_check = array('IDPROF1', 'IDPROF2', 'IDPROF3', 'IDPROF4', 'IDPROF5', 'IDPROF6', 'EMAIL');
2457
        foreach ($array_to_check as $key) {
2458
            $keymin = strtolower($key);
2459
            $i = (int)preg_replace('/[^0-9]/', '', $key);
2460
            $vallabel = $this->$keymin;
2461
2462
            if ($i > 0) {
2463
                if ($this->isACompany()) {
2464
                    // Check for unicity
2465
                    if ($vallabel && $this->id_prof_verifiable($i)) {
2466
                        if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
2467
                            $langs->load("errors");
2468
                            $error++;
2469
                            $this->errors[] = $langs->transcountry('ProfId' . $i, $this->country_code) . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
2470
                        }
2471
                    }
2472
2473
                    // Check for mandatory prof id (but only if country is other than ours)
2474
                    if ($mysoc->country_id > 0 && $this->country_id == $mysoc->country_id) {
2475
                        $idprof_mandatory = 'SOCIETE_' . $key . '_MANDATORY';
2476
                        if (!$vallabel && !empty($conf->global->$idprof_mandatory)) {
2477
                            $langs->load("errors");
2478
                            $error++;
2479
                            $this->errors[] = $langs->trans("ErrorProdIdIsMandatory", $langs->transcountry('ProfId' . $i, $this->country_code)) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
2480
                        }
2481
                    }
2482
                }
2483
            } else {
2484
                //var_dump($conf->global->SOCIETE_EMAIL_UNIQUE);
2485
                //var_dump($conf->global->SOCIETE_EMAIL_MANDATORY);
2486
                if ($key == 'EMAIL') {
2487
                    // Check for unicity
2488
                    if ($vallabel && !empty($conf->global->SOCIETE_EMAIL_UNIQUE)) {
2489
                        if ($this->id_prof_exists($keymin, $vallabel, ($this->id > 0 ? $this->id : 0))) {
2490
                            $langs->load("errors");
2491
                            $error++;
2492
                            $this->errors[] = $langs->trans('Email') . " " . $langs->trans("ErrorProdIdAlreadyExist", $vallabel) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
2493
                        }
2494
                    }
2495
2496
                    // Check for mandatory
2497
                    if (!empty($conf->global->SOCIETE_EMAIL_MANDATORY) && !isValidEMail($this->email)) {
2498
                        $langs->load("errors");
2499
                        $error++;
2500
                        $this->errors[] = $langs->trans("ErrorBadEMail", $this->email) . ' (' . $langs->trans("ForbiddenBySetupRules") . ')';
2501
                    }
2502
                }
2503
            }
2504
        }
2505
2506
        if ($error)
2507
            $result = -4;
2508
2509
        return $result;
2510
    }
2511
2512
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2513
2514
    /**
2515
     *  Return if third party is a company (Business) or an end user (Consumer)
2516
     *
2517
     * @return    boolean     true=is a company, false=a and user
2518
     */
2519
    function isACompany()
2520
    {
2521
        global $conf;
2522
2523
        // Define if third party is treated as company (or not) when nature is unknown
2524
        $isacompany = empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES) ? 0 : 1; // 0 by default
2525
        if (!empty($this->tva_intra))
2526
            $isacompany = 1;
2527
        else if (!empty($this->typent_code) && $this->typent_code != 'TE_UNKNOWN') {
2528
            // TODO Add a field is_a_company into dictionary
2529
            if (preg_match('/^TE_PRIVATE/', $this->typent_code))
2530
                $isacompany = 0;
2531
            else
2532
                $isacompany = 1;
2533
        }
2534
2535
        return $isacompany;
2536
    }
2537
2538
    /**
2539
     *  Returns if a profid sould be verified
2540
     *
2541
     * @param int $idprof 1,2,3,4,5,6 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm,5=idprof5,6=idprof6)
2542
     * @return boolean            true , false
2543
     */
2544
    function id_prof_verifiable($idprof)
2545
    {
2546
        // phpcs:enable
2547
        global $conf;
2548
2549
        switch ($idprof) {
2550
            case 1:
2551
                $ret = (!$conf->global->SOCIETE_IDPROF1_UNIQUE ? false : true);
2552
                break;
2553
            case 2:
2554
                $ret = (!$conf->global->SOCIETE_IDPROF2_UNIQUE ? false : true);
2555
                break;
2556
            case 3:
2557
                $ret = (!$conf->global->SOCIETE_IDPROF3_UNIQUE ? false : true);
2558
                break;
2559
            case 4:
2560
                $ret = (!$conf->global->SOCIETE_IDPROF4_UNIQUE ? false : true);
2561
                break;
2562
            case 5:
2563
                $ret = (!$conf->global->SOCIETE_IDPROF5_UNIQUE ? false : true);
2564
                break;
2565
            case 6:
2566
                $ret = (!$conf->global->SOCIETE_IDPROF6_UNIQUE ? false : true);
2567
                break;
2568
            default:
2569
                $ret = false;
2570
        }
2571
2572
        return $ret;
2573
    }
2574
2575
    /**
2576
     *    Verify if a profid exists into database for others thirds
2577
     *
2578
     * @param string $idprof 'idprof1','idprof2','idprof3','idprof4','idprof5','idprof6','email' (Example: idprof1=siren, idprof2=siret, idprof3=naf, idprof4=rcs/rm)
2579
     * @param string $value Value of profid
2580
     * @param int $socid Id of thirdparty to exclude (if update)
2581
     * @return   boolean                True if exists, False if not
2582
     */
2583
    function id_prof_exists($idprof, $value, $socid = 0)
2584
    {
2585
        // phpcs:enable
2586
        $field = $idprof;
2587
2588
        switch ($idprof) { // For backward compatibility
2589
            case '1':
2590
            case 'idprof1':
2591
                $field = "siren";
2592
                break;
2593
            case '2':
2594
            case 'idprof2':
2595
                $field = "siret";
2596
                break;
2597
            case '3':
2598
            case 'idprof3':
2599
                $field = "ape";
2600
                break;
2601
            case '4':
2602
            case 'idprof4':
2603
                $field = "idprof4";
2604
                break;
2605
            case '5':
2606
                $field = "idprof5";
2607
                break;
2608
            case '6':
2609
                $field = "idprof6";
2610
                break;
2611
        }
2612
2613
        //Verify duplicate entries
2614
        $sql = "SELECT COUNT(*) as idprof FROM " . MAIN_DB_PREFIX . "societe WHERE " . $field . " = '" . $value . "' AND entity IN (" . getEntity('societe') . ")";
2615
        if ($socid)
2616
            $sql .= " AND rowid <> " . $socid;
2617
        $resql = $this->db->query($sql);
2618
        if ($resql) {
2619
            $obj = $this->db->fetch_object($resql);
2620
            $count = $obj->idprof;
2621
        } else {
2622
            $count = 0;
2623
            print $this->db->error();
2624
        }
2625
        $this->db->free($resql);
2626
2627
        if ($count > 0)
2628
            return true;
2629
        else
2630
            return false;
2631
    }
2632
2633
    /**
2634
     *      Update parameters of third party
2635
     *
2636
     * @param int $id Id of company (deprecated, use 0 here and call update on an object loaded by a fetch)
2637
     * @param User $user Utilisateur qui demande la mise a jour
2638
     * @param int $call_trigger 0=no, 1=yes
2639
     * @param int $allowmodcodeclient Inclut modif code client et code compta
2640
     * @param int $allowmodcodefournisseur Inclut modif code fournisseur et code compta fournisseur
2641
     * @param string $action 'add' or 'update' or 'merge'
2642
     * @param int $nosyncmember Do not synchronize info of linked member
2643
     * @return int                                <0 if KO, >=0 if OK
2644
     */
2645
    function update($id, $user = '', $call_trigger = 1, $allowmodcodeclient = 0, $allowmodcodefournisseur = 0, $action = 'update', $nosyncmember = 1)
2646
    {
2647
        global $langs, $conf, $hookmanager;
2648
2649
        require_once DOL_DOCUMENT_ROOT . '/core/lib/functions2.lib.php';
2650
2651
        if (empty($id))
2652
            $id = $this->id;
2653
2654
        $error = 0;
2655
2656
        dol_syslog(get_class($this) . "::Update id=" . $id . " call_trigger=" . $call_trigger . " allowmodcodeclient=" . $allowmodcodeclient . " allowmodcodefournisseur=" . $allowmodcodefournisseur);
2657
2658
        $now = dol_now();
2659
2660
        // Clean parameters
2661
        $this->id = $id;
2662
        $this->entity = ((isset($this->entity) && is_numeric($this->entity)) ? $this->entity : $conf->entity);
2663
        $this->name = $this->name ? trim($this->name) : trim($this->nom);
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

2663
        $this->name = $this->name ? trim($this->name) : trim(/** @scrutinizer ignore-deprecated */ $this->nom);

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2664
        $this->nom = $this->name; // For backward compatibility
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

2664
        /** @scrutinizer ignore-deprecated */ $this->nom = $this->name; // For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
2665
        $this->name_alias = trim($this->name_alias);
2666
        $this->ref_ext = trim($this->ref_ext);
2667
        $this->address = $this->address ? trim($this->address) : trim($this->address);
2668
        $this->zip = $this->zip ? trim($this->zip) : trim($this->zip);
2669
        $this->town = $this->town ? trim($this->town) : trim($this->town);
2670
        $this->state_id = trim($this->state_id);
0 ignored issues
show
Documentation Bug introduced by
The property $state_id was declared of type integer, but trim($this->state_id) is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
2671
        $this->country_id = ($this->country_id > 0) ? $this->country_id : 0;
2672
        $this->phone = trim($this->phone);
2673
        $this->phone = preg_replace("/\s/", "", $this->phone);
2674
        $this->phone = preg_replace("/\./", "", $this->phone);
2675
        $this->fax = trim($this->fax);
2676
        $this->fax = preg_replace("/\s/", "", $this->fax);
2677
        $this->fax = preg_replace("/\./", "", $this->fax);
2678
        $this->email = trim($this->email);
2679
        $this->skype = trim($this->skype);
2680
        $this->twitter = trim($this->twitter);
2681
        $this->facebook = trim($this->facebook);
2682
        $this->url = $this->url ? clean_url($this->url, 0) : '';
2683
        $this->note_private = trim($this->note_private);
2684
        $this->note_public = trim($this->note_public);
2685
        $this->idprof1 = trim($this->idprof1);
2686
        $this->idprof2 = trim($this->idprof2);
2687
        $this->idprof3 = trim($this->idprof3);
2688
        $this->idprof4 = trim($this->idprof4);
2689
        $this->idprof5 = (!empty($this->idprof5) ? trim($this->idprof5) : '');
2690
        $this->idprof6 = (!empty($this->idprof6) ? trim($this->idprof6) : '');
2691
        $this->prefix_comm = trim($this->prefix_comm);
2692
        $this->outstanding_limit = price2num($this->outstanding_limit);
2693
        $this->order_min_amount = price2num($this->order_min_amount);
2694
        $this->supplier_order_min_amount = price2num($this->supplier_order_min_amount);
2695
2696
        $this->tva_assuj = trim($this->tva_assuj);
2697
        $this->tva_intra = dol_sanitizeFileName($this->tva_intra, '');
2698
        if (empty($this->status))
2699
            $this->status = 0;
2700
2701
        if (!empty($this->multicurrency_code))
2702
            $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
2703
        if (empty($this->fk_multicurrency)) {
2704
            $this->multicurrency_code = '';
2705
            $this->fk_multicurrency = 0;
2706
        }
2707
2708
        // Local taxes
2709
        $this->localtax1_assuj = trim($this->localtax1_assuj);
2710
        $this->localtax2_assuj = trim($this->localtax2_assuj);
2711
2712
        $this->localtax1_value = trim($this->localtax1_value);
2713
        $this->localtax2_value = trim($this->localtax2_value);
2714
2715
        if ($this->capital != '')
2716
            $this->capital = price2num(trim($this->capital));
2717
        if (!is_numeric($this->capital))
2718
            $this->capital = '';     // '' = undef
2719
2720
        $this->effectif_id = trim($this->effectif_id);
2721
        $this->forme_juridique_code = trim($this->forme_juridique_code);
2722
2723
        //Gencod
2724
        $this->barcode = trim($this->barcode);
2725
2726
        // For automatic creation
2727
        if ($this->code_client == -1 || $this->code_client === 'auto')
2728
            $this->get_codeclient($this, 0);
2729
        if ($this->code_fournisseur == -1 || $this->code_fournisseur === 'auto')
2730
            $this->get_codefournisseur($this, 1);
2731
2732
        $this->code_compta = trim($this->code_compta);
2733
        $this->code_compta_fournisseur = trim($this->code_compta_fournisseur);
2734
2735
        // Check parameters. More tests are done later in the ->verify()
2736
        if (!is_numeric($this->client) && !is_numeric($this->fournisseur)) {
2737
            $langs->load("errors");
2738
            $this->error = $langs->trans("BadValueForParameterClientOrSupplier");
2739
            return -1;
2740
        }
2741
2742
        $customer = false;
2743
        if (!empty($allowmodcodeclient) && !empty($this->client)) {
2744
            // Attention get_codecompta peut modifier le code suivant le module utilise
2745
            if (empty($this->code_compta)) {
2746
                $ret = $this->get_codecompta('customer');
2747
                if ($ret < 0)
2748
                    return -1;
2749
            }
2750
2751
            $customer = true;
2752
        }
2753
2754
        $supplier = false;
2755
        if (!empty($allowmodcodefournisseur) && !empty($this->fournisseur)) {
2756
            // Attention get_codecompta peut modifier le code suivant le module utilise
2757
            if (empty($this->code_compta_fournisseur)) {
2758
                $ret = $this->get_codecompta('supplier');
2759
                if ($ret < 0)
2760
                    return -1;
2761
            }
2762
2763
            $supplier = true;
2764
        }
2765
2766
        //Web services
2767
        $this->webservices_url = $this->webservices_url ? clean_url($this->webservices_url, 0) : '';
2768
        $this->webservices_key = trim($this->webservices_key);
2769
2770
        //Incoterms
2771
        $this->fk_incoterms = (int)$this->fk_incoterms;
2772
        $this->location_incoterms = trim($this->location_incoterms);
2773
2774
        $this->db->begin();
2775
2776
        // Check name is required and codes are ok or unique.
2777
        // If error, this->errors[] is filled
2778
        $result = 0;
2779
        if ($action != 'add' && $action != 'merge') {
2780
            // We don't check when update called during a create because verify was already done.
2781
            // For a merge, we suppose source data is clean and a customer code of a deleted thirdparty must be accepted into a target thirdparty with empty code without duplicate error
2782
            $result = $this->verify();
2783
2784
            // If there is only one error and error is ErrorBadCustomerCodeSyntax and we don't change customer code, we allow the update
2785
            // So we can update record that were using and old numbering rule.
2786
            if (is_array($this->errors)) {
2787
                if (in_array('ErrorBadCustomerCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_client == $this->code_client) {
2788
                    if (($key = array_search('ErrorBadCustomerCodeSyntax', $this->errors)) !== false)
2789
                        unset($this->errors[$key]); // Remove error message
2790
                }
2791
                if (in_array('ErrorBadSupplierCodeSyntax', $this->errors) && is_object($this->oldcopy) && $this->oldcopy->code_fournisseur == $this->code_fournisseur) {
2792
                    if (($key = array_search('ErrorBadSupplierCodeSyntax', $this->errors)) !== false)
2793
                        unset($this->errors[$key]); // Remove error message
2794
                }
2795
                if (empty($this->errors)) { // If there is no more error, we can make like if there is no error at all
2796
                    $result = 0;
2797
                }
2798
            }
2799
        }
2800
2801
        if ($result >= 0) {
2802
            dol_syslog(get_class($this) . "::update verify ok or not done");
2803
2804
            $sql = "UPDATE " . MAIN_DB_PREFIX . "societe SET ";
2805
            $sql .= "entity = " . $this->db->escape($this->entity);
2806
            $sql .= ",nom = '" . $this->db->escape($this->name) . "'"; // Required
2807
            $sql .= ",name_alias = '" . $this->db->escape($this->name_alias) . "'";
2808
            $sql .= ",ref_ext = " . (!empty($this->ref_ext) ? "'" . $this->db->escape($this->ref_ext) . "'" : "null");
2809
            $sql .= ",address = '" . $this->db->escape($this->address) . "'";
2810
2811
            $sql .= ",zip = " . (!empty($this->zip) ? "'" . $this->db->escape($this->zip) . "'" : "null");
2812
            $sql .= ",town = " . (!empty($this->town) ? "'" . $this->db->escape($this->town) . "'" : "null");
2813
2814
            $sql .= ",fk_departement = '" . (!empty($this->state_id) ? $this->state_id : '0') . "'";
2815
            $sql .= ",fk_pays = '" . (!empty($this->country_id) ? $this->country_id : '0') . "'";
2816
2817
            $sql .= ",phone = " . (!empty($this->phone) ? "'" . $this->db->escape($this->phone) . "'" : "null");
2818
            $sql .= ",fax = " . (!empty($this->fax) ? "'" . $this->db->escape($this->fax) . "'" : "null");
2819
            $sql .= ",email = " . (!empty($this->email) ? "'" . $this->db->escape($this->email) . "'" : "null");
2820
            $sql .= ",skype = " . (!empty($this->skype) ? "'" . $this->db->escape($this->skype) . "'" : "null");
2821
            $sql .= ",twitter = " . (!empty($this->twitter) ? "'" . $this->db->escape($this->twitter) . "'" : "null");
2822
            $sql .= ",facebook = " . (!empty($this->facebook) ? "'" . $this->db->escape($this->facebook) . "'" : "null");
2823
            $sql .= ",url = " . (!empty($this->url) ? "'" . $this->db->escape($this->url) . "'" : "null");
2824
2825
            $sql .= ",parent = " . ($this->parent > 0 ? $this->parent : "null");
2826
2827
            $sql .= ",note_private = " . (!empty($this->note_private) ? "'" . $this->db->escape($this->note_private) . "'" : "null");
2828
            $sql .= ",note_public = " . (!empty($this->note_public) ? "'" . $this->db->escape($this->note_public) . "'" : "null");
2829
2830
            $sql .= ",siren   = '" . $this->db->escape($this->idprof1) . "'";
2831
            $sql .= ",siret   = '" . $this->db->escape($this->idprof2) . "'";
2832
            $sql .= ",ape     = '" . $this->db->escape($this->idprof3) . "'";
2833
            $sql .= ",idprof4 = '" . $this->db->escape($this->idprof4) . "'";
2834
            $sql .= ",idprof5 = '" . $this->db->escape($this->idprof5) . "'";
2835
            $sql .= ",idprof6 = '" . $this->db->escape($this->idprof6) . "'";
2836
2837
            $sql .= ",tva_assuj = " . ($this->tva_assuj != '' ? "'" . $this->db->escape($this->tva_assuj) . "'" : "null");
2838
            $sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) . "'";
2839
            $sql .= ",status = " . $this->status;
2840
2841
            // Local taxes
2842
            $sql .= ",localtax1_assuj = " . ($this->localtax1_assuj != '' ? "'" . $this->db->escape($this->localtax1_assuj) . "'" : "null");
2843
            $sql .= ",localtax2_assuj = " . ($this->localtax2_assuj != '' ? "'" . $this->db->escape($this->localtax2_assuj) . "'" : "null");
2844
            if ($this->localtax1_assuj == 1) {
2845
                if ($this->localtax1_value != '') {
2846
                    $sql .= ",localtax1_value =" . $this->localtax1_value;
2847
                } else
2848
                    $sql .= ",localtax1_value =0.000";
2849
            } else
2850
                $sql .= ",localtax1_value =0.000";
2851
2852
            if ($this->localtax2_assuj == 1) {
2853
                if ($this->localtax2_value != '') {
2854
                    $sql .= ",localtax2_value =" . $this->localtax2_value;
2855
                } else
2856
                    $sql .= ",localtax2_value =0.000";
2857
            } else
2858
                $sql .= ",localtax2_value =0.000";
2859
2860
            $sql .= ",capital = " . ($this->capital == '' ? "null" : $this->capital);
2861
2862
            $sql .= ",prefix_comm = " . (!empty($this->prefix_comm) ? "'" . $this->db->escape($this->prefix_comm) . "'" : "null");
2863
2864
            $sql .= ",fk_effectif = " . (!empty($this->effectif_id) ? "'" . $this->db->escape($this->effectif_id) . "'" : "null");
2865
            if (isset($this->stcomm_id)) {
2866
                $sql .= ",fk_stcomm=" . (!empty($this->stcomm_id) ? $this->stcomm_id : "0");
2867
            }
2868
            $sql .= ",fk_typent = " . (!empty($this->typent_id) ? "'" . $this->db->escape($this->typent_id) . "'" : "0");
2869
2870
            $sql .= ",fk_forme_juridique = " . (!empty($this->forme_juridique_code) ? "'" . $this->db->escape($this->forme_juridique_code) . "'" : "null");
2871
2872
            $sql .= ",mode_reglement = " . (!empty($this->mode_reglement_id) ? "'" . $this->db->escape($this->mode_reglement_id) . "'" : "null");
2873
            $sql .= ",cond_reglement = " . (!empty($this->cond_reglement_id) ? "'" . $this->db->escape($this->cond_reglement_id) . "'" : "null");
2874
            $sql .= ",mode_reglement_supplier = " . (!empty($this->mode_reglement_supplier_id) ? "'" . $this->db->escape($this->mode_reglement_supplier_id) . "'" : "null");
2875
            $sql .= ",cond_reglement_supplier = " . (!empty($this->cond_reglement_supplier_id) ? "'" . $this->db->escape($this->cond_reglement_supplier_id) . "'" : "null");
2876
            $sql .= ",fk_shipping_method = " . (!empty($this->shipping_method_id) ? "'" . $this->db->escape($this->shipping_method_id) . "'" : "null");
2877
2878
            $sql .= ",client = " . (!empty($this->client) ? $this->client : 0);
2879
            $sql .= ",fournisseur = " . (!empty($this->fournisseur) ? $this->fournisseur : 0);
2880
            $sql .= ",barcode = " . (!empty($this->barcode) ? "'" . $this->db->escape($this->barcode) . "'" : "null");
2881
            $sql .= ",default_lang = " . (!empty($this->default_lang) ? "'" . $this->db->escape($this->default_lang) . "'" : "null");
2882
            $sql .= ",logo = " . (!empty($this->logo) ? "'" . $this->db->escape($this->logo) . "'" : "null");
2883
            $sql .= ",outstanding_limit= " . ($this->outstanding_limit != '' ? $this->outstanding_limit : 'null');
2884
            $sql .= ",order_min_amount= " . ($this->order_min_amount != '' ? $this->order_min_amount : 'null');
2885
            $sql .= ",supplier_order_min_amount= " . ($this->supplier_order_min_amount != '' ? $this->supplier_order_min_amount : 'null');
2886
            $sql .= ",fk_prospectlevel='" . $this->db->escape($this->fk_prospectlevel) . "'";
2887
2888
            $sql .= ",webservices_url = " . (!empty($this->webservices_url) ? "'" . $this->db->escape($this->webservices_url) . "'" : "null");
2889
            $sql .= ",webservices_key = " . (!empty($this->webservices_key) ? "'" . $this->db->escape($this->webservices_key) . "'" : "null");
2890
2891
            //Incoterms
2892
            $sql .= ", fk_incoterms = " . $this->fk_incoterms;
2893
            $sql .= ", location_incoterms = " . (!empty($this->location_incoterms) ? "'" . $this->db->escape($this->location_incoterms) . "'" : "null");
2894
2895
            if ($customer) {
2896
                $sql .= ", code_client = " . (!empty($this->code_client) ? "'" . $this->db->escape($this->code_client) . "'" : "null");
2897
                $sql .= ", code_compta = " . (!empty($this->code_compta) ? "'" . $this->db->escape($this->code_compta) . "'" : "null");
2898
            }
2899
2900
            if ($supplier) {
2901
                $sql .= ", code_fournisseur = " . (!empty($this->code_fournisseur) ? "'" . $this->db->escape($this->code_fournisseur) . "'" : "null");
2902
                $sql .= ", code_compta_fournisseur = " . (!empty($this->code_compta_fournisseur) ? "'" . $this->db->escape($this->code_compta_fournisseur) . "'" : "null");
2903
            }
2904
            $sql .= ", fk_user_modif = " . ($user->id > 0 ? $user->id : "null");
0 ignored issues
show
Bug introduced by
The property id does not exist on string.
Loading history...
2905
            $sql .= ", fk_multicurrency = " . (int)$this->fk_multicurrency;
2906
            $sql .= ", multicurrency_code = '" . $this->db->escape($this->multicurrency_code) . "'";
2907
            $sql .= " WHERE rowid = " . (int)$id;
2908
2909
            $resql = $this->db->query($sql);
2910
            if ($resql) {
2911
                if (is_object($this->oldcopy)) { // If we have information on old values
2912
                    if ($this->oldcopy->country_id != $this->country_id) {
2913
                        unset($this->country_code);
2914
                        unset($this->country);
2915
                    }
2916
                    if ($this->oldcopy->state_id != $this->state_id) {
2917
                        unset($this->state_code);
2918
                        unset($this->state);
2919
                    }
2920
                } else {
2921
                    unset($this->country_code); // We clean this, in the doubt, because it may have been changed after an update of country_id
2922
                    unset($this->country);
2923
                    unset($this->state_code);
2924
                    unset($this->state);
2925
                }
2926
2927
                $nbrowsaffected = $this->db->affected_rows($resql);
2928
2929
                if (!$error && $nbrowsaffected) {
2930
                    // Update information on linked member if it is an update
2931
                    if (!$nosyncmember && !empty($conf->adherent->enabled)) {
2932
                        require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
2933
2934
                        dol_syslog(get_class($this) . "::update update linked member");
2935
2936
                        $lmember = new Adherent($this->db);
2937
                        $result = $lmember->fetch(0, 0, $this->id);
2938
2939
                        if ($result > 0) {
2940
                            $lmember->societe = $this->name;
2941
                            //$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname;	// We keep firstname and lastname of member unchanged
2942
                            //$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname;		// We keep firstname and lastname of member unchanged
2943
                            $lmember->address = $this->address;
2944
                            $lmember->email = $this->email;
2945
                            $lmember->skype = $this->skype;
2946
                            $lmember->twitter = $this->twitter;
2947
                            $lmember->facebook = $this->facebook;
2948
                            $lmember->phone = $this->phone;
2949
2950
                            $result = $lmember->update($user, 0, 1, 1, 1); // Use nosync to 1 to avoid cyclic updates
2951
                            if ($result < 0) {
2952
                                $this->error = $lmember->error;
2953
                                dol_syslog(get_class($this) . "::update " . $this->error, LOG_ERR);
2954
                                $error++;
2955
                            }
2956
                        } elseif ($result < 0) {
2957
                            $this->error = $lmember->error;
2958
                            $error++;
2959
                        }
2960
                    }
2961
                }
2962
2963
                $action = 'update';
2964
2965
                // Actions on extra fields
2966
                if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { // For avoid conflicts if trigger used
2967
                    $result = $this->insertExtraFields();
2968
                    if ($result < 0) {
2969
                        $error++;
2970
                    }
2971
                }
2972
2973
                if (!$error && $call_trigger) {
2974
                    // Call trigger
2975
                    $result = $this->call_trigger('COMPANY_MODIFY', $user);
2976
                    if ($result < 0)
2977
                        $error++;
2978
                    // End call triggers
2979
                }
2980
2981
                if (!$error) {
2982
                    dol_syslog(get_class($this) . "::Update success");
2983
                    $this->db->commit();
2984
                    return 1;
2985
                } else {
2986
                    $this->db->rollback();
2987
                    return -1;
2988
                }
2989
            } else {
2990
                if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
2991
                    // Doublon
2992
                    $this->error = $langs->trans("ErrorDuplicateField");
2993
                    $result = -1;
2994
                } else {
2995
                    $this->error = $this->db->lasterror();
2996
                    $result = -2;
2997
                }
2998
                $this->db->rollback();
2999
                return $result;
3000
            }
3001
        } else {
3002
            $this->db->rollback();
3003
            dol_syslog(get_class($this) . "::Update fails verify " . join(',', $this->errors), LOG_WARNING);
3004
            return -3;
3005
        }
3006
    }
3007
3008
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3009
3010
    /**
3011
     *        Renvoie un code compta, suivant le module de code compta.
3012
     *      Peut etre identique a celui saisit ou genere automatiquement.
3013
     *      A ce jour seule la generation automatique est implementee
3014
     *
3015
     * @param string $type Type of thirdparty ('customer' or 'supplier')
3016
     * @return    string                Code compta si ok, 0 si aucun, <0 si ko
3017
     */
3018
    function get_codecompta($type)
3019
    {
3020
        // phpcs:enable
3021
        global $conf;
3022
3023
        if (!empty($conf->global->SOCIETE_CODECOMPTA_ADDON)) {
3024
            $res = false;
3025
            $dirsociete = array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
3026
            foreach ($dirsociete as $dirroot) {
3027
                $res = dol_include_once($dirroot . $conf->global->SOCIETE_CODECOMPTA_ADDON . '.php');
3028
                if ($res)
3029
                    break;
3030
            }
3031
3032
            if ($res) {
3033
                $classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
3034
                $mod = new $classname;
3035
3036
                // Defini code compta dans $mod->code
3037
                $result = $mod->get_code($this->db, $this, $type);
3038
3039
                if ($type == 'customer')
3040
                    $this->code_compta = $mod->code;
3041
                else if ($type == 'supplier')
3042
                    $this->code_compta_fournisseur = $mod->code;
3043
3044
                return $result;
3045
            } else {
3046
                $this->error = 'ErrorAccountancyCodeNotDefined';
3047
                return -1;
3048
            }
3049
        } else {
3050
            if ($type == 'customer')
3051
                $this->code_compta = '';
3052
            else if ($type == 'supplier')
3053
                $this->code_compta_fournisseur = '';
3054
3055
            return 0;
3056
        }
3057
    }
3058
3059
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3060
3061
    /**
3062
     *    Add link to sales representative
3063
     *
3064
     * @param User $user Object user
3065
     * @param int $commid Id of user
3066
     * @return    void
3067
     */
3068
    function add_commercial(User $user, $commid)
3069
    {
3070
        // phpcs:enable
3071
        $error = 0;
3072
3073
3074
        if ($this->id > 0 && $commid > 0) {
3075
            $sql = "DELETE FROM  " . MAIN_DB_PREFIX . "societe_commerciaux";
3076
            $sql .= " WHERE fk_soc = " . $this->id . " AND fk_user =" . $commid;
3077
3078
            $this->db->query($sql);
3079
3080
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_commerciaux";
3081
            $sql .= " ( fk_soc, fk_user )";
3082
            $sql .= " VALUES (" . $this->id . "," . $commid . ")";
3083
3084
            if (!$this->db->query($sql)) {
3085
                dol_syslog(get_class($this) . "::add_commercial Erreur");
3086
            } else {
3087
                $this->context = array('commercial_modified' => $commid);
3088
3089
                $result = $this->call_trigger('COMPANY_LINK_SALE_REPRESENTATIVE', $user);
3090
                if ($result < 0)
3091
                    $error++;
3092
            }
3093
        }
3094
    }
3095
3096
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3097
3098
    /**
3099
     *    Set properties with value into $conf
3100
     *
3101
     * @param Conf $conf Conf object (possibility to use another entity)
3102
     * @return    void
3103
     */
3104
    function setMysoc(Conf $conf)
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Conf was not found. Did you mean Conf? If so, make sure to prefix the type with \.
Loading history...
3105
    {
3106
        global $langs;
3107
3108
        $this->id = 0;
3109
        $this->name = empty($conf->global->MAIN_INFO_SOCIETE_NOM) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOM;
3110
        $this->address = empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS) ? '' : $conf->global->MAIN_INFO_SOCIETE_ADDRESS;
3111
        $this->zip = empty($conf->global->MAIN_INFO_SOCIETE_ZIP) ? '' : $conf->global->MAIN_INFO_SOCIETE_ZIP;
3112
        $this->town = empty($conf->global->MAIN_INFO_SOCIETE_TOWN) ? '' : $conf->global->MAIN_INFO_SOCIETE_TOWN;
3113
        $this->state_id = empty($conf->global->MAIN_INFO_SOCIETE_STATE) ? '' : $conf->global->MAIN_INFO_SOCIETE_STATE;
0 ignored issues
show
Documentation Bug introduced by
It seems like empty($conf->global->MAI...MAIN_INFO_SOCIETE_STATE can also be of type string. However, the property $state_id is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
3114
        $this->region_code = empty($conf->global->MAIN_INFO_SOCIETE_REGION) ? '' : $conf->global->MAIN_INFO_SOCIETE_REGION;
0 ignored issues
show
Documentation Bug introduced by
It seems like empty($conf->global->MAI...AIN_INFO_SOCIETE_REGION can also be of type string. However, the property $region_code is declared as type integer. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
3115
        $this->object = empty($conf->global->MAIN_INFO_SOCIETE_OBJECT) ? '' : $conf->global->MAIN_INFO_SOCIETE_OBJECT;
3116
3117
        $this->note_private = empty($conf->global->MAIN_INFO_SOCIETE_NOTE) ? '' : $conf->global->MAIN_INFO_SOCIETE_NOTE;
3118
3119
        $this->nom = $this->name;          // deprecated
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

3119
        /** @scrutinizer ignore-deprecated */ $this->nom = $this->name;          // deprecated

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3120
        // We define country_id, country_code and country
3121
        $country_id = $country_code = $country_label = '';
3122
        if (!empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY)) {
3123
            $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_COUNTRY);
3124
            $country_id = $tmp[0];
3125
            if (!empty($tmp[1])) {   // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
3126
                $country_code = $tmp[1];
3127
                $country_label = $tmp[2];
3128
            } else {                    // For backward compatibility
3129
                dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
3130
                include_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
3131
                $country_code = getCountry($country_id, 2, $this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3132
                $country_label = getCountry($country_id, 0, $this->db);  // This need a SQL request, but it's the old feature that should not be used anymore
3133
            }
3134
        }
3135
        $this->country_id = $country_id;
0 ignored issues
show
Documentation Bug introduced by
The property $country_id was declared of type integer, but $country_id is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
3136
        $this->country_code = $country_code;
3137
        $this->country = $country_label;
3138
        if (is_object($langs))
3139
            $this->country = ($langs->trans('Country' . $country_code) != 'Country' . $country_code) ? $langs->trans('Country' . $country_code) : $country_label;
3140
3141
        $this->phone = empty($conf->global->MAIN_INFO_SOCIETE_TEL) ? '' : $conf->global->MAIN_INFO_SOCIETE_TEL;
3142
        $this->fax = empty($conf->global->MAIN_INFO_SOCIETE_FAX) ? '' : $conf->global->MAIN_INFO_SOCIETE_FAX;
3143
        $this->url = empty($conf->global->MAIN_INFO_SOCIETE_WEB) ? '' : $conf->global->MAIN_INFO_SOCIETE_WEB;
3144
        // Id prof generiques
3145
        $this->idprof1 = empty($conf->global->MAIN_INFO_SIREN) ? '' : $conf->global->MAIN_INFO_SIREN;
3146
        $this->idprof2 = empty($conf->global->MAIN_INFO_SIRET) ? '' : $conf->global->MAIN_INFO_SIRET;
3147
        $this->idprof3 = empty($conf->global->MAIN_INFO_APE) ? '' : $conf->global->MAIN_INFO_APE;
3148
        $this->idprof4 = empty($conf->global->MAIN_INFO_RCS) ? '' : $conf->global->MAIN_INFO_RCS;
3149
        $this->idprof5 = empty($conf->global->MAIN_INFO_PROFID5) ? '' : $conf->global->MAIN_INFO_PROFID5;
3150
        $this->idprof6 = empty($conf->global->MAIN_INFO_PROFID6) ? '' : $conf->global->MAIN_INFO_PROFID6;
3151
        $this->tva_intra = empty($conf->global->MAIN_INFO_TVAINTRA) ? '' : $conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
3152
        $this->managers = empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS) ? '' : $conf->global->MAIN_INFO_SOCIETE_MANAGERS;
3153
        $this->capital = empty($conf->global->MAIN_INFO_CAPITAL) ? '' : $conf->global->MAIN_INFO_CAPITAL;
3154
        $this->forme_juridique_code = empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE) ? '' : $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
3155
        $this->email = empty($conf->global->MAIN_INFO_SOCIETE_MAIL) ? '' : $conf->global->MAIN_INFO_SOCIETE_MAIL;
3156
        $this->logo = empty($conf->global->MAIN_INFO_SOCIETE_LOGO) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO;
3157
        $this->logo_small = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
3158
        $this->logo_mini = empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI) ? '' : $conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
3159
3160
        // Define if company use vat or not
3161
        $this->tva_assuj = $conf->global->FACTURE_TVAOPTION;
3162
3163
        // Define if company use local taxes
3164
        $this->localtax1_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION == 'localtax1on')) ? 1 : 0);
3165
        $this->localtax2_assuj = ((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION == '1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION == 'localtax2on')) ? 1 : 0);
3166
    }
3167
3168
    /**
3169
     *  Initialise an instance with random values.
3170
     *  Used to build previews or test instances.
3171
     *    id must be 0 if object instance is a specimen.
3172
     *
3173
     * @return    void
3174
     */
3175
    function initAsSpecimen()
3176
    {
3177
        $now = dol_now();
3178
3179
        // Initialize parameters
3180
        $this->id = 0;
3181
        $this->name = 'THIRDPARTY SPECIMEN ' . dol_print_date($now, 'dayhourlog');
3182
        $this->nom = $this->name;   // For backward compatibility
0 ignored issues
show
Deprecated Code introduced by
The property Alixar\Models\Company::$nom has been deprecated: Use $name instead ( Ignorable by Annotation )

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

3182
        /** @scrutinizer ignore-deprecated */ $this->nom = $this->name;   // For backward compatibility

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3183
        $this->ref_ext = 'Ref ext';
3184
        $this->specimen = 1;
3185
        $this->address = '21 jump street';
3186
        $this->zip = '99999';
3187
        $this->town = 'MyTown';
3188
        $this->state_id = 1;
3189
        $this->state_code = 'AA';
3190
        $this->state = 'MyState';
3191
        $this->country_id = 1;
3192
        $this->country_code = 'FR';
3193
        $this->email = '[email protected]';
3194
        $this->skype = 'tom.hanson';
3195
        $this->twitter = 'tomhanson';
3196
        $this->facebook = 'tomhanson';
3197
        $this->url = 'http://www.specimen.com';
3198
3199
        $this->phone = '0909090901';
3200
        $this->fax = '0909090909';
3201
3202
        $this->code_client = 'CC-' . dol_print_date($now, 'dayhourlog');
3203
        $this->code_fournisseur = 'SC-' . dol_print_date($now, 'dayhourlog');
3204
        $this->capital = 10000;
3205
        $this->client = 1;
3206
        $this->prospect = 1;
3207
        $this->fournisseur = 1;
3208
        $this->tva_assuj = 1;
3209
        $this->tva_intra = 'EU1234567';
3210
        $this->note_public = 'This is a comment (public)';
3211
        $this->note_private = 'This is a comment (private)';
3212
3213
        $this->idprof1 = 'idprof1';
3214
        $this->idprof2 = 'idprof2';
3215
        $this->idprof3 = 'idprof3';
3216
        $this->idprof4 = 'idprof4';
3217
        $this->idprof5 = 'idprof5';
3218
        $this->idprof6 = 'idprof6';
3219
    }
3220
3221
    /**
3222
     *  Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
3223
     *
3224
     * @param int $localTaxNum To get info for only localtax1 or localtax2
3225
     * @return        boolean                    true or false
3226
     */
3227
    function useLocalTax($localTaxNum = 0)
3228
    {
3229
        $sql = "SELECT t.localtax1, t.localtax2";
3230
        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
3231
        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $this->db->escape($this->country_code) . "'";
3232
        $sql .= " AND t.active = 1";
3233
        if (empty($localTaxNum))
3234
            $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
3235
        elseif ($localTaxNum == 1)
3236
            $sql .= " AND t.localtax1_type <> '0'";
3237
        elseif ($localTaxNum == 2)
3238
            $sql .= " AND t.localtax2_type <> '0'";
3239
3240
        dol_syslog("useLocalTax", LOG_DEBUG);
3241
        $resql = $this->db->query($sql);
3242
        if ($resql) {
3243
            return ($this->db->num_rows($resql) > 0);
3244
        } else
3245
            return false;
3246
    }
3247
3248
    /**
3249
     *  Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
3250
     *
3251
     * @return        boolean                    true or false
3252
     */
3253
    function useNPR()
3254
    {
3255
        $sql = "SELECT t.rowid";
3256
        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
3257
        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $this->db->escape($this->country_code) . "'";
3258
        $sql .= " AND t.active = 1 AND t.recuperableonly = 1";
3259
3260
        dol_syslog("useNPR", LOG_DEBUG);
3261
        $resql = $this->db->query($sql);
3262
        if ($resql) {
3263
            return ($this->db->num_rows($resql) > 0);
3264
        } else
3265
            return false;
3266
    }
3267
3268
    /**
3269
     *  Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
3270
     *
3271
     * @return        boolean            true or false
3272
     */
3273
    function useRevenueStamp()
3274
    {
3275
        $sql = "SELECT COUNT(*) as nb";
3276
        $sql .= " FROM " . MAIN_DB_PREFIX . "c_revenuestamp as r, " . MAIN_DB_PREFIX . "c_country as c";
3277
        $sql .= " WHERE r.fk_pays = c.rowid AND c.code = '" . $this->db->escape($this->country_code) . "'";
3278
        $sql .= " AND r.active = 1";
3279
3280
        dol_syslog("useRevenueStamp", LOG_DEBUG);
3281
        $resql = $this->db->query($sql);
3282
        if ($resql) {
3283
            $obj = $this->db->fetch_object($resql);
3284
            return (($obj->nb > 0) ? true : false);
3285
        } else {
3286
            $this->error = $this->db->lasterror();
3287
            return false;
3288
        }
3289
    }
3290
3291
    /**
3292
     *    Return prostect level
3293
     *
3294
     * @return     string        Libelle
3295
     */
3296
    function getLibProspLevel()
3297
    {
3298
        return $this->LibProspLevel($this->fk_prospectlevel);
3299
    }
3300
3301
    /**
3302
     *  Return label of prospect level
3303
     *
3304
     * @param int $fk_prospectlevel Prospect level
3305
     * @return string                            label of level
3306
     */
3307
    function LibProspLevel($fk_prospectlevel)
3308
    {
3309
        // phpcs:enable
3310
        global $langs;
3311
3312
        $lib = $langs->trans("ProspectLevel" . $fk_prospectlevel);
3313
        // If lib not found in language file, we get label from cache/databse
3314
        if ($lib == $langs->trans("ProspectLevel" . $fk_prospectlevel)) {
3315
            $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label');
3316
        }
3317
        return $lib;
3318
    }
3319
3320
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3321
3322
    /**
3323
     *  Set prospect level
3324
     *
3325
     * @param User $user Utilisateur qui definie la remise
3326
     * @return    int                    <0 if KO, >0 if OK
3327
     * @deprecated Use update function instead
3328
     */
3329
    function set_prospect_level(User $user)
3330
    {
3331
        // phpcs:enable
3332
        return $this->update($this->id, $user);
3333
    }
3334
3335
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3336
3337
    /**
3338
     *  Return status of prospect
3339
     *
3340
     * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
3341
     * @param string $label Label to use for status for added status
3342
     * @return string                Libelle
3343
     */
3344
    function getLibProspCommStatut($mode = 0, $label = '')
3345
    {
3346
        return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
3347
    }
3348
3349
    /**
3350
     *  Return label of a given status
3351
     *
3352
     * @param int|string $statut Id or code for prospection status
3353
     * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
3354
     * @param string $label Label to use for status for added status
3355
     * @return string                    Libelle du statut
3356
     */
3357
    function LibProspCommStatut($statut, $mode = 0, $label = '')
3358
    {
3359
        // phpcs:enable
3360
        global $langs;
3361
        $langs->load('customers');
3362
3363
        if ($mode == 2) {
3364
            if ($statut == '-1' || $statut == 'ST_NO')
3365
                return img_action($langs->trans("StatusProspect-1"), -1) . ' ' . $langs->trans("StatusProspect-1");
3366
            elseif ($statut == '0' || $statut == 'ST_NEVER')
3367
                return img_action($langs->trans("StatusProspect0"), 0) . ' ' . $langs->trans("StatusProspect0");
3368
            elseif ($statut == '1' || $statut == 'ST_TODO')
3369
                return img_action($langs->trans("StatusProspect1"), 1) . ' ' . $langs->trans("StatusProspect1");
3370
            elseif ($statut == '2' || $statut == 'ST_PEND')
3371
                return img_action($langs->trans("StatusProspect2"), 2) . ' ' . $langs->trans("StatusProspect2");
3372
            elseif ($statut == '3' || $statut == 'ST_DONE')
3373
                return img_action($langs->trans("StatusProspect3"), 3) . ' ' . $langs->trans("StatusProspect3");
3374
            else {
3375
                return img_action(($langs->trans("StatusProspect" . $statut) != "StatusProspect" . $statut) ? $langs->trans("StatusProspect" . $statut) : $label, 0) . ' ' . (($langs->trans("StatusProspect" . $statut) != "StatusProspect" . $statut) ? $langs->trans("StatusProspect" . $statut) : $label);
3376
            }
3377
        }
3378
        if ($mode == 3) {
3379
            if ($statut == '-1' || $statut == 'ST_NO')
3380
                return img_action($langs->trans("StatusProspect-1"), -1);
3381
            elseif ($statut == '0' || $statut == 'ST_NEVER')
3382
                return img_action($langs->trans("StatusProspect0"), 0);
3383
            elseif ($statut == '1' || $statut == 'ST_TODO')
3384
                return img_action($langs->trans("StatusProspect1"), 1);
3385
            elseif ($statut == '2' || $statut == 'ST_PEND')
3386
                return img_action($langs->trans("StatusProspect2"), 2);
3387
            elseif ($statut == '3' || $statut == 'ST_DONE')
3388
                return img_action($langs->trans("StatusProspect3"), 3);
3389
            else {
3390
                return img_action(($langs->trans("StatusProspect" . $statut) != "StatusProspect" . $statut) ? $langs->trans("StatusProspect" . $statut) : $label, 0);
3391
            }
3392
        }
3393
        if ($mode == 4) {
3394
            if ($statut == '-1' || $statut == 'ST_NO')
3395
                return img_action($langs->trans("StatusProspect-1"), -1) . ' ' . $langs->trans("StatusProspect-1");
3396
            elseif ($statut == '0' || $statut == 'ST_NEVER')
3397
                return img_action($langs->trans("StatusProspect0"), 0) . ' ' . $langs->trans("StatusProspect0");
3398
            elseif ($statut == '1' || $statut == 'ST_TODO')
3399
                return img_action($langs->trans("StatusProspect1"), 1) . ' ' . $langs->trans("StatusProspect1");
3400
            elseif ($statut == '2' || $statut == 'ST_PEND')
3401
                return img_action($langs->trans("StatusProspect2"), 2) . ' ' . $langs->trans("StatusProspect2");
3402
            elseif ($statut == '3' || $statut == 'ST_DONE')
3403
                return img_action($langs->trans("StatusProspect3"), 3) . ' ' . $langs->trans("StatusProspect3");
3404
            else {
3405
                return img_action(($langs->trans("StatusProspect" . $statut) != "StatusProspect" . $statut) ? $langs->trans("StatusProspect" . $statut) : $label, 0) . ' ' . (($langs->trans("StatusProspect" . $statut) != "StatusProspect" . $statut) ? $langs->trans("StatusProspect" . $statut) : $label);
3406
            }
3407
        }
3408
3409
        return "Error, mode/status not found";
3410
    }
3411
3412
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3413
3414
    /**
3415
     *  Set outstanding value
3416
     *
3417
     * @param User $user User making change
3418
     * @return    int                    <0 if KO, >0 if OK
3419
     * @deprecated Use update function instead
3420
     */
3421
    function set_OutstandingBill(User $user)
3422
    {
3423
        // phpcs:enable
3424
        return $this->update($this->id, $user);
3425
    }
3426
3427
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3428
3429
    /**
3430
     *  Return amount of order not paid and total
3431
     *
3432
     * @param string $mode 'customer' or 'supplier'
3433
     * @return    array                array('opened'=>Amount, 'total'=>Total amount)
3434
     */
3435
    function getOutstandingProposals($mode = 'customer')
3436
    {
3437
        $table = 'propal';
3438
        if ($mode == 'supplier')
3439
            $table = 'supplier_proposal';
3440
3441
        $sql = "SELECT rowid, total_ht, total as total_ttc, fk_statut FROM " . MAIN_DB_PREFIX . $table . " as f";
3442
        $sql .= " WHERE fk_soc = " . $this->id;
3443
        if ($mode == 'supplier') {
3444
            $sql .= " AND entity IN (" . getEntity('supplier_proposal') . ")";
3445
        } else {
3446
            $sql .= " AND entity IN (" . getEntity('propal') . ")";
3447
        }
3448
3449
        dol_syslog("getOutstandingProposals", LOG_DEBUG);
3450
        $resql = $this->db->query($sql);
3451
        if ($resql) {
3452
            $outstandingOpened = 0;
3453
            $outstandingTotal = 0;
3454
            $outstandingTotalIncTax = 0;
3455
            while ($obj = $this->db->fetch_object($resql)) {
3456
                $outstandingTotal += $obj->total_ht;
3457
                $outstandingTotalIncTax += $obj->total_ttc;
3458
                if ($obj->fk_statut != 0) {    // Not a draft
3459
                    $outstandingOpened += $obj->total_ttc;
3460
                }
3461
            }
3462
            return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax); // 'opened' is 'incl taxes'
3463
        } else
3464
            return array();
3465
    }
3466
3467
    /**
3468
     *  Return amount of order not paid and total
3469
     *
3470
     * @param string $mode 'customer' or 'supplier'
3471
     * @return        array                array('opened'=>Amount, 'total'=>Total amount)
3472
     */
3473
    function getOutstandingOrders($mode = 'customer')
3474
    {
3475
        $table = 'commande';
3476
        if ($mode == 'supplier')
3477
            $table = 'commande_fournisseur';
3478
3479
        $sql = "SELECT rowid, total_ht, total_ttc, fk_statut FROM " . MAIN_DB_PREFIX . $table . " as f";
3480
        $sql .= " WHERE fk_soc = " . $this->id;
3481
        if ($mode == 'supplier') {
3482
            $sql .= " AND entity IN (" . getEntity('supplier_order') . ")";
3483
        } else {
3484
            $sql .= " AND entity IN (" . getEntity('commande') . ")";
3485
        }
3486
3487
        dol_syslog("getOutstandingOrders", LOG_DEBUG);
3488
        $resql = $this->db->query($sql);
3489
        if ($resql) {
3490
            $outstandingOpened = 0;
3491
            $outstandingTotal = 0;
3492
            $outstandingTotalIncTax = 0;
3493
            while ($obj = $this->db->fetch_object($resql)) {
3494
                $outstandingTotal += $obj->total_ht;
3495
                $outstandingTotalIncTax += $obj->total_ttc;
3496
                if ($obj->fk_statut != 0) {    // Not a draft
3497
                    $outstandingOpened += $obj->total_ttc;
3498
                }
3499
            }
3500
            return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax); // 'opened' is 'incl taxes'
3501
        } else
3502
            return array();
3503
    }
3504
3505
    /**
3506
     *  Return amount of bill not paid and total
3507
     *
3508
     * @param string $mode 'customer' or 'supplier'
3509
     * @return        array                array('opened'=>Amount, 'total'=>Total amount)
3510
     */
3511
    function getOutstandingBills($mode = 'customer')
3512
    {
3513
        $table = 'facture';
3514
        if ($mode == 'supplier')
3515
            $table = 'facture_fourn';
3516
3517
        /* Accurate value of remain to pay is to sum remaintopay for each invoice
3518
          $paiement = $invoice->getSommePaiement();
3519
          $creditnotes=$invoice->getSumCreditNotesUsed();
3520
          $deposits=$invoice->getSumDepositsUsed();
3521
          $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3522
          $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3523
         */
3524
        if ($mode == 'supplier')
3525
            $sql = "SELECT rowid, total_ht as total_ht, total_ttc, paye, fk_statut, close_code FROM " . MAIN_DB_PREFIX . $table . " as f";
3526
        else
3527
            $sql = "SELECT rowid, total as total_ht, total_ttc, paye, fk_statut, close_code FROM " . MAIN_DB_PREFIX . $table . " as f";
3528
        $sql .= " WHERE fk_soc = " . $this->id;
3529
        if ($mode == 'supplier') {
3530
            $sql .= " AND entity IN (" . getEntity('facture_fourn') . ")";
3531
        } else {
3532
            $sql .= " AND entity IN (" . getEntity('invoice') . ")";
3533
        }
3534
3535
        dol_syslog("getOutstandingBills", LOG_DEBUG);
3536
        $resql = $this->db->query($sql);
3537
        if ($resql) {
3538
            $outstandingOpened = 0;
3539
            $outstandingTotal = 0;
3540
            $outstandingTotalIncTax = 0;
3541
            if ($mode == 'supplier') {
3542
                require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
3543
                $tmpobject = new FactureFournisseur($this->db);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\FactureFournisseur was not found. Did you mean FactureFournisseur? If so, make sure to prefix the type with \.
Loading history...
3544
            } else {
3545
                require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
3546
                $tmpobject = new Facture($this->db);
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Facture was not found. Did you mean Facture? If so, make sure to prefix the type with \.
Loading history...
3547
            }
3548
            while ($obj = $this->db->fetch_object($resql)) {
3549
                $tmpobject->id = $obj->rowid;
3550
                if ($obj->fk_statut != 0                                           // Not a draft
3551
                    && !($obj->fk_statut == 3 && $obj->close_code == 'replaced')  // Not a replaced invoice
3552
                ) {
3553
                    $outstandingTotal += $obj->total_ht;
3554
                    $outstandingTotalIncTax += $obj->total_ttc;
3555
                }
3556
                if ($obj->paye == 0 && $obj->fk_statut != 0    // Not a draft
3557
                    && $obj->fk_statut != 3    // Not abandonned
3558
                    && $obj->fk_statut != 2) {   // Not classified as paid
3559
                    //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3560
                    $paiement = $tmpobject->getSommePaiement();
3561
                    $creditnotes = $tmpobject->getSumCreditNotesUsed();
3562
                    $deposits = $tmpobject->getSumDepositsUsed();
3563
                    $outstandingOpened += $obj->total_ttc - $paiement - $creditnotes - $deposits;
3564
                }
3565
            }
3566
            return array('opened' => $outstandingOpened, 'total_ht' => $outstandingTotal, 'total_ttc' => $outstandingTotalIncTax); // 'opened' is 'incl taxes'
3567
        } else {
3568
            return array();
3569
        }
3570
    }
3571
3572
    /**
3573
     *  Return amount of bill not paid
3574
     *
3575
     * @return        int                Amount in debt for thirdparty
3576
     * @deprecated
3577
     * @see getOutstandingBills()
3578
     */
3579
    function get_OutstandingBill()
3580
    {
3581
        // phpcs:enable
3582
        /* Accurate value of remain to pay is to sum remaintopay for each invoice
3583
          $paiement = $invoice->getSommePaiement();
3584
          $creditnotes=$invoice->getSumCreditNotesUsed();
3585
          $deposits=$invoice->getSumDepositsUsed();
3586
          $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
3587
          $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
3588
         */
3589
        $sql = "SELECT rowid, total_ttc FROM " . MAIN_DB_PREFIX . "facture as f";
3590
        $sql .= " WHERE fk_soc = " . $this->id;
3591
        $sql .= " AND paye = 0";
3592
        $sql .= " AND fk_statut <> 0"; // Not a draft
3593
        //$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')";		// Not abandonned for undefined reason
3594
        $sql .= " AND fk_statut <> 3";  // Not abandonned
3595
        $sql .= " AND fk_statut <> 2";  // Not clasified as paid
3596
3597
        dol_syslog("get_OutstandingBill", LOG_DEBUG);
3598
        $resql = $this->db->query($sql);
3599
        if ($resql) {
3600
            $outstandingAmount = 0;
3601
            require_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
3602
            $tmpobject = new Facture($this->db);
3603
            while ($obj = $this->db->fetch_object($resql)) {
3604
                $tmpobject->id = $obj->rowid;
3605
                $paiement = $tmpobject->getSommePaiement();
3606
                $creditnotes = $tmpobject->getSumCreditNotesUsed();
3607
                $deposits = $tmpobject->getSumDepositsUsed();
3608
                $outstandingAmount += $obj->total_ttc - $paiement - $creditnotes - $deposits;
3609
            }
3610
            return $outstandingAmount;
3611
        } else
3612
            return 0;
3613
    }
3614
3615
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3616
3617
    /**
3618
     * Return label of status customer is prospect/customer
3619
     *
3620
     * @return   string            Label
3621
     */
3622
    function getLibCustProspStatut()
3623
    {
3624
        return $this->LibCustProspStatut($this->client);
3625
    }
3626
3627
    /**
3628
     *  Renvoi le libelle d'un statut donne
3629
     *
3630
     * @param int $statut Id statut
3631
     * @return    string                Libelle du statut
3632
     */
3633
    function LibCustProspStatut($statut)
3634
    {
3635
        // phpcs:enable
3636
        global $langs;
3637
        $langs->load('companies');
3638
3639
        if ($statut == 0)
3640
            return $langs->trans("NorProspectNorCustomer");
3641
        if ($statut == 1)
3642
            return $langs->trans("Customer");
3643
        if ($statut == 2)
3644
            return $langs->trans("Prospect");
3645
        if ($statut == 3)
3646
            return $langs->trans("ProspectCustomer");
3647
    }
3648
3649
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3650
3651
    /**
3652
     *  Create a document onto disk according to template module.
3653
     *
3654
     * @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
3655
     * @param Translate $outputlangs objet lang a utiliser pour traduction
0 ignored issues
show
Bug introduced by
The type Alixar\Models\Translate was not found. Did you mean Translate? If so, make sure to prefix the type with \.
Loading history...
3656
     * @param int $hidedetails Hide details of lines
3657
     * @param int $hidedesc Hide description
3658
     * @param int $hideref Hide ref
3659
     * @param null|array $moreparams Array to provide more information
3660
     * @return int                            <0 if KO, >0 if OK
3661
     */
3662
    public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
3663
    {
3664
        global $conf, $user, $langs;
3665
3666
        if (!empty($moreparams) && !empty($moreparams['use_companybankid'])) {
3667
            $modelpath = "core/modules/bank/doc/";
3668
3669
            include_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
3670
            $companybankaccount = new CompanyBankAccount($this->db);
3671
            $result = $companybankaccount->fetch($moreparams['use_companybankid']);
3672
            if (!$result)
3673
                dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
3674
            $result = $companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3675
        } else {
3676
            // Positionne le modele sur le nom du modele a utiliser
3677
            if (!dol_strlen($modele)) {
3678
                if (!empty($conf->global->COMPANY_ADDON_PDF)) {
3679
                    $modele = $conf->global->COMPANY_ADDON_PDF;
3680
                } else {
3681
                    print $langs->trans("Error") . " " . $langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
3682
                    return 0;
3683
                }
3684
            }
3685
3686
            $modelpath = "core/modules/societe/doc/";
3687
3688
            $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
3689
        }
3690
3691
        return $result;
3692
    }
3693
3694
    /**
3695
     * Sets object to supplied categories.
3696
     *
3697
     * Deletes object from existing categories not supplied.
3698
     * Adds it to non existing supplied categories.
3699
     * Existing categories are left untouch.
3700
     *
3701
     * @param int[]|int $categories Category ID or array of Categories IDs
3702
     * @param string $type Category type ('customer' or 'supplier')
3703
     * @return    int                            <0 if KO, >0 if OK
3704
     */
3705
    public function setCategories($categories, $type)
3706
    {
3707
        require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
3708
3709
        // Decode type
3710
        if ($type == 'customer') {
3711
            $type_id = Categorie::TYPE_CUSTOMER;
3712
            $type_text = 'customer';
3713
        } elseif ($type == 'supplier') {
3714
            $type_id = Categorie::TYPE_SUPPLIER;
3715
            $type_text = 'supplier';
3716
        } else {
3717
            dol_syslog(__METHOD__ . ': Type ' . $type . 'is an unknown company category type. Done nothing.', LOG_ERR);
3718
            return -1;
3719
        }
3720
3721
        // Handle single category
3722
        if (!is_array($categories)) {
3723
            $categories = array($categories);
3724
        }
3725
3726
        // Get current categories
3727
        $c = new Categorie($this->db);
3728
        $existing = $c->containing($this->id, $type_id, 'id');
3729
3730
        // Diff
3731
        if (is_array($existing)) {
3732
            $to_del = array_diff($existing, $categories);
3733
            $to_add = array_diff($categories, $existing);
3734
        } else {
3735
            $to_del = array(); // Nothing to delete
3736
            $to_add = $categories;
3737
        }
3738
3739
        $error = 0;
3740
3741
        // Process
3742
        foreach ($to_del as $del) {
3743
            if ($c->fetch($del) > 0) {
3744
                $c->del_type($this, $type_text);
3745
            }
3746
        }
3747
        foreach ($to_add as $add) {
3748
            if ($c->fetch($add) > 0) {
3749
                $result = $c->add_type($this, $type_text);
3750
                if ($result < 0) {
3751
                    $error++;
3752
                    $this->error = $c->error;
3753
                    $this->errors = $c->errors;
3754
                    break;
3755
                }
3756
            }
3757
        }
3758
3759
        return $error ? -1 : 1;
3760
    }
3761
3762
    /**
3763
     * Sets sales representatives of the thirdparty
3764
     *
3765
     * @param int[]|int $salesrep User ID or array of user IDs
3766
     * @return    int                            <0 if KO, >0 if OK
3767
     */
3768
    public function setSalesRep($salesrep)
3769
    {
3770
        global $user;
3771
3772
        // Handle single user
3773
        if (!is_array($salesrep)) {
3774
            $salesrep = array($salesrep);
3775
        }
3776
3777
        // Get current users
3778
        $existing = $this->getSalesRepresentatives($user, 1);
3779
3780
        // Diff
3781
        if (is_array($existing)) {
3782
            $to_del = array_diff($existing, $salesrep);
3783
            $to_add = array_diff($salesrep, $existing);
3784
        } else {
3785
            $to_del = array(); // Nothing to delete
3786
            $to_add = $salesrep;
3787
        }
3788
3789
        $error = 0;
3790
3791
        // Process
3792
        foreach ($to_del as $del) {
3793
            $this->del_commercial($user, $del);
3794
        }
3795
        foreach ($to_add as $add) {
3796
            $result = $this->add_commercial($user, $add);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $result is correct as $this->add_commercial($user, $add) targeting Alixar\Models\Company::add_commercial() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
3797
            if ($result < 0) {
3798
                $error++;
3799
                $this->error = $c->error;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $c seems to be never defined.
Loading history...
3800
                $this->errors = $c->errors;
3801
                break;
3802
            }
3803
        }
3804
3805
        return $error ? -1 : 1;
3806
    }
3807
3808
    /**
3809
     *  Return array of sales representatives
3810
     *
3811
     * @param User $user Object user
3812
     * @param int $mode 0=Array with properties, 1=Array of id.
3813
     * @return array            Array of sales representatives of third party
3814
     */
3815
    function getSalesRepresentatives(User $user, $mode = 0)
3816
    {
3817
        global $conf;
3818
3819
        $reparray = array();
3820
3821
        $sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
3822
        $sql .= " FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc, " . MAIN_DB_PREFIX . "user as u";
3823
        if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
3824
            $sql .= ", " . MAIN_DB_PREFIX . "usergroup_user as ug";
3825
            $sql .= " WHERE ((ug.fk_user = sc.fk_user";
3826
            $sql .= " AND ug.entity = " . $conf->entity . ")";
3827
            $sql .= " OR u.admin = 1)";
3828
        } else
3829
            $sql .= " WHERE entity in (0, " . $conf->entity . ")";
3830
3831
        $sql .= " AND u.rowid = sc.fk_user AND sc.fk_soc = " . $this->id;
3832
3833
        $resql = $this->db->query($sql);
3834
        if ($resql) {
3835
            $num = $this->db->num_rows($resql);
3836
            $i = 0;
3837
            while ($i < $num) {
3838
                $obj = $this->db->fetch_object($resql);
3839
3840
                if (empty($mode)) {
3841
                    $reparray[$i]['id'] = $obj->rowid;
3842
                    $reparray[$i]['lastname'] = $obj->lastname;
3843
                    $reparray[$i]['firstname'] = $obj->firstname;
3844
                    $reparray[$i]['email'] = $obj->email;
3845
                    $reparray[$i]['statut'] = $obj->statut;
3846
                    $reparray[$i]['entity'] = $obj->entity;
3847
                    $reparray[$i]['login'] = $obj->login;
3848
                    $reparray[$i]['photo'] = $obj->photo;
3849
                } else {
3850
                    $reparray[] = $obj->rowid;
3851
                }
3852
                $i++;
3853
            }
3854
            return $reparray;
3855
        } else {
3856
            dol_print_error($this->db);
3857
            return -1;
3858
        }
3859
    }
3860
3861
    /**
3862
     *    Add link to sales representative
3863
     *
3864
     * @param User $user Object user
3865
     * @param int $commid Id of user
3866
     * @return    void
3867
     */
3868
    function del_commercial(User $user, $commid)
3869
    {
3870
        // phpcs:enable
3871
        $error = 0;
3872
        $this->context = array('commercial_modified' => $commid);
3873
3874
        $result = $this->call_trigger('COMPANY_UNLINK_SALE_REPRESENTATIVE', $user);
3875
        if ($result < 0)
3876
            $error++;
3877
3878
        if ($this->id > 0 && $commid > 0) {
3879
            $sql = "DELETE FROM  " . MAIN_DB_PREFIX . "societe_commerciaux ";
3880
            $sql .= " WHERE fk_soc = " . $this->id . " AND fk_user =" . $commid;
3881
3882
            if (!$this->db->query($sql)) {
3883
                dol_syslog(get_class($this) . "::del_commercial Erreur");
3884
            }
3885
        }
3886
    }
3887
}