Passed
Push — main ( 82a9e6...5943f3 )
by Daniel
02:54
created

setArchiveFromAnaf()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 39
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 4
Bugs 0 Features 1
Metric Value
cc 5
eloc 30
c 4
b 0
f 1
nc 5
nop 1
dl 0
loc 39
ccs 0
cts 31
cp 0
crap 30
rs 9.1288
1
<?php
2
3
/*
4
 * Copyright (c) 2024, Daniel Popiniuc and its licensors.
5
 *
6
 * All rights reserved. This program and the accompanying materials
7
 * are made available under the terms of the Eclipse Public License v1.0
8
 * which accompanies this distribution, and is available at
9
 * http://www.eclipse.org/legal/epl-v10.html
10
 *
11
 * Contributors:
12
 *    Daniel Popiniuc
13
 */
14
15
namespace danielgp\efactura;
16
17
class ClassElectronicInvoiceUserInterface
18
{
19
20
    use \danielgp\io_operations\InputOutputFiles;
21
22
    private array $arrayConfiguration;
23
    private \SebastianBergmann\Timer\Timer $classTimer;
24
25
    public function __construct()
26
    {
27
        $this->classTimer         = new \SebastianBergmann\Timer\Timer();
28
        $this->classTimer->start();
29
        $this->arrayConfiguration = $this->getArrayFromJsonFile(__DIR__
30
            . DIRECTORY_SEPARATOR . 'config', 'BasicConfiguration.json');
31
    }
32
33
    public function actionAnalyzeZIPfromANAFfromLocalFolder(string $strFilePath): array
34
    {
35
        $arrayFiles    = new \RecursiveDirectoryIterator($strFilePath, \FilesystemIterator::SKIP_DOTS);
36
        $arrayInvoices = [];
37
        $intFileNo     = 0;
38
        foreach ($arrayFiles as $strFile) {
39
            if ($strFile->isFile() && ($strFile->getExtension() === 'zip')) {
40
                $arrayInvoices[$intFileNo] = $this->setArchiveFromAnaf($strFile->getRealPath());
41
                $intFileNo++;
42
            }
43
        }
44
        return $arrayInvoices;
45
    }
46
47
    private function getButtonToActionSomething(array $arrayButtonFeatures): string
48
    {
49
        $arrayButtonStyle = [
50
            'font: bold 14pt Arial',
51
            'margin: 2px',
52
            'padding: 4px 10px',
53
        ];
54
        $arrayStylePieces = $arrayButtonStyle;
55
        if (array_key_exists('AdditionalStyle', $arrayButtonFeatures)) {
56
            $arrayStylePieces = array_merge($arrayButtonStyle, $arrayButtonFeatures['AdditionalStyle']);
57
        }
58
        return vsprintf('<a href="%s" class="btn btn-outline-primary" style="%s">%s</a>', [
59
            $arrayButtonFeatures['URL'],
60
            implode(';', $arrayStylePieces),
61
            $arrayButtonFeatures['Text'],
62
        ]);
63
    }
64
65
    private function setArchiveFromAnaf(string $strFile)
66
    {
67
        $classZip      = new \ZipArchive();
68
        $arrayToReturn = [];
69
        $res           = $classZip->open($strFile, \ZipArchive::RDONLY);
70
        if ($res === true) {
71
            $intFilesArchived = $classZip->numFiles;
72
            for ($intArchivedFile = 0; $intArchivedFile < $intFilesArchived; $intArchivedFile++) {
73
                $strArchivedFile = $classZip->getNameIndex($intArchivedFile);
74
                $strFileStats    = $classZip->statIndex($intArchivedFile);
75
                $matches         = [];
76
                preg_match('/^[0-9]{5,20}\.xml$/', $strArchivedFile, $matches, PREG_OFFSET_CAPTURE);
77
                $matches2        = [];
78
                preg_match('/^semnatura_[0-9]{5,20}\.xml$/', $strArchivedFile, $matches2, PREG_OFFSET_CAPTURE);
79
                if ($matches !== []) {
80
                    $resInvoice        = $classZip->getStream($strArchivedFile);
81
                    $strInvoiceContent = stream_get_contents($resInvoice);
82
                    fclose($resInvoice);
83
                    $arrayToReturn     = $this->setStandardizedFeedbackArray([
84
                        'Response_Index'      => pathinfo($strFile)['filename'],
85
                        'Size'                => $strFileStats['size'],
86
                        'FileDate'            => date('Y-m-d H:i:s', $strFileStats['mtime']),
87
                        'Matches'             => $matches,
88
                        'strArchivedFileName' => $strArchivedFile,
89
                        'strInvoiceContent'   => $strInvoiceContent,
90
                    ]);
91
                } elseif ($matches2 === []) {
92
                    echo vsprintf('<div>' . $this->arrayConfiguration['Feedback']['DifferentFile'] . '</div>', [
93
                        $strArchivedFile,
94
                        $strFile->getBasename(),
95
                    ]);
96
                }
97
            }
98
        } else {
99
            // @codeCoverageIgnoreStart
100
            throw new \RuntimeException(sprintf('Archive %s could not be opened!', $strFile));
101
            // @codeCoverageIgnoreEnd
102
        }
103
        return $arrayToReturn;
104
    }
105
106
    public function setActionToDo(): void
107
    {
108
        echo '<main>';
109
        $arrayOptions = [
110
            'action' => FILTER_SANITIZE_SPECIAL_CHARS,
111
        ];
112
        $arrayInputs  = filter_input_array(INPUT_GET, $arrayOptions);
113
        if (array_key_exists('action', $arrayInputs)) {
114
            switch ($arrayInputs['action']) {
115
                case 'AnalyzeZIPfromANAFfromLocalFolder':
116
                    $arrayInvoices = $this->actionAnalyzeZIPfromANAFfromLocalFolder('P:/e-Factura/Downloaded/');
117
                    $this->setArrayToHtmlTable($arrayInvoices);
118
                    break;
119
            }
120
        }
121
        echo '</main>';
122
    }
123
124
    private function setArrayToHtmlTableHeader(array $arrayData): string
125
    {
126
        $arrayMap    = [
127
            'Amount_TOTAL'   => 'TOTAL',
128
            'Amount_VAT'     => 'TVA',
129
            'Amount_wo_VAT'  => 'Valoare',
130
            'Customer_CUI'   => 'CUI client',
131
            'Customer_Name'  => 'Nume client',
132
            'Document_No'    => 'Identificator',
133
            'Error'          => 'Eroare',
134
            'Issue_Date'     => 'Data emiterii',
135
            'Loading_Index'  => 'Index încărcare',
136
            'No_Lines'       => 'Nr. linii',
137
            'Response_Date'  => 'Data răspuns',
138
            'Response_Index' => 'Index răspuns',
139
            'Supplier_CUI'   => 'CUI emitent',
140
            'Supplier_Name'  => 'Nume emitent',
141
        ];
142
        $strToReturn = '<th>#</th>';
143
        foreach ($arrayData as $key) {
144
            $strToReturn .= sprintf('<th>%s</th>', (array_key_exists($key, $arrayMap) ? $arrayMap[$key] : $key));
145
        }
146
        return '<thead><tr>' . $strToReturn . '</tr></thead>';
147
    }
148
149
    public function setArrayToHtmlTable(array $arrayData)
150
    {
151
        foreach ($arrayData as $intLineNo => $arrayContent) {
152
            ksort($arrayContent);
153
            if ($intLineNo === 0) {
154
                echo '<table style="margin-left:auto;margin-right:auto;">'
155
                . $this->setArrayToHtmlTableHeader(array_keys($arrayContent))
156
                . '<tbody>';
157
            }
158
            echo '<tr' . ($arrayContent['Error'] === '' ? '' : ' style="color:red;"') . '>'
159
            . '<td>' . $intLineNo . '</td>'
160
            . '<td>' . implode('</td><td>', array_values($arrayContent)) . '</td>'
161
            . '</tr>';
162
        }
163
        echo '</tbody>'
164
        . '</table>';
165
    }
166
167
    private function setDataSupplierOrCustomer(array $arrayData)
168
    {
169
        $strCustomerCui = '';
170
        if (isset($arrayData['PartyTaxScheme']['01']['CompanyID'])) {
171
            $strCustomerCui = $arrayData['PartyTaxScheme']['01']['CompanyID'];
172
        } else {
173
            $strCustomerCui = $arrayData['PartyLegalEntity']['CompanyID'];
174
        }
175
        if (is_numeric($strCustomerCui)) {
176
            $strCustomerCui = 'RO' . $strCustomerCui;
177
        }
178
        return $strCustomerCui;
179
    }
180
181
    public function setHtmlFooter(): void
182
    {
183
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
184
                __DIR__,
185
                'HTML',
186
                'footer.html',
187
        ])));
188
        echo vsprintf($strHtmlContent, [
189
            (new \SebastianBergmann\Timer\ResourceUsageFormatter())->resourceUsage($this->classTimer->stop()),
190
            date('Y'),
191
            $this->arrayConfiguration['Application']['Developer'],
192
        ]);
193
    }
194
195
    public function setHtmlHeader(): void
196
    {
197
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
198
                __DIR__,
199
                'HTML',
200
                'header.html',
201
        ])));
202
        echo vsprintf($strHtmlContent, [
203
            $this->arrayConfiguration['Application']['Name'],
204
            $this->arrayConfiguration['Application']['Developer'],
205
        ]);
206
    }
207
208
    private function setStandardizedFeedbackArray(array $arrayData): array
209
    {
210
        $arrayToReturn = [
211
            'Response_Date'  => '',
212
            'Response_Index' => $arrayData['Response_Index'],
213
            'Loading_Index'  => '',
214
            'Size'           => '',
215
            'Document_No'    => '',
216
            'Issue_Date'     => '',
217
            'Amount_wo_VAT'  => '',
218
            'Amount_TOTAL'   => '',
219
            'Amount_VAT'     => '',
220
            'Supplier_CUI'   => '',
221
            'Supplier_Name'  => '',
222
            'Customer_CUI'   => '',
223
            'Customer_Name'  => '',
224
            'No_Lines'       => '',
225
            'Error'          => '',
226
        ];
227
        if ($arrayData['Size'] > 1000) {
228
            file_put_contents($arrayData['strArchivedFileName'], $arrayData['strInvoiceContent']);
229
            $appR                           = new \danielgp\efactura\ClassElectronicInvoiceRead();
230
            $arrayElectronicInv             = $appR->readElectronicInvoice($arrayData['strArchivedFileName']);
231
            $arrayBasic                     = $arrayElectronicInv['Header']['CommonBasicComponents-2'];
232
            $arrayAggregate                 = $arrayElectronicInv['Header']['CommonAggregateComponents-2'];
233
            $floatAmounts                   = [
234
                'wo_VAT' => (float) $arrayAggregate['LegalMonetaryTotal']['TaxExclusiveAmount']['value'],
235
                'TOTAL'  => (float) $arrayAggregate['LegalMonetaryTotal']['TaxInclusiveAmount']['value'],
236
            ];
237
            $arrayParties                   = [
238
                'Customer' => $arrayAggregate['AccountingCustomerParty']['Party'],
239
                'Supplier' => $arrayAggregate['AccountingSupplierParty']['Party'],
240
            ];
241
            $arrayToReturn['Loading_Index'] = substr($arrayData['Matches'][0][0], 0, -4);
242
            $arrayToReturn['Size']          = $arrayData['Size'];
243
            $arrayToReturn['Document_No']   = $arrayBasic['ID'];
244
            $arrayToReturn['Issue_Date']    = $arrayBasic['IssueDate'];
245
            $arrayToReturn['Response_Date'] = $arrayData['FileDate'];
246
            $arrayToReturn['Amount_wo_VAT'] = $floatAmounts['wo_VAT'];
247
            $arrayToReturn['Amount_TOTAL']  = $floatAmounts['TOTAL'];
248
            $arrayToReturn['Amount_VAT']    = round(($floatAmounts['TOTAL'] - $floatAmounts['wo_VAT']), 2);
249
            $arrayToReturn['Supplier_CUI']  = $this->setDataSupplierOrCustomer($arrayParties['Supplier']);
250
            $arrayToReturn['Supplier_Name'] = $arrayParties['Supplier']['PartyLegalEntity']['RegistrationName'];
251
            $arrayToReturn['Customer_CUI']  = $this->setDataSupplierOrCustomer($arrayParties['Customer']);
252
            $arrayToReturn['Customer_Name'] = $arrayParties['Customer']['PartyLegalEntity']['RegistrationName'];
253
            $arrayToReturn['No_Lines']      = count($arrayElectronicInv['Lines']);
254
            unlink($arrayData['strArchivedFileName']);
255
        } elseif ($arrayData['Size'] > 0) {
256
            $objErrors                      = new \SimpleXMLElement($arrayData['strInvoiceContent']);
257
            $arrayToReturn['Loading_Index'] = $objErrors->attributes()->Index_incarcare->__toString();
258
            $arrayToReturn['Size']          = $arrayData['Size'];
259
            $arrayToReturn['Response_Date'] = $arrayData['FileDate'];
260
            $arrayToReturn['Supplier_CUI']  = 'RO' . $objErrors->attributes()->Cif_emitent->__toString();
261
            $arrayToReturn['Supplier_Name'] = '??????????';
262
            $arrayToReturn['Error']         = '<div style="max-width:200px;font-size:0.8rem;">'
263
                . $objErrors->Error->attributes()->errorMessage->__toString() . '</div>';
264
        }
265
        return $arrayToReturn;
266
    }
267
268
    public function setUserInterface(): void
269
    {
270
        echo '<header class="border-bottom">'
271
        . $this->getButtonToActionSomething([
272
            'Text' => 'Analyze ZIP archives from ANAF from a local folder',
273
            'URL'  => '?action=AnalyzeZIPfromANAFfromLocalFolder',
274
        ])
275
        . '</header>';
276
    }
277
}
278