Company::fetch()   F
last analyzed

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 221
Code Lines 171

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 37
eloc 171
nc 2121729
nop 12
dl 0
loc 221
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

Long Method

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

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

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

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 alxarafe
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 alxarafe
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 alxarafe
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 alxarafe
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 alxarafe
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 alxarafe
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 alxarafe
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 alxarafe
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 alxarafe
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))