Passed
Push — main ( 786958...82a9e6 )
by Daniel
02:52
created

setArrayToHtmlTable()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 16
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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