Passed
Push — main ( 7297d3...786958 )
by Daniel
02:52
created

setArrayToHtmlTable()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 11
c 3
b 0
f 0
nc 3
nop 1
dl 0
loc 15
ccs 0
cts 12
cp 0
crap 20
rs 9.9
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
    private 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;
72
                $intArchivedFile < $intFilesArchived;
73
                $intArchivedFile++) {
74
                $strArchivedFile = $classZip->getNameIndex($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'                => strlen($strInvoiceContent),
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_Index' => 'Index răspuns',
137
            'Supplier_CUI'   => 'CUI emitent',
138
            'Supplier_Name'  => 'Nume emitent',
139
        ];
140
        $strToReturn = '';
141
        foreach ($arrayData as $key) {
142
            $strToReturn .= sprintf('<th>%s</th>', (array_key_exists($key, $arrayMap) ? $arrayMap[$key] : $key));
143
        }
144
        return '<thead><tr>' . $strToReturn . '</tr></thead>';
145
    }
146
147
    private function setArrayToHtmlTable(array $arrayData)
148
    {
149
        foreach ($arrayData as $intLineNo => $arrayContent) {
150
            ksort($arrayContent);
151
            if ($intLineNo === 0) {
152
                echo '<table style="margin-left:auto;margin-right:auto;">'
153
                . $this->setArrayToHtmlTableHeader(array_keys($arrayContent))
154
                . '<tbody>';
155
            }
156
            echo '<tr' . ($arrayContent['Error'] === '' ? '' : ' style="color:red;"') . '>'
157
            . '<td>' . implode('</td><td>', array_values($arrayContent)) . '</td>'
158
            . '</tr>';
159
        }
160
        echo '</tbody>'
161
        . '</table>';
162
    }
163
164
    public function setHtmlFooter(): void
165
    {
166
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
167
                __DIR__,
168
                'HTML',
169
                'footer.html',
170
        ])));
171
        echo vsprintf($strHtmlContent, [
172
            (new \SebastianBergmann\Timer\ResourceUsageFormatter())->resourceUsage($this->classTimer->stop()),
173
            date('Y'),
174
            $this->arrayConfiguration['Application']['Developer'],
175
        ]);
176
    }
177
178
    public function setHtmlHeader(): void
179
    {
180
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
181
                __DIR__,
182
                'HTML',
183
                'header.html',
184
        ])));
185
        echo vsprintf($strHtmlContent, [
186
            $this->arrayConfiguration['Application']['Name'],
187
            $this->arrayConfiguration['Application']['Developer'],
188
        ]);
189
    }
190
191
    private function setStandardizedFeedbackArray(array $arrayData): array
192
    {
193
        $arrayToReturn = [
194
            'Response_Index' => $arrayData['Response_Index'],
195
            'Loading_Index'  => '',
196
            'Size'           => '',
197
            'Document_No'    => '',
198
            'Issue_Date'     => '',
199
            'Amount_wo_VAT'  => '',
200
            'Amount_TOTAL'   => '',
201
            'Amount_VAT'     => '',
202
            'Supplier_CUI'   => '',
203
            'Supplier_Name'  => '',
204
            'Customer_CUI'   => '',
205
            'Customer_Name'  => '',
206
            'No_Lines'       => '',
207
            'Error'          => '',
208
        ];
209
        if ($arrayData['Size'] > 1000) {
210
            file_put_contents($arrayData['strArchivedFileName'], $arrayData['strInvoiceContent']);
211
            $appR                           = new \danielgp\efactura\ClassElectronicInvoiceRead();
212
            $arrayElectronicInv             = $appR->readElectronicInvoice($arrayData['strArchivedFileName']);
213
            $arrayBasic                     = $arrayElectronicInv['Header']['CommonBasicComponents-2'];
214
            $arrayAggregate                 = $arrayElectronicInv['Header']['CommonAggregateComponents-2'];
215
            $floatAmounts                   = [
216
                'wo_VAT' => (float) $arrayAggregate['LegalMonetaryTotal']['TaxExclusiveAmount']['value'],
217
                'TOTAL'  => (float) $arrayAggregate['LegalMonetaryTotal']['TaxInclusiveAmount']['value'],
218
            ];
219
            $arrayParties                   = [
220
                'Customer' => $arrayAggregate['AccountingCustomerParty']['Party'],
221
                'Supplier' => $arrayAggregate['AccountingSupplierParty']['Party'],
222
            ];
223
            $arrayToReturn['Loading_Index'] = substr($arrayData['Matches'][0][0], 0, -4);
224
            $arrayToReturn['Size']          = $arrayData['Size'];
225
            $arrayToReturn['Document_No']   = $arrayBasic['ID'];
226
            $arrayToReturn['Issue_Date']    = $arrayBasic['IssueDate'];
227
            $arrayToReturn['Amount_wo_VAT'] = $floatAmounts['wo_VAT'];
228
            $arrayToReturn['Amount_TOTAL']  = $floatAmounts['TOTAL'];
229
            $arrayToReturn['Amount_VAT']    = ($floatAmounts['TOTAL'] - $floatAmounts['wo_VAT']);
230
            $arrayToReturn['Supplier_CUI']  = $arrayParties['Supplier']['PartyTaxScheme']['01']['CompanyID'];
231
            $arrayToReturn['Supplier_Name'] = $arrayParties['Supplier']['PartyLegalEntity']['RegistrationName'];
232
            $arrayToReturn['Customer_CUI']  = $arrayParties['Customer']['PartyTaxScheme']['01']['CompanyID'];
233
            $arrayToReturn['Customer_Name'] = $arrayParties['Customer']['PartyLegalEntity']['RegistrationName'];
234
            $arrayToReturn['No_Lines']      = count($arrayElectronicInv['Lines']);
235
            unlink($arrayData['strArchivedFileName']);
236
        } elseif ($arrayData['Size'] > 0) {
237
            $objErrors                      = new \SimpleXMLElement($arrayData['strInvoiceContent']);
238
            $arrayToReturn['Loading_Index'] = $objErrors->attributes()->Index_incarcare->__toString();
239
            $arrayToReturn['Size']          = $arrayData['Size'];
240
            $arrayToReturn['Supplier_CUI']  = 'RO' . $objErrors->attributes()->Cif_emitent->__toString();
241
            $arrayToReturn['Supplier_Name'] = '??????????';
242
            $arrayToReturn['Error']         = '<div style="max-width:200px;font-size:0.8rem;">'
243
                . $objErrors->Error->attributes()->errorMessage->__toString() . '</div>';
244
        }
245
        return $arrayToReturn;
246
    }
247
248
    public function setUserInterface(): void
249
    {
250
        echo '<header class="border-bottom">'
251
        . $this->getButtonToActionSomething([
252
            'Text' => 'Analyze ZIP archives from ANAF from a local folder',
253
            'URL'  => '?action=AnalyzeZIPfromANAFfromLocalFolder',
254
        ])
255
        . '</header>';
256
    }
257
}
258