Passed
Push — main ( 1dd856...8e456c )
by Daniel
02:57
created

setActionToDo()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

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