Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 137
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
EmailReport
0.00% covered (danger)
0.00%
0 / 137
0.00% covered (danger)
0.00%
0 / 10
2652
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getUsersForEmail
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 getEmployeeArray
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 getStoreTaskGroups
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 decodeDailyResultsFields
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 getCheckListArray
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
380
 getPrintLogArray
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 getDiffArray
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
110
 insertIntoReportLogDatabase
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 decodeString
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2
3namespace BuyerKiosk\DailyReport;
4
5class EmailReport extends BaseReport {
6
7    public $data;
8    public $date;
9    protected $statsDate;
10    public function __construct($typeNum, $data)
11    {
12        parent::__construct($typeNum);
13        $this->data = $data;
14        
15        // Check if HISTORY data exists and has closingDate
16        if (isset($this->data['HISTORY'][0]['closingDate'])) {
17            $this->statsDate = $this->data['HISTORY'][0]['closingDate']." 05:00:00";
18        } else {
19            // Use current date as fallback
20            $this->statsDate = date('Y-m-d')." 05:00:00";
21            $this->log->LogWarn("HISTORY data missing closingDate, using current date as fallback");
22        }
23        
24        $this->date = new \DateTime('now', new \DateTimeZone($this->getTimeZone()));
25    }
26
27    public function getUsersForEmail() {
28        $group = \UserFrosting\GroupLoader::fetch($this->getTypeNum(), 'name');
29
30        $usersArray = $group->fetchUsers();
31        $emailsArray = [];
32        foreach($usersArray as $user) {
33            $name = explode(" ",$user->display_name);
34            if((int)$user->getDailyReport() == 1) {
35                $tempContact['email'] = $user->email;
36                $tempContact['name'] = $name[0];
37                $tempContact['full_name_array'] = $name;
38                $emailsArray[] = $tempContact;
39            }
40        }
41        return $emailsArray;
42    }
43
44    function getEmployeeArray() {
45        $employeeArray = [];
46        //Get an array with employees and their names
47        try {
48            $stmt = $this->usersDB->prepare("SELECT * FROM (SELECT id, display_name, MAX(role) as primaryRole, SUM(buyRole) as buyer, SUM(store) as store FROM
49(SELECT uf_user.id as id, display_name, role, IF(role=3,1,0) as buyRole , IF(group_id = 12,1,0) as store, enabled  FROM uf_user JOIN (SELECT user_id FROM uf_group_user
50JOIN (SELECT id FROM uf_group WHERE name = :typeNum) as A ON uf_group_user.group_id = A.id)
51AS B ON B.user_id = uf_user.id
52JOIN uf_group_user ON uf_group_user.user_id = uf_user.id
53 JOIN uf_group ON uf_group_user.group_id = uf_group.id) AS D
54 WHERE enabled = 1
55GROUP BY id) as F WHERE store != 1");
56
57            $stmt->bindValue(":typeNum", $this->getTypeNum());
58            if($stmt->execute()) {
59                while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
60                    $temp['id'] = $row['id'];
61                    $temp['isBuyer'] = $row['buyer'];
62                    $name = explode(" ", $row['display_name']);
63                    $temp['firstName'] = $name[0];
64                    $temp['lastName'] = "";
65                    if(count($name) > 1) {
66                        $temp['lastName'] = $name[1];
67                    }
68                    $employeeArray[(int)$row['id']] = $temp;
69                }
70                return $employeeArray;
71            }
72            $this->log->LogError("Execution Failed on Get Employees Query");
73        } catch (\PDOException $e) {
74            $this->log->LogError("PDO Exception Caught on Get Employees Query");
75        }
76        return null;
77    }
78
79    public function getStoreTaskGroups() {
80        $taskGroups = [];
81        //Get an array with taskGroups and their names
82        $stmt = $this->storeDB->query("SELECT * FROM taskGroups WHERE 1");
83        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
84            $tempTask['id'] = $row['id'];
85            $tempTask['groupName'] = $row['groupName'];
86            $taskGroups[$row['id']] = $tempTask;
87        }
88        return $taskGroups;
89    }
90    public function decodeDailyResultsFields() {
91        // Check if DAILYRESULTS data exists
92        if (!isset($this->data['DAILYRESULTS'][0])) {
93            $this->log->LogWarning("DAILYRESULTS data not found, skipping decode");
94            return;
95        }
96        
97        // Safely decode each field with null coalescing
98        $fields = [
99            'openingCheckListSubmitter',
100            'openingCheckListComments',
101            'closingCheckListSubmitter',
102            'closingCheckListComments',
103            'varianceExplanation',
104            'dayCloseComments',
105            'dayCloseSubmitter'
106        ];
107        
108        foreach ($fields as $field) {
109            if (isset($this->data['DAILYRESULTS'][0][$field])) {
110                $this->data['DAILYRESULTS'][0][$field] = $this->decodeString($this->data['DAILYRESULTS'][0][$field]);
111            } else {
112                $this->data['DAILYRESULTS'][0][$field] = '';
113                $this->log->LogDebug("Field '$field' not found in DAILYRESULTS, using empty string");
114            }
115        }
116    }
117
118    public function getCheckListArray($taskGroups, $employeeArray) {
119        $checkListArray = [];
120
121        foreach($taskGroups as $group) {
122            $checkListArray[$group['id']]['tasks'] = [];
123            $checkListArray[$group['id']]['name'] = $group['groupName'];
124        }
125
126        // Check if CHECKLIST data exists
127        if (isset($this->data['CHECKLIST']) && is_array($this->data['CHECKLIST'])) {
128            foreach ($this->data['CHECKLIST'] as $task) {
129                $timeStamp = isset($task['timeStamp']) ? $task['timeStamp'] : date('Y-m-d H:i:s');
130                $timestamp = \DateTime::createFromFormat("Y-m-d H:i:s", $timeStamp);
131                $tempTask['assignedStatus'] = isset($task['assignedStatus']) ? $task['assignedStatus'] : '';
132                $tempTask['assignedEmployee'] = "None";
133                $tempTask['completedEmployee'] = "None";
134                
135                if(isset($task['assignedEmpID']) && $task['assignedEmpID'] !== "null" && isset($employeeArray[(int)$task['assignedEmpID']])) {
136                    $tempTask['assignedEmployee'] = $employeeArray[(int)$task['assignedEmpID']];
137                }
138                if(isset($task['completedEmpID']) && $task['completedEmpID'] !== "null" && isset($employeeArray[(int)$task['completedEmpID']])) {
139                    $tempTask['completedEmployee'] = $employeeArray[(int)$task['completedEmpID']];
140                }
141                
142                $tempTask['completedStatus'] = isset($task['completedStatus']) ? $task['completedStatus'] : '';
143                $tempTask['taskName'] = isset($task['taskName']) ? $this->decodeString($task['taskName']) : '';
144                $tempTask['taskComment'] = isset($task['taskComment']) ? $this->decodeString($task['taskComment']) : '';
145                $tempTask['time'] = $timestamp ? $timestamp->format("g:i A") : '';
146                
147                $taskGroup = isset($task['taskGroup']) ? $task['taskGroup'] : 'default';
148                if (isset($checkListArray[$taskGroup])) {
149                    $checkListArray[$taskGroup]['tasks'][] = $tempTask;
150                }
151            }
152        }
153
154        return $checkListArray;
155    }
156
157    public function getPrintLogArray() {
158        $printLog = new \PrintLog();
159        $store = new \Store();
160        $store->createStore($this->getTypeNum());
161        $printLog->gatherPrintLogArray($store, $this->statsDate);
162        $printLogArray['sorterStats'] = getSorterStatsArray($store, $this->statsDate);
163        $printLogArray['buyerStats'] = getBuyerStatsArray($store, $this->statsDate);
164        $printLogArray['storeStats'] = $printLog->getStoreStats();
165        return $printLogArray;
166    }
167    public function getDiffArray($xd) {
168        $red = "#c44c4c";
169        $green = "#4CA6C6";
170        $diff = [];
171        
172        // Helper function to safely get numeric value
173        $getNumeric = function($key) use ($xd) {
174            return isset($xd[$key]) ? (float)$xd[$key] : 0.0;
175        };
176        
177        // Week comparisons
178        $diff['diffGrossCostWeek']['diff'] = $getNumeric('currentYearGrossSalesCostWeekToDate') - $getNumeric('lastYearGrossSalesCostWeekToDate');
179        $diff['diffGrossCostWeek']['color'] = $diff['diffGrossCostWeek']['diff'] > 0 ? $green : $red;
180        
181        $diff['diffGrossRetailWeek']['diff'] = $getNumeric('currentYearGrossSalesRetailWeekToDate') - $getNumeric('lastYearGrossSalesRetailWeekToDate');
182        $diff['diffGrossRetailWeek']['color'] = $diff['diffGrossRetailWeek']['diff'] > 0 ? $green : $red;
183        
184        $diff['diffNetCostWeek']['diff'] = $getNumeric('currentYearNetSalesCostWeekToDate') - $getNumeric('lastYearNetSalesCostWeekToDate');
185        $diff['diffNetCostWeek']['color'] = $diff['diffNetCostWeek']['diff'] > 0 ? $green : $red;
186        
187        $diff['diffNetRetailWeek']['diff'] = $getNumeric('currentYearNetSalesRetailWeekToDate') - $getNumeric('lastYearNetSalesRetailWeekToDate');
188        $diff['diffNetRetailWeek']['color'] = $diff['diffNetRetailWeek']['diff'] > 0 ? $green : $red;
189
190        // Month comparisons
191        $diff['diffGrossCostMonth']['diff'] = $getNumeric('currentYearGrossSalesCostMonthToDate') - $getNumeric('lastYearGrossSalesCostMonthToDate');
192        $diff['diffGrossCostMonth']['color'] = $diff['diffGrossCostMonth']['diff'] > 0 ? $green : $red;
193        
194        $diff['diffGrossRetailMonth']['diff'] = $getNumeric('currentYearGrossSalesRetailMonthToDate') - $getNumeric('lastYearGrossSalesRetailMonthToDate');
195        $diff['diffGrossRetailMonth']['color'] = $diff['diffGrossRetailMonth']['diff'] > 0 ? $green : $red;
196        
197        $diff['diffNetCostMonth']['diff'] = $getNumeric('currentYearNetSalesCostMonthToDate') - $getNumeric('lastYearNetSalesCostMonthToDate');
198        $diff['diffNetCostMonth']['color'] = $diff['diffNetCostMonth']['diff'] > 0 ? $green : $red;
199        
200        $diff['diffNetRetailMonth']['diff'] = $getNumeric('currentYearNetSalesRetailMonthToDate') - $getNumeric('lastYearNetSalesRetailMonthToDate');
201        $diff['diffNetRetailMonth']['color'] = $diff['diffNetRetailMonth']['diff'] > 0 ? $green : $red;
202        
203        return $diff;
204    }
205    public function insertIntoReportLogDatabase($email, $firstName, $lastName, $success) {
206        try {
207            $stmt = $this->mainDB->prepare("INSERT INTO dailyReportLog (`type`, typeNum, contactEmail, firstName, lastName, timeStamp, success) VALUES (:type, :typeNum, :contactEmail, :firstName, :lastName, CURRENT_TIMESTAMP , :success)");
208            $stmt->bindValue(":type", 1);
209            $stmt->bindValue(":typeNum", $this->getTypeNum());
210            $stmt->bindValue(":contactEmail", $email);
211            $stmt->bindValue(":firstName", $firstName);
212            $stmt->bindValue(":lastName", $lastName);
213            $stmt->bindValue(":success", $success);
214            if($stmt->execute()) {
215                return true;
216            }
217        } catch (\PDOException $e) {
218            error_log("ERROR: EmailReport::insertIntoReportLogDatabase - PDO Exception: " . $e->getMessage());
219            $this->log->LogError("PDO Exception: " . $e->getMessage());
220            if (is_array($e->errorInfo)) {
221                $this->log->LogError("Error info: " . print_r($e->errorInfo, true));
222            }
223        }
224        return false;
225    }
226    public function decodeString($string) {
227        $string = htmlspecialchars_decode(urldecode($string));
228
229        $string = str_replace(["\\r\\n", "\\r", "\\n"], "\n", $string);
230        $string = str_replace("\\t","&#9;", $string);
231        $string = str_replace("\\","", $string);
232        $string = str_replace("u003e",">", $string);
233        $string = str_replace("u003c","<", $string);
234        return $string;
235    }
236}