Passed
Push — main ( 8e456c...e52264 )
by Daniel
02:52
created

ClassElectronicInvoiceUserInterface   A

Complexity

Total Complexity 25

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 147
c 2
b 0
f 0
dl 0
loc 214
ccs 0
cts 164
cp 0
rs 10
wmc 25

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A setHtmlFooter() 0 11 1
A setActionToDo() 0 16 3
A setUserInterface() 0 8 1
A setStandardizedFeedbackArray() 0 52 3
A setArchiveFromAnaf() 0 37 5
A actionAnalyzeZIPfromANAFfromLocalFolder() 0 12 4
A getButtonToActionSomething() 0 15 2
A setArrayToHtmlTable() 0 19 4
A setHtmlHeader() 0 10 1
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
                        'ResponseIndex'       => 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
        foreach ($arrayData as $intLineNo => $arrayContent) {
124
            ksort($arrayContent);
125
            if ($intLineNo === 0) {
126
                echo '<table style="margin-left:auto;margin-right:auto;">'
127
                . '<thead>'
128
                . '<tr>'
129
                . '<th>' . implode('</th><th>', array_keys($arrayContent)) . '</th>'
130
                . '</tr>'
131
                . '</thead>';
132
                echo '<tbody>';
133
            }
134
            echo '<tr' . ($arrayContent['Error'] === '' ? '' : ' style="color:red;"') . '>'
135
            . '<td>' . implode('</td><td>', array_values($arrayContent)) . '</td>'
136
            . '</tr>';
137
        }
138
        echo '</tbody>'
139
        . '</table>';
140
    }
141
142
    public function setHtmlFooter(): void
143
    {
144
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
145
                __DIR__,
146
                'HTML',
147
                'footer.html',
148
        ])));
149
        echo vsprintf($strHtmlContent, [
150
            (new \SebastianBergmann\Timer\ResourceUsageFormatter())->resourceUsage($this->classTimer->stop()),
151
            date('Y'),
152
            $this->arrayConfiguration['Application']['Developer'],
153
        ]);
154
    }
155
156
    public function setHtmlHeader(): void
157
    {
158
        $strHtmlContent = implode('', $this->getFileEntireContent(implode(DIRECTORY_SEPARATOR, [
159
                __DIR__,
160
                'HTML',
161
                'header.html',
162
        ])));
163
        echo vsprintf($strHtmlContent, [
164
            $this->arrayConfiguration['Application']['Name'],
165
            $this->arrayConfiguration['Application']['Developer'],
166
        ]);
167
    }
168
169
    private function setStandardizedFeedbackArray(array $arrayData): array
170
    {
171
        $arrayToReturn = [
172
            'ResponseIndex' => $arrayData['ResponseIndex'],
173
            'LoadingIndex'  => '',
174
            'Size'          => '',
175
            'Document_No'   => '',
176
            'Issue_Date'    => '',
177
            'Amount_wo_VAT' => '',
178
            'Amount_TOTAL'  => '',
179
            'Amount_VAT'    => '',
180
            'Supplier_CUI'  => '',
181
            'Supplier_Name' => '',
182
            'Customer_CUI'  => '',
183
            'Customer_Name' => '',
184
            'Error'         => '',
185
        ];
186
        if ($arrayData['Size'] > 1000) {
187
            file_put_contents($arrayData['strArchivedFileName'], $arrayData['strInvoiceContent']);
188
            $appR                           = new \danielgp\efactura\ClassElectronicInvoiceRead();
189
            $arrayElectronicInv             = $appR->readElectronicInvoice($arrayData['strArchivedFileName']);
190
            $arrayBasic                     = $arrayElectronicInv['Header']['CommonBasicComponents-2'];
191
            $arrayAggregate                 = $arrayElectronicInv['Header']['CommonAggregateComponents-2'];
192
            $floatAmounts                   = [
193
                'wo_VAT' => (float) $arrayAggregate['LegalMonetaryTotal']['TaxExclusiveAmount']['value'],
194
                'TOTAL'  => (float) $arrayAggregate['LegalMonetaryTotal']['TaxInclusiveAmount']['value'],
195
            ];
196
            $arrayParties                   = [
197
                'Customer' => $arrayAggregate['AccountingCustomerParty']['Party'],
198
                'Supplier' => $arrayAggregate['AccountingSupplierParty']['Party'],
199
            ];
200
            $arrayToReturn['LoadingIndex']  = substr($arrayData['Matches'][0][0], 0, -4);
201
            $arrayToReturn['Size']          = $arrayData['Size'];
202
            $arrayToReturn['Document_No']   = $arrayBasic['ID'];
203
            $arrayToReturn['Issue_Date']    = $arrayBasic['IssueDate'];
204
            $arrayToReturn['Amount_wo_VAT'] = $floatAmounts['wo_VAT'];
205
            $arrayToReturn['Amount_TOTAL']  = $floatAmounts['TOTAL'];
206
            $arrayToReturn['Amount_VAT']    = ($floatAmounts['TOTAL'] - $floatAmounts['wo_VAT']);
207
            $arrayToReturn['Supplier_CUI']  = $arrayParties['Supplier']['PartyTaxScheme']['01']['CompanyID'];
208
            $arrayToReturn['Supplier_Name'] = $arrayParties['Supplier']['PartyLegalEntity']['RegistrationName'];
209
            $arrayToReturn['Customer_CUI']  = $arrayParties['Customer']['PartyTaxScheme']['01']['CompanyID'];
210
            $arrayToReturn['Customer_Name'] = $arrayParties['Customer']['PartyLegalEntity']['RegistrationName'];
211
            unlink($arrayData['strArchivedFileName']);
212
        } elseif ($arrayData['Size'] > 0) {
213
            $objErrors                      = new \SimpleXMLElement($arrayData['strInvoiceContent']);
214
            $arrayToReturn['LoadingIndex']  = $objErrors->attributes()->Index_incarcare->__toString();
215
            $arrayToReturn['Size']          = $arrayData['Size'];
216
            $arrayToReturn['Supplier_CUI']  = $objErrors->attributes()->Cif_emitent->__toString();
217
            $arrayToReturn['Supplier_Name'] = '??????????';
218
            $arrayToReturn['Error']         = $objErrors->Error->attributes()->errorMessage->__toString();
219
        }
220
        return $arrayToReturn;
221
    }
222
223
    public function setUserInterface(): void
224
    {
225
        echo '<header class="border-bottom">'
226
        . $this->getButtonToActionSomething([
227
            'Text' => 'Analyze ZIP archives from ANAF from a local folder',
228
            'URL'  => '?action=AnalyzeZIPfromANAFfromLocalFolder',
229
        ])
230
        . '</header>';
231
    }
232
}
233