Completed
Push — master ( 6ffd4c...f02542 )
by Ricardo
02:35
created

Import::handle()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Integrations\Connectors\Jira;
4
5
use Log;
6
use App\Models\User;
7
8
use Fabrica\Models\Code\CodeIssueLink;
9
use Casa\Models\Registers\Spent;
10
use Casa\Models\Calendar\Estimate;
11
use Casa\Models\Calendar\Event;
12
13
use Transmissor\Models\Comment;
14
15
use Fabrica\Models\Code\Release;
16
use Fabrica\Models\Code\Issue;
17
use Fabrica\Models\Code\Field as FieldModel;
18
use Fabrica\Models\Code\Project as ProjectModel;
19
20
use JiraRestApi\Project\ProjectService;
21
use JiraRestApi\JiraException;
22
use JiraRestApi\Field\Field;
23
use JiraRestApi\Issue\IssueService;
24
use JiraRestApi\Issue\Version;
25
use JiraRestApi\Field\FieldService;
26
27
28
class Import extends Jira
29
{
30
    public function handle()
31
    {
32
        $this->info('Importando Jira...');
33
        $this->getFields();
34
        $this->getProjects();
35
        $this->getInfoFromIssues();
36
    }
37
38
    public function getFields()
39
    {
40
        try {
41
            $fieldService = new FieldService($this->getConfig($this->_token));
42
        
43
            // $fieldService->getAllFields(Field::CUSTOM),
44
            $fields = $fieldService->getAllFields(); 
45
            foreach($fields as $field) {
46
                $this->info('Registrando FieldModel ...');   
47
                FieldModel::registerFieldForProject($field, $this->_token->account->customize_url);
48
            }
49
            
50
        } catch (JiraException $e) {
51
            $this->setError('testSearch Failed : '.$e->getMessage());
52
        }
53
    }
54
55
    public function getProjects()
56
    {
57
        $this->info('Importando Projetos do Jira...');
58
        try {
59
            $proj = new ProjectService($this->getConfig($this->_token));
60
        
61
            $prjs = $proj->getAllProjects();
62
            // $this->info(print_r($prjs, true));
63
        
64
            foreach ($prjs as $p) {
65
                // $this->info(print_r($p, true));
66
                // Project Key:USS, Id:10021, Name:User Shipping Service, projectCategory: Desenvolvimento
67
                if (!$projModel = ProjectModel::where('projectPathKey', $p->key)->first()) {
68
                    if (!$projModel && !$projModel = ProjectModel::where('projectPath', $p->name)->first()) {
69
                        $this->info('Registrando Projeto: '.$p->key);   
70
                        $projModel = ProjectModel::create(
71
                            [
72
                            'name' => $p->name,
73
                            'projectPathKey' => $p->key,
74
                            // 'created_at' => $p->created,
75
                            // 'updated_at' => $p->updated
76
                            ]
77
                        );
78
                    } else {
79
                        $projModel->projectPathKey = $p->key;
80
                        $projModel->save();
81
                    }
82
                }
83
                $this->projectVersions($projModel);
84
85
                $this->getIssuesFromProject($projModel);
86
                // echo sprintf("Project Key:%s, Id:%s, Name:%s, projectCategory: %s\n",
87
                //     $p->key, $p->id, $p->name, $p->projectCategory['name']
88
                // );            
89
            }            
90
        } catch (JiraException $e) {
91
            $this->setError("Error Occured! " . $e->getMessage());
92
        }
93
    }
94
95
    public function getInfoFromIssues()
96
    {
97
        $chunkNumber = 10;
98
        $object = $this;
99
        // Trata os Outros Dados dos Usuários                                                                                                                                                    
100
        Issue::chunk(
101
            $chunkNumber, function ($issues) use ($object, $chunkNumber) {                                                                                                                               
102
                foreach ($issues as $issue) {                                                                                                                                                          
103
                    if ($this->output) {                                                                                                                                                                  
104
                        $this->output->returnOutput()->progressAdvance($chunkNumber);                                                                                                                                 
105
                    }
106
                    // $object->issueTimeTracking($issue->key_name); // @todo Retirar Depois
107
                    // $object->issueWorklog($issue->key_name);
108
                    $object->comment($issue->key_name);
109
                    $object->getIssueRemoteLink($issue->key_name);
110
                }
111
            }
112
        );
113
    }
114
115
    public function getIssuesFromProject($project)
116
    {
117
        // $jql = 'status = Documentação ORDER BY created DESC';
118
        // $jql = 'project IN ('.$project->getSlug().')';
119
        $jql = 'project='.$project->getSlug();
120
        $paginate = $this->getPaginate(1);
121
        $result = $this->searchIssue($jql, $paginate);
122
        if (!empty($result->issues)) {
123
            foreach ($result->issues as $issue) {
124
                if (!$issueInstance = Issue::where(['key_name' => $issue->key])->first()) {
125
                    $this->info('Registrando Issue: '.$issue->key);   
126
                    $issueInstance = Issue::create(
127
                        [
128
                        'key_name' => $issue->key,
129
                        'url' => $issue->self,
130
                        // 'created_at' => $issue->created,
131
                        // 'updated_at' => $issue->updated
132
                        // 'sumary' => '', @todo fazer aqui 
133
                        ]
134
                    );
135
                    if (!empty($issue->fields)) {
136
                        $issueInstance->setField($issue->fields, $issue->key);
137
                    }
138
                }
139
            }
140
        }
141
    }
142
143
    public function searchIssue($jql = false, $paginate = false)
144
    {
145
        if (!$jql) {
146
            $jql = 'project not in (TEST)  and assignee = currentUser() and status in (Resolved, closed)';
147
        }
148
149
        // $jql = str_replace(" ", "%20", $jql);
150
        $jql = str_replace(" ", "+", $jql);
151
        $jql = str_replace(" ", "\\u002f", $jql);
152
153
        try {
154
            return (new IssueService($this->getConfig($this->_token)))->search($jql); //, $paginate);
155
            // return (new IssueService($this->getConfig($this->_token)))->search($jql);
156
        } catch (JiraException $e) {
157
            $this->setError('testSearch Failed : '.$e->getMessage());
158
        }
159
    }
160
161
    /**
162
     * @todo
163
     *
164
     * @param [type] $project
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
165
     * @return void
166
     */
167
    public function project($project)
168
    {
169
        $this->info('Importando Projeto do Jira...');
170
        try {
171
            $proj = new ProjectService($this->getConfig($this->_token));
172
        
173
            $p = $proj->get($project->getSlug());
174
            
175
            var_dump($p);            
0 ignored issues
show
Security Debugging Code introduced by
var_dump($p); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
176
        } catch (JiraException $e) {
177
            $this->setError("Error Occured! " . $e->getMessage());
178
        }
179
    }
180
181
    public function issueTimeTracking($issueKey = 'TEST-961')
182
    {
183
184
        try {
185
            $issueService = new IssueService($this->getConfig($this->_token));
186
            
187
            // get issue's time tracking info
188
            $rets = $issueService->getTimeTracking($issueKey);
189
            $this->info('Registrando timetracking');
190
            Spent::registerSpentForIssue($rets, $this->_token->account->customize_url);
191
192
            
193
            // $timeTracking = new TimeTracking;
194
195
            // $timeTracking->setOriginalEstimate('3w 4d 6h');
196
            // $timeTracking->setRemainingEstimate('1w 2d 3h');
197
            
198
            // // add time tracking
199
            // $ret = $issueService->timeTracking($issueKey, $timeTracking);
200
            // var_dump($ret);
201
        } catch (JiraException $e) {
202
            $this->setError('testSearch Failed : '.$e->getMessage());
203
        }
204
    }
205
206
    public function issueWorklog($issueKey = 'TEST-961')
207
    {
208
209
        try {
210
            $issueService = new IssueService($this->getConfig($this->_token));
211
            
212
            // get issue's all worklog
213
            $worklogs = $issueService->getWorklog($issueKey)->getWorklogs();
214
            $this->info('Registrando worklogs');
215
            Spent::registerSpentForIssue($worklogs, $this->_token->account->customize_url);
216
            
217
            // // get worklog by id
218
            // $wlId = 12345;
219
            // $wl = $issueService->getWorklogById($issueKey, $wlId);
220
            // var_dump($wl);
221
            
222
        } catch (JiraException $e) {
223
            $this->setError('testSearch Failed : '.$e->getMessage());
224
        }
225
    }
226
227 View Code Duplication
    public function issueLinkType()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
228
    {
229
        try {
230
            $ils = new IssueLinkService($this->getConfig($this->_token));
231
        
232
            $rets = $ils->getIssueLinkTypes();
233
            foreach($rets as $ret) {
234
                $this->info('Criando CodeIssueLinkType: '.$ret->name); // @todo
235
                var_dump($ret);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($ret); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
236
                CodeIssueLink::firstOrCreate(
237
                    [
238
                    'name' => $ret->name
239
                    ]
240
                );
241
            }
242
            
243
        } catch (JiraException $e) {
244
            $this->setError("Error Occured! " . $e->getMessage());
245
        }
246
    }
247
248 View Code Duplication
    public function getIssueRemoteLink($issueKey = 'TEST-316')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
249
    {
250
        try {
251
            $issueService = new IssueService($this->getConfig($this->_token));
252
253
            $rils = $issueService->getRemoteIssueLink($issueKey);
254
            foreach($rils as $ril) {
255
                $this->info('Criando CodeIssueLink: '.$ril->name); // @todo
256
                var_dump($ril);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($ril); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
257
                CodeIssueLink::firstOrCreate(
258
                    [
259
                    'name' => $ril->name
260
                    ]
261
                );
262
            }
263
        } catch (JiraException $e) {
264
            $this->setError($e->getMessage());
265
        }
266
    }
267
268 View Code Duplication
    public function comment($issueKey = "TEST-879")
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
269
    {
270
271
        try {
272
            $issueService = new IssueService($this->getConfig($this->_token));
273
        
274
            $comments = $issueService->getComments($issueKey);
275
            $this->info('Criando comentários p/ Issue: '.$issueKey);
276
            Comment::registerComents(
277
                $comments,
278
                $issueKey,
279
                Issue::class,
280
                $this->_token->account->customize_url
281
            );
282
        
283
        
284
        } catch (JiraException $e) {
285
            $this->setError('get Comment Failed : '.$e->getMessage());
286
        }
287
    }
288
289
    public function getFieldInfo($issueKey = "TEST-879")
290
    {
291
        try {
292
            $issueService = new IssueService($this->getConfig($this->_token));
293
            
294
            $queryParam = [
295
                'fields' => [  // default: '*all'
296
                    'summary',
297
                    'comment',
298
                ],
299
                'expand' => [
300
                    'renderedFields',
301
                    'names',
302
                    'schema',
303
                    'transitions',
304
                    'operations',
305
                    'editmeta',
306
                    'changelog',
307
                ]
308
            ];
309
                    
310
            $issue = $issueService->get($issueKey, $queryParam);
311
            
312
            var_dump($issue->fields);    
0 ignored issues
show
Security Debugging Code introduced by
var_dump($issue->fields); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
313
        } catch (JiraException $e) {
314
            $this->setError("Error Occured! " . $e->getMessage());
315
        }
316
    }
317
318
    public function projectVersions($projInstance)
319
    {
320
        try {
321
            $proj = new ProjectService($this->getConfig($this->_token));
322
        
323
            $vers = $proj->getVersions($projInstance->getSlug());
324
        
325
            foreach ($vers as $v) {
326
                /** @todo Usar id e url
327
                 * JiraRestApi\Issue\Version^ {#5807
328
                 * +self: "https://sitec.atlassian.net/rest/api/2/version/10207"
329
                 * +id: "10207"
330
                 * +name: "v0.1.0"
331
                 * +description: null
332
                 * +archived: false
333
                 * +released: false
334
                 * +releaseDate: null
335
                 * +overdue: null
336
                 * +userReleaseDate: null
337
                 * +projectId: 10215
338
                 * }
339
                  */
340
                // $v is  JiraRestApi\Issue\Version
341
                if (!Release::where(
342
                    [
343
                        'name' => $v->name,
344
                        'code_project_id' => $projInstance->id
345
                    ]
346
                )->first()
347
                ) {
348
                    $this->info('Criando Versão (Proj '.$projInstance->id.'): '.$v->name);
349
                    Release::create(
350
                        [
351
                        'name' => $v->name,
352
                        // 'start' => $v->startDate,
353
                        'release' => $v->releaseDate,
354
                        'code_project_id' => $projInstance->id,
355
                        // 'created_at' => $v->created,
356
                        // 'updated_at' => $v->updated
357
                        ]
358
                    );
359
                }
360
            }
361
        } catch (JiraException $e) {
362
            $this->setError("Error Occured! " . $e->getMessage());
363
        }
364
    }
365
366
    public function projectType()
367
    {
368
        try {
369
            $proj = new ProjectService($this->getConfig($this->_token));
370
        
371
            // get all project type
372
            $prjtyps = $proj->getProjectTypes();
373
        
374
            foreach ($prjtyps as $pt) {
375
                var_dump($pt);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($pt); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
376
            }
377
        
378
            // get specific project type.
379
            $pt = $proj->getProjectType('software');
380
            var_dump($pt);
381
        
382
        } catch (JiraException $e) {
383
            $this->setError("Error Occured! " . $e->getMessage());
384
        }
385
    }
386
}
387