Completed
Push — master ( 3796bd...927f95 )
by Shawn
04:45
created

JpasImportHandler::importNewData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 3
1
<?php
2
namespace SET\Handlers\Excel;
3
4
use Illuminate\Support\Collection;
5
use Illuminate\Support\Facades\Input;
6
use SET\User;
7
use \Maatwebsite\Excel\Files\ImportHandler;
8
9
/**
10
 * Class JpasImportHandler
11
 *
12
 * Going to handle importing our JPAS excel file.
13
 *
14
 * @package SET\Handlers
15
 */
16
class JpasImportHandler implements ImportHandler
17
{
18
19
    private $unique;
20
    private $changes;
21
22
    /**
23
     * Set our variables as new collections.
24
     */
25
    public function __construct()
26
    {
27
        $this->unique = new Collection();
28
        $this->changes = new Collection();
29
    }
30
31
    /**
32
     * Initial call from UserController.
33
     * Based on what we get, we will either call an initial import or the resolve import.
34
     *
35
     * @param $import
36
     * @return array
37
     */
38
    public function handle($import)
39
    {
40
        $excel = $import->get();
41
        $data = Input::all();
42
43
        //We always pass a token and the file. If there is anything more, then we are resolving.
44
        if ($data['resolveImport']) {
45
            $this->resolveImport($excel, $data);
46
        } else {
47
            $this->initialImport($excel);
48
        }
49
50
        //Return this data. It is just used for the initial import, but still nice to see.
51
        return array('unique' => $this->unique, 'changes' => $this->changes);
52
    }
53
54
    /**
55
     * Cycle through our excel spreadsheet.
56
     * If we can't figure where data goes, we will push it to a collection so the user can map it.
57
     * Otherwise, we will update the record.
58
     *
59
     * @param $excel
60
     */
61
    private function initialImport($excel)
62
    {
63
        foreach ($excel as $row) {
64
            $row->name = preg_replace('/(,\s|\s)/', '_', $row->name);
65
            if (!is_null($row->name) && $row->name != '') { //we get a bunch of null records that we can ignore.
66
                $user = User::where('jpas_name', $row->name)->first(); //see if the record maps to a user
67
                if (is_null($user)) {
68
                    $this->unique->push($row); //if no results, we need to have the admin map this record to a user.
69
                } else {
70
                    $this->getUserChanges($this->mapJpasToUser($user, $row));
71
                }
72
            }
73
        }
74
    }
75
76
    /**
77
     * User has mapped some accounts. We need to update those records.
78
     *
79
     * @param $excel
80
     * @param $data
81
     */
82
    private function resolveImport($excel, $data)
83
    {
84
        foreach ($data as $jpasName => $userGroup) {
85
            if ($jpasName == 'approve') {
86
                $this->updateUserData($userGroup);
87
88
            } else if ($userGroup != '' && is_numeric($userGroup)) {
89
                $this->importNewData($excel, $userGroup, $jpasName);
90
            }
91
        }
92
    }
93
94
    /**
95
     * Place changes so the user can approve/reject them.
96
     *
97
     * @param $user
98
     */
99
    private function getUserChanges($user)
100
    {
101
        if ($user->isDirty()) {
102
            foreach ($user->getDirty() as $attribute => $newValue) {
103
                $this->changes->push([
104
                    'user' => $user,
105
                    'field' => $attribute,
106
                    'original' => $user->getOriginal($attribute),
107
                    'new' => $newValue
108
                ]);
109
            }
110
        }
111
    }
112
113
    /**
114
     * Update user. If there are changes, let's log them to an array.
115
     *
116
     * @param $user
117
     */
118
    private function updateAndLogUser($user)
119
    {
120
        //We will let the user know what changes were made.
121
        if ($user->isDirty()) {
122
            $log = "The following changes have been made for $user->userFullName: \n";
123
            foreach ($user->getDirty() as $attribute => $value) {
124
                $original = $user->getOriginal($attribute);
125
                $log .= "Changed $attribute from '$original' to '$value'.\n";
126
            }
127
            $user->save();
128
            $this->changes->push($log);
129
        }
130
131
    }
132
133
    /**
134
     * Map the data from our JPAS Excel to our User model.
135
     *
136
     * @param $user
137
     * @param $data
138
     */
139
    private function mapJpasToUser($user, $data)
140
    {
141
        $user->jpas_name = $data->name;
142
        $user->clearance = $data->eligibility;
143
        $user->elig_date = $this->getCorrectDateFormat($data->eligibility_date);
144
        $user->inv = $data->inves;
145
        $user->inv_close = $this->getCorrectDateFormat($data->prev_inves);
146
147
        return $user;
148
    }
149
150
    private function getCorrectDateFormat($date)
151
    {
152
        //If we get a date object, just format to Y-m-d
153
        if (is_object($date)) {
154
            return $date->toDateString();
155
        }
156
157
        //If we get a string in the a format such as 2/15/2015 0:00 then convert it to Y-m-d
158
        $d = \DateTime::createFromFormat('n/j/Y G:i', $date);
159
        if ($d) {
160
            return $d->format('Y-m-d');
161
        }
162
163
        //if already in Y-m-d, then just return it.
164
        $d = \DateTime::createFromFormat('Y-m-d', $date);
165
        if ($d) {
166
            return $date;
167
        }
168
169
        //Otherwise store null for the date.
170
        return null;
171
    }
172
173
    /**
174
     * @param $excel
175
     * @param $userGroup
176
     * @param $jpasName
177
     * @return mixed
178
     */
179
    private function importNewData($excel, $userGroup, $jpasName)
180
    {
181
        $user = User::find($userGroup);
182
        foreach ($excel as $row) {
183
            $row->name = preg_replace('/(,\s|\s)/', '_', $row->name);
184
            if ($row->name == $jpasName) {
185
                $this->updateAndLogUser($this->mapJpasToUser($user, $row));
186
            }
187
        }
188
    }
189
190
    /**
191
     * @param $userGroup
192
     */
193
    private function updateUserData($userGroup)
194
    {
195
        foreach ($userGroup as $userId => $changesGroup) {
196
            $user = User::find($userId);
197
            foreach ($changesGroup as $field => $newValue) {
198
                if ($newValue != "0") {
199
                    $user[$field] = $newValue;
200
                }
201
            }
202
            $this->updateAndLogUser($user);
203
        }
204
    }
205
}
206