-
Notifications
You must be signed in to change notification settings - Fork 246
/
Cliente.php
336 lines (289 loc) · 10.4 KB
/
Cliente.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<?php
/**
* This file is part of FacturaScripts
* Copyright (C) 2013-2023 Carlos Garcia Gomez <carlos@facturascripts.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace FacturaScripts\Core\Model;
use FacturaScripts\Core\Base\DataBase\DataBaseWhere;
use FacturaScripts\Core\DataSrc\Paises;
use FacturaScripts\Core\Lib\Vies;
use FacturaScripts\Core\Tools;
use FacturaScripts\Dinamic\Model\Contacto as DinContacto;
use FacturaScripts\Dinamic\Model\CuentaBancoCliente as DinCuentaBancoCliente;
use FacturaScripts\Dinamic\Model\CuentaEspecial as DinCuentaEspecial;
use FacturaScripts\Dinamic\Model\GrupoClientes as DinGrupoClientes;
use FacturaScripts\Dinamic\Model\Subcuenta as DinSubcuenta;
/**
* The client. You can have one or more associated addresses and accounts.
*
* @author Carlos García Gómez <carlos@facturascripts.com>
*/
class Cliente extends Base\ComercialContact
{
use Base\ModelTrait;
const SPECIAL_ACCOUNT = 'CLIENT';
/** @var string */
public $codagente;
/** @var string */
public $codgrupo;
/** @var string */
public $codtarifa;
/** @var string */
public $diaspago;
/** @var integer */
public $idcontactoenv;
/** @var integer */
public $idcontactofact;
/** @var float */
public $riesgoalcanzado;
/** @var float */
public $riesgomax;
public function checkVies(): bool
{
$codiso = Paises::get($this->getDefaultAddress()->codpais)->codiso ?? '';
return Vies::check($this->cifnif ?? '', $codiso) === 1;
}
public function clear()
{
parent::clear();
$this->codretencion = Tools::settings('default', 'codretencion');
}
/**
* @param string $query
* @param string $fieldCode
* @param DataBaseWhere[] $where
*
* @return CodeModel[]
*/
public function codeModelSearch(string $query, string $fieldCode = '', array $where = []): array
{
$field = empty($fieldCode) ? $this->primaryColumn() : $fieldCode;
$fields = 'cifnif|codcliente|email|nombre|observaciones|razonsocial|telefono1|telefono2';
$where[] = new DataBaseWhere($fields, mb_strtolower($query, 'UTF8'), 'LIKE');
$where[] = new DataBaseWhere('fechabaja', null, 'IS');
return CodeModel::all($this->tableName(), $field, $this->primaryDescriptionColumn(), false, $where);
}
/**
* Returns an array with the addresses associated with this customer.
*
* @return DinContacto[]
*/
public function getAddresses(): array
{
$contactModel = new DinContacto();
$where = [new DataBaseWhere($this->primaryColumn(), $this->primaryColumnValue())];
return $contactModel->all($where, [], 0, 0);
}
/**
* Returns the bank accounts associated with this customer.
*
* @return DinCuentaBancoCliente[]
*/
public function getBankAccounts(): array
{
$contactAccounts = new DinCuentaBancoCliente();
$where = [new DataBaseWhere($this->primaryColumn(), $this->primaryColumnValue())];
return $contactAccounts->all($where, [], 0, 0);
}
/**
* Return the default billing or shipping address.
*
* @return DinContacto
*/
public function getDefaultAddress($type = 'billing'): Contacto
{
$contact = new DinContacto();
$idcontacto = $type === 'shipping' ? $this->idcontactoenv : $this->idcontactofact;
$contact->loadFromCode($idcontacto);
return $contact;
}
public function getGroup(): GrupoClientes
{
$group = new DinGrupoClientes();
$group->loadFromCode($this->codgrupo);
return $group;
}
/**
* Returns the preferred payment days for this customer.
*
* @return array
*/
public function getPaymentDays(): array
{
$days = [];
foreach (explode(',', $this->diaspago . ',') as $str) {
if (is_numeric(trim($str))) {
$days[] = trim($str);
}
}
return $days;
}
public function getSubcuenta(string $codejercicio, bool $crear): Subcuenta
{
// ya tiene una subcuenta asignada
if ($this->codsubcuenta) {
// buscamos la subcuenta para el ejercicio
$subAccount = new DinSubcuenta();
$where = [
new DataBaseWhere('codsubcuenta', $this->codsubcuenta),
new DataBaseWhere('codejercicio', $codejercicio),
];
if ($subAccount->loadFromCode('', $where)) {
return $subAccount;
}
// no hemos encontrado la subcuenta
// si no queremos crearla, devolvemos una vacía
if (false === $crear) {
return new DinSubcuenta();
}
// buscamos la cuenta especial
$special = new DinCuentaEspecial();
if (false === $special->loadFromCode(static::SPECIAL_ACCOUNT)) {
return new DinSubcuenta();
}
// ahora creamos la subcuenta
return $special->getCuenta($codejercicio)->createSubcuenta($this->codsubcuenta, $this->razonsocial);
}
// ¿El grupo tiene subcuenta?
$group = $this->getGroup();
if ($group->codsubcuenta) {
return $group->getSubcuenta($codejercicio, $crear);
}
// si no creamos la subcuenta, devolvemos una vacía
return $crear ?
$this->createSubcuenta($codejercicio) :
new DinSubcuenta();
}
public function install(): string
{
// we need exits Contacto before, but we can't check it because it would create a cyclic check
// we need to check Agente and GrupoClientes models before
new Agente();
new GrupoClientes();
return parent::install();
}
public static function primaryColumn(): string
{
return 'codcliente';
}
public function primaryDescriptionColumn(): string
{
return 'nombre';
}
public static function tableName(): string
{
return 'clientes';
}
public function test(): bool
{
if (empty($this->nombre)) {
Tools::log()->warning(
'field-can-not-be-null',
['%fieldName%' => 'nombre', '%tableName%' => static::tableName()]
);
return false;
}
if (!empty($this->codcliente) && 1 !== preg_match('/^[A-Z0-9_\+\.\-]{1,10}$/i', $this->codcliente)) {
Tools::log()->error(
'invalid-alphanumeric-code',
['%value%' => $this->codcliente, '%column%' => 'codcliente', '%min%' => '1', '%max%' => '10']
);
return false;
}
// we validate the days of payment
$arrayDias = [];
foreach (str_getcsv($this->diaspago ?? '') as $day) {
if ((int)$day >= 1 && (int)$day <= 31) {
$arrayDias[] = (int)$day;
}
}
$this->diaspago = empty($arrayDias) ? null : implode(',', $arrayDias);
return parent::test();
}
protected function createSubcuenta(string $codejercicio): Subcuenta
{
// buscamos la cuenta especial
$special = new DinCuentaEspecial();
if (false === $special->loadFromCode(static::SPECIAL_ACCOUNT)) {
return new DinSubcuenta();
}
// buscamos la cuenta
$cuenta = $special->getCuenta($codejercicio);
if (empty($cuenta->codcuenta)) {
return new DinSubcuenta();
}
// obtenemos un código de subcuenta libre
$code = $cuenta->getFreeSubjectAccountCode($this);
if (empty($code)) {
return new DinSubcuenta();
}
// creamos la subcuenta
$subAccount = $cuenta->createSubcuenta($code, $this->razonsocial);
if (false === $subAccount->save()) {
return new DinSubcuenta();
}
// guardamos el código de subcuenta
$this->codsubcuenta = $subAccount->codsubcuenta;
$this->save();
return $subAccount;
}
protected function saveInsert(array $values = []): bool
{
if (empty($this->codcliente)) {
$this->codcliente = (string)$this->newCode();
}
$return = parent::saveInsert($values);
if ($return && empty($this->idcontactofact)) {
$parts = explode(' ', $this->nombre);
// creates new contact
$contact = new DinContacto();
$contact->apellidos = count($parts) > 1 ? implode(' ', array_slice($parts, 1)) : '';
$contact->cifnif = $this->cifnif;
$contact->codagente = $this->codagente;
$contact->codcliente = $this->codcliente;
$contact->descripcion = $this->nombre;
$contact->email = $this->email;
$contact->empresa = $this->razonsocial;
$contact->fax = $this->fax;
$contact->nombre = $parts[0];
$contact->personafisica = $this->personafisica;
$contact->telefono1 = $this->telefono1;
$contact->telefono2 = $this->telefono2;
$contact->tipoidfiscal = $this->tipoidfiscal;
if ($contact->save()) {
$this->idcontactofact = $contact->idcontacto;
return $this->save();
}
}
return $return;
}
/**
* Devuelve las settings de la empresa
*
* @param string $idCompany
* @return array
*/
public function getSettings(string $idCompany)
{
$settingsModel = new SettingsModel();
$settingsModel->loadFromCode('', [
new DataBaseWhere('classnamemodel', static::class),
new DataBaseWhere('idmodel', $this->primaryColumnValue()),
new DataBaseWhere('idempresa', $idCompany),
]);
return $settingsModel->settings ?? [];
}
}