/
DocumentStitcher.php
408 lines (361 loc) · 12.1 KB
/
DocumentStitcher.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
<?php
/**
* This file is part of FacturaScripts
* Copyright (C) 2017-2021 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\Controller;
use FacturaScripts\Core\Base\Controller;
use FacturaScripts\Core\Base\ControllerPermissions;
use FacturaScripts\Core\Base\DataBase\DataBaseWhere;
use FacturaScripts\Core\Model\Base\BusinessDocumentLine;
use FacturaScripts\Core\Model\Base\TransformerDocument;
use FacturaScripts\Dinamic\Lib\BusinessDocumentGenerator;
use FacturaScripts\Dinamic\Model\EstadoDocumento;
use FacturaScripts\Dinamic\Model\User;
use Symfony\Component\HttpFoundation\Response;
/**
* Class DocumentStitcher
*
* @author Carlos García Gómez <carlos@facturascripts.com>
* @author Francesc Pineda Segarra <francesc.pineda.segarra@gmail.com>
*/
class DocumentStitcher extends Controller
{
const MODEL_NAMESPACE = '\\FacturaScripts\\Dinamic\\Model\\';
/**
* Array of document primary keys.
*
* @var array
*/
public $codes = [];
/**
*
* @var TransformerDocument[]
*/
public $documents = [];
/**
* Model name source.
*
* @var string
*/
public $modelName;
/**
*
* @var TransformerDocument[]
*/
public $moreDocuments = [];
/**
* Returns available status to group this model.
*
* @return array
*/
public function getAvailableStatus(): array
{
$status = [];
$documentState = new EstadoDocumento();
$where = [new DataBaseWhere('tipodoc', $this->modelName)];
foreach ($documentState->all($where) as $docState) {
if ($docState->generadoc) {
$status[] = $docState;
}
}
return $status;
}
/**
* Returns basic page attributes
*
* @return array
*/
public function getPageData()
{
$data = parent::getPageData();
$data['menu'] = 'sales';
$data['showonmenu'] = false;
$data['title'] = 'group-or-split';
$data['icon'] = 'fas fa-magic';
return $data;
}
/**
* Runs the controller's private logic.
*
* @param Response $response
* @param User $user
* @param ControllerPermissions $permissions
*/
public function privateCore(&$response, $user, $permissions)
{
parent::privateCore($response, $user, $permissions);
$this->codes = $this->getCodes();
$this->modelName = $this->getModelName();
$this->loadDocuments();
$this->loadMoreDocuments();
$status = (int)$this->request->request->get('status', '');
if ($status) {
// validate form request?
$token = $this->request->request->get('multireqtoken', '');
if (empty($token) || false === $this->multiRequestProtection->validate($token)) {
$this->toolBox()->i18nLog()->warning('invalid-request');
return;
}
if ($this->multiRequestProtection->tokenExist($token)) {
$this->toolBox()->i18nLog()->warning('duplicated-request');
return;
}
$this->generateNewDocument($status);
}
}
/**
*
* @param array $newLines
* @param TransformerDocument $doc
*/
protected function addBlankLine(array &$newLines, $doc)
{
$blankLine = $doc->getNewLine();
$blankLine->cantidad = 0;
$blankLine->iva = 0.0;
$blankLine->irpf = 0.0;
$blankLine->recargo = 0.0;
$newLines[] = $blankLine;
}
/**
*
* @param TransformerDocument $newDoc
*
* @return bool
*/
protected function addDocument($newDoc): bool
{
foreach ($this->documents as $doc) {
if ($doc->codalmacen != $newDoc->codalmacen ||
$doc->coddivisa != $newDoc->coddivisa ||
$doc->idempresa != $newDoc->idempresa ||
$doc->subjectColumnValue() != $newDoc->subjectColumnValue()) {
$this->toolBox()->i18nLog()->warning('incompatible-document', ['%code%' => $newDoc->codigo]);
return false;
}
}
$this->documents[] = $newDoc;
return true;
}
/**
*
* @param array $newLines
* @param TransformerDocument $doc
*/
protected function addInfoLine(array &$newLines, $doc)
{
$infoLine = $doc->getNewLine();
$infoLine->cantidad = 0;
$infoLine->descripcion = $this->getDocInfoLineDescription($doc);
$infoLine->iva = 0.0;
$infoLine->irpf = 0.0;
$infoLine->recargo = 0.0;
$newLines[] = $infoLine;
}
/**
*
* @param TransformerDocument $doc
* @param BusinessDocumentLine $docLines
* @param array $newLines
* @param array $quantities
* @param int $idestado
*/
protected function breakDownLines(&$doc, &$docLines, &$newLines, &$quantities, $idestado)
{
$full = true;
foreach ($docLines as $line) {
$quantity = (float)$this->request->request->get('approve_quant_' . $line->primaryColumnValue(), '0');
$quantities[$line->primaryColumnValue()] = $quantity;
if (empty($quantity) && $line->cantidad) {
$full = $full && $line->servido >= $line->cantidad;
continue;
} elseif (($quantity + $line->servido) < $line->cantidad) {
$full = false;
}
$newLines[] = $line;
}
if ($full) {
$doc->setDocumentGeneration(false);
$doc->idestado = $idestado;
if (false === $doc->save()) {
$this->dataBase->rollback();
$this->toolBox()->i18nLog()->error('record-save-error');
return;
}
}
/// we get the lines again in case they have been updated
foreach ($doc->getLines() as $line) {
$line->servido += $quantities[$line->primaryColumnValue()];
if (false === $line->save()) {
$this->dataBase->rollback();
$this->toolBox()->i18nLog()->error('record-save-error');
return;
}
}
}
/**
* Generates a new document with this data.
*
* @param int $idestado
*/
protected function generateNewDocument(int $idestado)
{
$this->dataBase->beginTransaction();
/// group needed data
$newLines = [];
$properties = ['fecha' => $this->request->request->get('fecha', '')];
$prototype = null;
$quantities = [];
foreach ($this->documents as $doc) {
$lines = $doc->getLines();
if (null === $prototype) {
$prototype = clone $doc;
} elseif ('true' === $this->request->request->get('extralines', '') && !empty($lines)) {
$this->addBlankLine($newLines, $doc);
}
if ('true' === $this->request->request->get('extralines', '') && !empty($lines)) {
$this->addInfoLine($newLines, $doc);
}
/// we break down quantities and lines
$this->breakDownLines($doc, $lines, $newLines, $quantities, $idestado);
}
if (null === $prototype || empty($newLines)) {
$this->dataBase->rollback();
return;
}
/// allow plugins to do stuff on the prototype before save
if (false === $this->pipe('checkPrototype', $prototype, $newLines)) {
$this->dataBase->rollback();
return;
}
/// generate new document
$generator = new BusinessDocumentGenerator();
$newClass = $this->getGenerateClass($idestado);
if (false === $generator->generate($prototype, $newClass, $newLines, $quantities, $properties)) {
$this->dataBase->rollback();
$this->toolBox()->i18nLog()->error('record-save-error');
return;
}
$this->dataBase->commit();
/// redirect to the new document
foreach ($generator->getLastDocs() as $doc) {
$this->redirect($doc->url());
$this->toolBox()->i18nLog()->notice('record-updated-correctly');
break;
}
}
/**
* Returns documents keys.
*
* @return array
*/
protected function getCodes(): array
{
$code = $this->request->request->get('code', []);
if ($code) {
return $code;
}
$codes = explode(',', $this->request->get('codes', ''));
$newcodes = $this->request->get('newcodes', []);
return empty($newcodes) ? $codes : array_merge($codes, $newcodes);
}
/**
*
* @param TransformerDocument $doc
*
* @return string
*/
protected function getDocInfoLineDescription($doc): string
{
$description = $this->toolBox()->i18n()->trans($doc->modelClassName() . '-min') . ' ' . $doc->codigo;
if (isset($doc->numero2) && $doc->numero2) {
$description .= ' (' . $doc->numero2 . ')';
} elseif (isset($doc->numproveedor) && $doc->numproveedor) {
$description .= ' (' . $doc->numproveedor . ')';
}
$description .= ', ' . $doc->fecha . "\n--------------------";
return $description;
}
/**
* Returns the name of the new class to generate from this status.
*
* @param int $idestado
*
* @return string
*/
protected function getGenerateClass(int $idestado): string
{
$estado = new EstadoDocumento();
$estado->loadFromCode($idestado);
return $estado->generadoc;
}
/**
* Returns model name.
*
* @return string
*/
protected function getModelName(): string
{
$model = $this->request->get('model', '');
return $this->request->request->get('model', $model);
}
/**
* Loads selected documents.
*/
protected function loadDocuments()
{
if (empty($this->codes) || empty($this->modelName)) {
return;
}
$modelClass = self::MODEL_NAMESPACE . $this->modelName;
foreach ($this->codes as $code) {
$doc = new $modelClass();
if ($doc->loadFromCode($code)) {
$this->addDocument($doc);
}
}
/// sort by date
uasort($this->documents, function ($doc1, $doc2) {
if (strtotime($doc1->fecha . ' ' . $doc1->hora) > strtotime($doc2->fecha . ' ' . $doc2->hora)) {
return 1;
} elseif (strtotime($doc1->fecha . ' ' . $doc1->hora) < strtotime($doc2->fecha . ' ' . $doc2->hora)) {
return -1;
}
return 0;
});
}
protected function loadMoreDocuments()
{
if (empty($this->documents) || empty($this->modelName)) {
return;
}
$modelClass = self::MODEL_NAMESPACE . $this->modelName;
$model = new $modelClass();
$where = [
new DataBaseWhere('editable', true),
new DataBaseWhere('codalmacen', $this->documents[0]->codalmacen),
new DataBaseWhere('coddivisa', $this->documents[0]->coddivisa),
new DataBaseWhere($model->subjectColumn(), $this->documents[0]->subjectColumnValue())
];
$order = ['fecha' => 'ASC', 'hora' => 'ASC'];
foreach ($model->all($where, $order) as $doc) {
if (false === in_array($doc->primaryColumnValue(), $this->getCodes())) {
$this->moreDocuments[] = $doc;
}
}
}
}