Passed
Push — main ( af03f2...7297d3 )
by Daniel
03:08
created

setArrayToHtmlTable()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 36
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 30
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 36
ccs 0
cts 32
cp 0
crap 42
rs 8.8177
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; $intArchivedFile < $intFilesArchived; $intArchivedFile++) {
72
                $strArchivedFile = $classZip->getNameIndex($intArchivedFile);
73
                $matches         = [];
74
                preg_match('/^[0-9]{5,20}\.xml$/', $strArchivedFile, $matches, PREG_OFFSET_CAPTURE);
75
                $matches2        = [];
76
                preg_match('/^semnatura_[0-9]{5,20}\.xml$/', $strArchivedFile, $matches2, PREG_OFFSET_CAPTURE);
77
                if ($matches !== []) {
78
                    $resInvoice        = $classZip->getStream($strArchivedFile);
79
                    $strInvoiceContent = stream_get_contents($resInvoice);
80
                    fclose($resInvoice);
81
                    $arrayToReturn     = $this->setStandardizedFeedbackArray([
82
                        'Response_Index'      => pathinfo($strFile)['filename'],
83
                        'Size'                => strlen($strInvoiceContent),
84
                        'Matches'             => $matches,
85
                        'strArchivedFileName' => $strArchivedFile,
86
                        'strInvoiceContent'   => $strInvoiceContent,
87
                    ]);
88
                } elseif ($matches2 === []) {
89
                    echo vsprintf('<div>' . $this->arrayConfiguration['Feedback']['DifferentFile'] . '</div>', [
90
                        $strArchivedFile,
91
                        $strFile->getBasename(),
92
                    ]);
93
                }
94
            }
95
        } else {
96
            // @codeCoverageIgnoreStart
97
            throw new \RuntimeException(sprintf('Archive %s could not be opened!', $strFile));
98
            // @codeCoverageIgnoreEnd
99
        }
100
        return $arrayToReturn;
101
    }
102
103
    public function setActionToDo(): void
104
    {
105
        echo '<main>';
106
        $arrayOptions = [
107
            'action' => FILTER_SANITIZE_SPECIAL_CHARS,
108
        ];
109
        $arrayInputs  = filter_input_array(INPUT_GET, $arrayOptions);
110
        if (array_key_exists('action', $arrayInputs)) {
111
            switch ($arrayInputs['action']) {
112
                case 'AnalyzeZIPfromANAFfromLocalFolder':
113
                    $arrayInvoices = $this->actionAnalyzeZIPfromANAFfromLocalFolder('P:/e-Factura/Downloaded/');
114
                    $this->setArrayToHtmlTable($arrayInvoices);
115
                    break;
116
            }
117
        }
118
        echo '</main>';
119
    }
120
121
    private function setArrayToHtmlTable(array $arrayData)
122
    {
123
        $arrayMap = [
124
            'Amount_TOTAL'   => 'TOTAL',
125
            'Amount_VAT'     => 'TVA',
126
            'Amount_wo_VAT'  => 'Valoare',
127
            'Customer_CUI'   => 'CUI client',
128
            'Customer_Name'  => 'Nume client',
129
            'Document_No'    => 'Identificator',
130
            'Error'          => 'Eroare',
131
            'Issue_Date'     => 'Data emiterii',
132
            'Loading_Index'  => 'Index încărcare',
133
            'No_Lines'       => 'Nr. linii',
134
            'Response_Index' => 'Index răspuns',
135
            'Supplier_CUI'   => 'CUI emitent',
136
            'Supplier_Name'  => 'Nume emitent',
137
        ];
138
        foreach ($arrayData as $intLineNo => $arrayContent) {
139
            ksort($arrayContent);
140
            if ($intLineNo === 0) {
141
                echo '<table style="margin-left:auto;margin-right:auto;">'
142
                . '<thead>'
143
                . '<tr>';
144
                foreach (array_keys($arrayContent) as $key) {
145
                    echo sprintf('<th>%s</th>', (array_key_exists($key, $arrayMap) ? $arrayMap[$key] : $key));
146
                }
147
                echo '</tr>'
148
                . '</thead>';
149
                echo '<tbody>';
150
            }
151
            echo '<tr' . ($arrayContent['Error'] === '' ? '' : ' style="color:red;"') . '>'
152
            . '<td>' . implode('</td><td>', array_values($arrayContent)) . '</td>'
153
            . '</tr>';
154
        }
155
        echo '</tbody>'
156
        . '</table>';
157
    }
158
159
    public function setHtmlFooter(): void
160
    {
161
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
162
                __DIR__,
163
                'HTML',
164
                'footer.html',
165
        ])));
166
        echo vsprintf($strHtmlContent, [
167
            (new \SebastianBergmann\Timer\ResourceUsageFormatter())->resourceUsage($this->classTimer->stop()),
168
            date('Y'),
169
            $this->arrayConfiguration['Application']['Developer'],
170
        ]);
171
    }
172
173
    public function setHtmlHeader(): void
174
    {
175
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
176
                __DIR__,
177
                'HTML',
178
                'header.html',
179
        ])));
180
        echo vsprintf($strHtmlContent, [
181
            $this->arrayConfiguration['Application']['Name'],
182
            $this->arrayConfiguration['Application']['Developer'],
183
        ]);
184
    }
185
186
    private function setStandardizedFeedbackArray(array $arrayData): array
187
    {
188
        $arrayToReturn = [
189
            'Response_Index' => $arrayData['Response_Index'],
190
            'Loading_Index'  => '',
191
            'Size'           => '',
192
            'Document_No'    => '',
193
            'Issue_Date'     => '',
194
            'Amount_wo_VAT'  => '',
195
            'Amount_TOTAL'   => '',
196
            'Amount_VAT'     => '',
197
            'Supplier_CUI'   => '',
198
            'Supplier_Name'  => '',
199
            'Customer_CUI'   => '',
200
            'Customer_Name'  => '',
201
            'No_Lines'       => '',
202
            'Error'          => '',
203
        ];
204
        if ($arrayData['Size'] > 1000) {
205
            file_put_contents($arrayData['strArchivedFileName'], $arrayData['strInvoiceContent']);
206
            $appR                           = new \danielgp\efactura\ClassElectronicInvoiceRead();
207
            $arrayElectronicInv             = $appR->readElectronicInvoice($arrayData['strArchivedFileName']);
208
            $arrayBasic                     = $arrayElectronicInv['Header']['CommonBasicComponents-2'];
209
            $arrayAggregate                 = $arrayElectronicInv['Header']['CommonAggregateComponents-2'];
210
            $floatAmounts                   = [
211
                'wo_VAT' => (float) $arrayAggregate['LegalMonetaryTotal']['TaxExclusiveAmount']['value'],
212
                'TOTAL'  => (float) $arrayAggregate['LegalMonetaryTotal']['TaxInclusiveAmount']['value'],
213
            ];
214
            $arrayParties                   = [
215
                'Customer' => $arrayAggregate['AccountingCustomerParty']['Party'],
216
                'Supplier' => $arrayAggregate['AccountingSupplierParty']['Party'],
217
            ];
218
            $arrayToReturn['Loading_Index'] = substr($arrayData['Matches'][0][0], 0, -4);
219
            $arrayToReturn['Size']          = $arrayData['Size'];
220
            $arrayToReturn['Document_No']   = $arrayBasic['ID'];
221
            $arrayToReturn['Issue_Date']    = $arrayBasic['IssueDate'];
222
            $arrayToReturn['Amount_wo_VAT'] = $floatAmounts['wo_VAT'];
223
            $arrayToReturn['Amount_TOTAL']  = $floatAmounts['TOTAL'];
224
            $arrayToReturn['Amount_VAT']    = ($floatAmounts['TOTAL'] - $floatAmounts['wo_VAT']);
225
            $arrayToReturn['Supplier_CUI']  = $arrayParties['Supplier']['PartyTaxScheme']['01']['CompanyID'];
226
            $arrayToReturn['Supplier_Name'] = $arrayParties['Supplier']['PartyLegalEntity']['RegistrationName'];
227
            $arrayToReturn['Customer_CUI']  = $arrayParties['Customer']['PartyTaxScheme']['01']['CompanyID'];
228
            $arrayToReturn['Customer_Name'] = $arrayParties['Customer']['PartyLegalEntity']['RegistrationName'];
229
            $arrayToReturn['No_Lines']      = count($arrayElectronicInv['Lines']);
230
            unlink($arrayData['strArchivedFileName']);
231
        } elseif ($arrayData['Size'] > 0) {
232
            $objErrors                      = new \SimpleXMLElement($arrayData['strInvoiceContent']);
233
            $arrayToReturn['Loading_Index'] = $objErrors->attributes()->Index_incarcare->__toString();
234
            $arrayToReturn['Size']          = $arrayData['Size'];
235
            $arrayToReturn['Supplier_CUI']  = 'RO' . $objErrors->attributes()->Cif_emitent->__toString();
236
            $arrayToReturn['Supplier_Name'] = '??????????';
237
            $arrayToReturn['Error']         = '<div style="max-width:200px;font-size:0.8rem;">'
238
                . $objErrors->Error->attributes()->errorMessage->__toString() . '</div>';
239
        }
240
        return $arrayToReturn;
241
    }
242
243
    public function setUserInterface(): void
244
    {
245
        echo '<header class="border-bottom">'
246
        . $this->getButtonToActionSomething([
247
            'Text' => 'Analyze ZIP archives from ANAF from a local folder',
248
            'URL'  => '?action=AnalyzeZIPfromANAFfromLocalFolder',
249
        ])
250
        . '</header>';
251
    }
252
}
253