ImportOldData   A
last analyzed

Complexity

Total Complexity 32

Size/Duplication

Total Lines 385
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 226
c 1
b 0
f 0
dl 0
loc 385
rs 9.84
wmc 32

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
F handle() 0 350 31
1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\Models\Tenant;
6
use App\Services\TenantManager;
7
use Illuminate\Console\Command;
8
use Illuminate\Support\Facades\DB;
9
use Illuminate\Support\Facades\Storage;
10
use Symfony\Component\Console\Exception\RuntimeException;
11
12
class ImportOldData extends Command
13
{
14
    /**
15
     * The name and signature of the console command.
16
     *
17
     * @var string
18
     */
19
    protected $signature = 'legacydata:import {tenantId}';
20
21
    /**
22
     * The console command description.
23
     *
24
     * @var string
25
     */
26
    protected $description = 'Imports data from legacy database (the first version of HR system)';
27
28
    protected $tenantManager;
29
30
    /**
31
     * Create a new command instance.
32
     *
33
     * @param TenantManager $tenantManager
34
     */
35
    public function __construct(TenantManager $tenantManager)
36
    {
37
        parent::__construct();
38
39
        $this->tenantManager = $tenantManager;
40
    }
41
42
    /**
43
     * Execute the console command.
44
     *
45
     * @return mixed
46
     */
47
    public function handle()
48
    {
49
        $tenantId = $this->argument('tenantId');
50
        $tenant = Tenant::find($tenantId);
51
52
        if (!$tenant) {
53
            throw new RuntimeException('Tenant with ID = '.$tenantId.' does not exist.');
0 ignored issues
show
Bug introduced by
Are you sure $tenantId of type array|null|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

53
            throw new RuntimeException('Tenant with ID = './** @scrutinizer ignore-type */ $tenantId.' does not exist.');
Loading history...
54
        }
55
56
        if (!$this->confirm('Do you REALLY WANT to run import legacy data?')) {
57
            return;
58
        }
59
60
        if (!$this->confirm('It will ERASE ALL current data for ::'.$tenant->subdomain.':: tenant. Are you sure?')) {
61
            return;
62
        }
63
64
        $this->tenantManager->setTenant($tenant);
65
        \DB::purge('tenant');
66
67
        DB::connection('tenant')->delete('DELETE FROM sources');
68
        DB::connection('tenant')->delete('DELETE FROM notes');
69
        DB::connection('tenant')->delete('DELETE FROM messages');
70
        DB::connection('tenant')->delete('DELETE FROM activities');
71
        DB::connection('tenant')->delete('DELETE FROM form_fields');
72
        DB::connection('tenant')->delete('DELETE FROM predefined_messages');
73
        DB::connection('tenant')->delete('DELETE FROM stages');
74
        DB::connection('tenant')->delete('DELETE FROM recruitments');
75
        DB::connection('tenant')->delete('DELETE FROM candidates');
76
        DB::connection('tenant')->delete('DELETE FROM user_invitations');
77
        DB::connection('tenant')->delete('DELETE FROM users');
78
79
        DB::connection()->delete('DELETE FROM tenant_users WHERE tenant_id='.$tenant->id);
80
81
        DB::connection('tenant')->statement('ALTER TABLE sources AUTO_INCREMENT = 1;');
82
        DB::connection('tenant')->statement('ALTER TABLE notes AUTO_INCREMENT = 1;');
83
        DB::connection('tenant')->statement('ALTER TABLE messages AUTO_INCREMENT = 1;');
84
        DB::connection('tenant')->statement('ALTER TABLE activities AUTO_INCREMENT = 1;');
85
        DB::connection('tenant')->statement('ALTER TABLE form_fields AUTO_INCREMENT = 1;');
86
        DB::connection('tenant')->statement('ALTER TABLE predefined_messages AUTO_INCREMENT = 1;');
87
        DB::connection('tenant')->statement('ALTER TABLE stages AUTO_INCREMENT = 1;');
88
        DB::connection('tenant')->statement('ALTER TABLE recruitments AUTO_INCREMENT = 1;');
89
        DB::connection('tenant')->statement('ALTER TABLE candidates AUTO_INCREMENT = 1;');
90
        DB::connection('tenant')->statement('ALTER TABLE user_invitations AUTO_INCREMENT = 1;');
91
        DB::connection('tenant')->statement('ALTER TABLE users AUTO_INCREMENT = 1;');
92
93
        $users = DB::connection('legacy')->select('SELECT * FROM users');
94
        foreach ($users as $user) {
95
            $email = str_replace('.pl', '.com', $user->email);
96
            DB::connection('tenant')->insert(
97
                'INSERT INTO users (id, created_at, updated_at, `name`, email, `password`)
98
                VALUES (?, ?, ?, ?, ?, ?)',
99
                [
100
                    $user->id,
101
                    $user->created_at,
102
                    $user->updated_at,
103
                    $user->name,
104
                    $email,
105
                    $user->password,
106
                ]
107
            );
108
109
            DB::connection('')->insert(
110
                'INSERT INTO tenant_users (created_at, updated_at, `username`, tenant_id)
111
                VALUES (?, ?, ?, ?)',
112
                [
113
                    $user->created_at,
114
                    $user->updated_at,
115
                    $email,
116
                    $tenantId,
117
                ]
118
            );
119
        }
120
121
        $stages = json_decode('[
122
    {
123
        "order": 1,
124
        "name": "Nowy",
125
        "action_name": "Zmień etap",
126
        "has_appointment": false,
127
        "is_quick_link": false
128
    },
129
    {
130
        "order": 2,
131
        "name": "Rozmowa telefoniczna",
132
        "action_name": "Zmień etap",
133
        "has_appointment": true,
134
        "is_quick_link": true
135
    },
136
    {
137
        "order": 3,
138
        "name": "Spotkanie",
139
        "action_name": "Zmień etap",
140
        "has_appointment": true,
141
        "is_quick_link": false
142
    },
143
    {
144
        "order": 4,
145
        "name": "Złożenie oferty",
146
        "action_name": "Zmień etap",
147
        "has_appointment": false,
148
        "is_quick_link": false
149
    },
150
    {
151
        "order": 5,
152
        "name": "Zatrudnienie",
153
        "action_name": "Zmień etap",
154
        "has_appointment": false,
155
        "is_quick_link": false
156
    },
157
    {
158
        "order": 6,
159
        "name": "Odrzucenie",
160
        "action_name": "Odrzuć",
161
        "has_appointment": false,
162
        "is_quick_link": true
163
    }
164
]');
165
166
        $stageId = 1;
167
        $stageMap = [];
168
        $recruitments = DB::connection('legacy')->select('SELECT * FROM recruitments');
169
        foreach ($recruitments as $recruitment) {
170
            DB::connection('tenant')->insert(
171
                'INSERT INTO recruitments (id, created_at, updated_at, name, job_title, notification_email, is_draft, state)
172
                VALUES (?, ?, ?, ?, ?, ?, 0, ?)',
173
                [
174
                    $recruitment->id,
175
                    $recruitment->created_at,
176
                    $recruitment->updated_at,
177
                    $recruitment->name,
178
                    $recruitment->name,
179
                    $recruitment->notification_email,
180
                    $recruitment->state == 0 ? 0 : 2,
181
                ]
182
            );
183
184
            foreach ($stages as $stage) {
185
                DB::connection('tenant')->insert(
186
                    'INSERT INTO stages (id, created_at, updated_at, recruitment_id, name,
187
                has_appointment, is_quick_link, `order`, action_name)
188
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
189
                    [
190
                        $stageId,
191
                        new \DateTime(),
192
                        new \DateTime(),
193
                        $recruitment->id,
194
                        $stage->name,
195
                        $stage->has_appointment,
196
                        $stage->is_quick_link,
197
                        $stage->order,
198
                        $stage->action_name,
199
                    ]
200
                );
201
202
                $stageMap[$recruitment->id][$stage->name] = $stageId;
203
204
                $stageId++;
205
            }
206
207
            $fields = json_decode(file_get_contents(base_path().'/database/seeds/form_fields.json'), true);
208
            $now = \Carbon\Carbon::now()->toDateTimeString();
209
210
            foreach ($fields as $field) {
211
                DB::connection('tenant')->table('form_fields')->insert([
212
                    'name'           => $field['name'],
213
                    'label'          => $field['label'],
214
                    'system'         => $field['system'],
215
                    'type'           => $field['type'],
216
                    'required'       => $field['required'],
217
                    'order'          => $field['order'],
218
                    'recruitment_id' => $recruitment->id,
219
                    'created_at'     => $now,
220
                    'updated_at'     => $now,
221
                ]);
222
            }
223
224
            $messages = json_decode(file_get_contents(base_path().'/database/seeds/predefined_messages.json'), true);
225
226
            foreach ($messages as $message) {
227
                $from_stage_id = null;
228
                $to_stage_id = null;
229
230
                if ($message['from_stage'] !== null) {
231
                    $from_stage_id = DB::connection('tenant')->table('stages')
232
                        ->where('recruitment_id', $recruitment->id)
233
                        ->where('order', $message['from_stage'])->select('id')->value('id');
234
                }
235
236
                if ($message['to_stage'] !== null) {
237
                    $to_stage_id = DB::connection('tenant')->table('stages')
238
                        ->where('recruitment_id', $recruitment->id)
239
                        ->where('order', $message['to_stage'])->select('id')->value('id');
240
                }
241
242
                DB::connection('tenant')->table('predefined_messages')->insert([
243
                    'subject'        => $message['subject'],
244
                    'body'           => $message['body'],
245
                    'trigger'        => $message['trigger'],
246
                    'from_stage_id'  => $from_stage_id,
247
                    'to_stage_id'    => $to_stage_id,
248
                    'recruitment_id' => $recruitment->id,
249
                    'created_at'     => $now,
250
                    'updated_at'     => $now,
251
                ]);
252
            }
253
        }
254
255
        $sources = DB::connection('legacy')->select('SELECT * FROM sources');
256
        foreach ($sources as $source) {
257
            DB::connection('tenant')->insert(
258
                'INSERT INTO sources (id, created_at, updated_at, `name`, recruitment_id, `key`)
259
                VALUES (?, ?, ?, ?, ?, ?)',
260
                [
261
                    $source->id,
262
                    $source->created_at,
263
                    $source->updated_at,
264
                    $source->name,
265
                    $source->recruitment_id,
266
                    $source->key,
267
                ]
268
            );
269
        }
270
271
        $candidates = DB::connection('legacy')->select('SELECT * FROM candidates');
272
        foreach ($candidates as $candidate) {
273
            $customFields = '[{"id": 0, "label": "Informacje dodatkowe", "value": '.json_encode($candidate->additional_info).'}]';
274
            $seenAt = $candidate->stage_id != 1 ? $candidate->created_at : null;
275
276
            $pathToCV = 'kissdigital/'.$candidate->path_to_cv;
277
278
            $stageId = 0;
279
280
            switch ($candidate->stage_id) {
281
                case 1:
282
                case 2:
283
                    $stageId = $stageMap[$candidate->recruitment_id]['Nowy'];
284
                    break;
285
                case 3:
286
                    //rozmowa tel
287
                    $stageId = $stageMap[$candidate->recruitment_id]['Rozmowa telefoniczna'];
288
                    break;
289
                case 4:
290
                    //spotkanie
291
                    $stageId = $stageMap[$candidate->recruitment_id]['Spotkanie'];
292
                    break;
293
                case 5:
294
                case 6:
295
                case 7:
296
                case 10:
297
                    //odrzucenie
298
                    $stageId = $stageMap[$candidate->recruitment_id]['Odrzucenie'];
299
                    break;
300
                case 8:
301
                    //Złożenie oferty
302
                    $stageId = $stageMap[$candidate->recruitment_id]['Złożenie oferty'];
303
                    break;
304
                case 9:
305
                    //Zatrudnienie
306
                    $stageId = $stageMap[$candidate->recruitment_id]['Zatrudnienie'];
307
                    break;
308
            }
309
310
            $photoPath = str_replace('.pdf', '_avatar.jpg', $candidate->path_to_cv);
311
            $photoExtraction = \Carbon\Carbon::now()->toDateTimeString();
312
313
            if (Storage::disk('s3')->missing($photoPath)) {
314
                $photoPath = null;
315
                $photoExtraction = null;
316
            }
317
318
            DB::connection('tenant')->insert(
319
                'INSERT INTO candidates (id, created_at, updated_at, `name`, email,
320
                `phone_number`, future_agreement, path_to_cv, source_id, recruitment_id, seen_at, stage_id, rate, custom_fields, photo_path, photo_extraction)
321
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
322
                [
323
                    $candidate->id,
324
                    $candidate->created_at,
325
                    $candidate->updated_at,
326
                    $candidate->first_name.' '.$candidate->last_name,
327
                    $candidate->email,
328
                    $candidate->phone_number,
329
                    $candidate->future_agreement,
330
                    $pathToCV,
331
                    $candidate->source_id,
332
                    $candidate->recruitment_id,
333
                    $seenAt,
334
                    $stageId,
335
                    $candidate->rate,
336
                    $customFields,
337
                    $photoPath,
338
                    $photoExtraction,
339
                ]
340
            );
341
        }
342
343
        $notes = DB::connection('legacy')->select('SELECT * FROM notes');
344
        foreach ($notes as $note) {
345
            DB::connection('tenant')->insert(
346
                'INSERT INTO notes (id, created_at, updated_at, `body`, candidate_id, `user_id`)
347
                VALUES (?, ?, ?, ?, ?, ?)',
348
                [
349
                    $note->id,
350
                    $note->created_at,
351
                    $note->updated_at,
352
                    $note->body,
353
                    $note->candidate_id,
354
                    $note->user_id ? $note->user_id : 2,
355
                ]
356
            );
357
        }
358
        foreach ($candidates as $candidate) {
359
            if ($candidate->stage_id == 10) {
360
                DB::connection('tenant')->insert(
361
                    'INSERT INTO notes (created_at, updated_at, `body`, candidate_id, `user_id`)
362
                VALUES (?, ?, ?, ?, ?)',
363
                    [
364
                        new \DateTime(),
365
                        new \DateTime(),
366
                        'Kandydat zrezygnował w trakcie rekrutacji',
367
                        $candidate->id,
368
                        2,
369
                    ]
370
                );
371
            }
372
        }
373
374
        $messages = DB::connection('legacy')->select('SELECT * FROM messages');
375
        foreach ($messages as $message) {
376
            $candidate = DB::connection('tenant')->select('SELECT * FROM candidates WHERE `id`='.$message->candidate_id);
377
            DB::connection('tenant')->insert(
378
                'INSERT INTO messages (id, created_at, updated_at, `type`, candidate_id,
379
                `subject`, `body`, `scheduled_for`, `sent_at`, `to`)
380
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
381
                [
382
                    $message->id,
383
                    $message->created_at,
384
                    $message->updated_at,
385
                    $message->type,
386
                    $message->candidate_id,
387
                    $message->subject,
388
                    $message->body,
389
                    $message->scheduled_at,
390
                    $message->created_at,
391
                    $candidate[0]->email,
392
                ]
393
            );
394
        }
395
396
        $this->info('Legacy data have been imported for tenant with subdomain \''.$tenant->subdomain.'\'.');
397
    }
398
}
399