ImportController.php 16.8 KB
Newer Older
Daniele Draganti's avatar
Daniele Draganti committed
1
2
<?php
/**
Daniele Draganti's avatar
Daniele Draganti committed
3
4
 * Emilia Romagna Open Innovation
 * Arter
Daniele Draganti's avatar
Daniele Draganti committed
5
6
7
8
9
10
 *
 *
 * @package    amos-proposte-collaborazione-een
 * @category   CategoryName
 */

Daniele Draganti's avatar
Daniele Draganti committed
11
namespace arter\amos\een\commands\controllers;
Daniele Draganti's avatar
Daniele Draganti committed
12

Daniele Draganti's avatar
Daniele Draganti committed
13
14
15
16
17
18
19
use arter\amos\attachments\components\FileImport;
use arter\amos\attachments\models\File;
use arter\amos\cwh\models\CwhPubblicazioni;
use arter\amos\een\commands\models\CollaborationProposalEen;
use arter\amos\een\models\EenPartnershipProposal;
use arter\amos\een\utility\EenMailUtility;
use arter\amos\tag\models\EntitysTagsMm;
Daniele Draganti's avatar
Daniele Draganti committed
20
21
22
23
24
use yii\console\Controller;
use yii\console\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;
use yii\helpers\Json;
Daniele Draganti's avatar
Daniele Draganti committed
25
use arter\amos\cwh\models\CwhConfigContents;
Daniele Draganti's avatar
Daniele Draganti committed
26
27
28

/**
 * Class ImportController
Daniele Draganti's avatar
Daniele Draganti committed
29
 * @package arter\amos\een\commands\controllers
Daniele Draganti's avatar
Daniele Draganti committed
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
 */
class ImportController extends Controller
{
    public $tempPath;
    public $ContractId;
    public $CountriesForDissemination;
    public $DeadlineDateAfter;
    public $DeadlineDateBefore;
    public $IncludeImages;
    public $OrganisationCountryName;
    public $OrganisationIdentifier;
    public $OrganisationName;
    public $ProfileTypes;
    public $PublishedDateAfter;
    public $PublishedDateBefore;
    public $SubmitDateAfter;
    public $SubmitDateBefore;
    public $UpdateDateAfter;
    public $UpdateDateBefore;
    public $passedOptions          = [
        'ContractId',
        'CountriesForDissemination',
        'DeadlineDateAfter',
        'DeadlineDateBefore',
        'IncludeImages',
        'OrganisationCountryName',
        'OrganisationIdentifier',
        'OrganisationName',
        'ProfileTypes',
        'PublishedDateAfter',
        'PublishedDateBefore',
        'SubmitDateAfter',
        'SubmitDateBefore',
        'UpdateDateAfter',
        'UpdateDateBefore',
    ];
    public $passedOptionsExplained = [
        'ContractId' => 'with Contract Id {value}',
        'CountriesForDissemination' => 'for the following countries {value}',
        'DeadlineDateAfter' => 'which expires after {value}',
        'DeadlineDateBefore' => 'which expires before {value}',
        'IncludeImages' => 'with attachments',
        'OrganisationCountryName' => 'published by an organization that resides in {value}',
        'OrganisationIdentifier' => 'published by (identifier) {value}',
        'OrganisationName' => 'published by (name) {value}',
        'ProfileTypes' => 'of these types {value}',
        'PublishedDateAfter' => 'published after {value}',
        'PublishedDateBefore' => 'published before {value}',
        'SubmitDateAfter' => 'submitted after {value}',
        'SubmitDateBefore' => 'submitted before {value}',
        'UpdateDateAfter' => 'updated after {value}',
        'UpdateDateBefore' => 'updated before {value}',
    ];

    public function options($actionID)
    {
        return ArrayHelper::merge(parent::options($actionID), $this->passedOptions);
    }

    /**
     * Import EEN Profile request proposal from http://een.ec.europa.eu
     *
     *
     * ```
     * php yii een/import/start --UpdateDateAfter="2020-11-01" --UpdateDateBefore="2020-11-05" --ProfileTypes="Tr,To,Br,Rdr" --IncludeImages=1
     * ```
     *
     * @throws Exception if the name argument is invalid or nothin passed
     */
    public function actionStart()
    {
        ini_set('memory_limit', '4096M');
        ini_set('soap.wsdl_cache_enabled', '0');
        ini_set('soap.wsdl_cache_ttl', '0');

        //ini_set("memory_limit","2G");

        if (!count($this->getPassedOptionValues())) {
            throw new Exception('No arguments passed');
        }

Daniele Draganti's avatar
Daniele Draganti committed
111
        $moduleEen  = \Yii::$app->getModule(\arter\amos\een\AmosEen::getModuleName());
Daniele Draganti's avatar
Daniele Draganti committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
        $conversion = $moduleEen->enableConversionTag;

        $this->ProfileTypes              = $this->normalizeArray($this->ProfileTypes);
        $this->CountriesForDissemination = $this->normalizeArray($this->CountriesForDissemination);

        $this->DeadlineDateAfter   = $this->normalizeDate($this->DeadlineDateAfter);
        $this->DeadlineDateBefore  = $this->normalizeDate($this->DeadlineDateBefore);
        $this->PublishedDateAfter  = $this->normalizeDate($this->PublishedDateAfter);
        $this->PublishedDateBefore = $this->normalizeDate($this->PublishedDateBefore);
        $this->SubmitDateAfter     = $this->normalizeDate($this->SubmitDateAfter);
        $this->SubmitDateBefore    = $this->normalizeDate($this->SubmitDateBefore);
        $this->UpdateDateAfter     = $this->normalizeDate($this->UpdateDateAfter);
        $this->UpdateDateBefore    = $this->normalizeDate($this->UpdateDateBefore);

        $this->IncludeImages = $this->normalizeBoolean($this->IncludeImages);

        $this->OrganisationCountryName = $this->normalizeString($this->OrganisationCountryName);
        $this->OrganisationIdentifier  = $this->normalizeString($this->OrganisationIdentifier);
        $this->OrganisationName        = $this->normalizeString($this->OrganisationName);

        $this->explainRequest();

        $Proposte = CollaborationProposalEen::findAll($this->getPassedOptionValues());
        $notify=0;

        $proposteCount = count($Proposte);
        if ($proposteCount) {

            $list_tags_not_found = false;

            foreach ((array) $Proposte->profile as $k => $profile) {

                $proposta = EenPartnershipProposal::findOne(['reference_external' => $profile->reference->external]);

                $PodProfile = new CollaborationProposalEen([
                    'podXml' => $profile
                ]);

                if (!$proposta) {
                    Console::stdout("NUOVA PROPOSTA {$profile->reference->external} \n\r");
                    $proposta = new EenPartnershipProposal();
                } else {
                    Console::stdout(@$profile->reference->external."\n\r");
                    Console::stdout("AGGIORNO LA PROPOSTA {$profile->reference->external} \n\r");
                    Console::stdout("CANCELLO I FILE DI {$profile->reference->external} \n\r");
                    File::deleteAll([
                        'attribute' => 'attachments',
                        'model' => EenPartnershipProposal::className(),
                        'itemId' => $proposta['id'],
                    ]);
                }

                $proposta->detachBehavior('fileBehavior');

                $proposta->setAttributes($PodProfile->toArray());

                $proposta->detachBehavior('cwhBehavior');
                $proposta->save(false);

                $attachments = $PodProfile->getAttachments();

                $attachmentsCount = count($attachments);

                if ($attachmentsCount) {
                    Console::stdout("SALVO I FILE {$attachmentsCount} DI {$PodProfile->podXml->reference->external} \n\r");
                    $FileImport = new FileImport();
                    foreach ($PodProfile->getAttachments() as $attachmentFilepath) {
                        Console::stdout("\t\t{$attachmentFilepath}\n\r");
                        $FileImport->importFileForModel($proposta, 'attachments', $attachmentFilepath);
                    }
                }

                $tagsNotFound            = [];
                $tagsMarkets             = $PodProfile->getTagsMarkets();
                $tagsMarketsCount        = count($tagsMarkets);
                $tagsNotFound['markets'] = [];
                $savedTags               = [];

                if ($tagsMarketsCount && in_array('markets', $moduleEen->tagsEenEnabled)) {
                    Console::stdout("SALVO I TAGS {$tagsMarketsCount} MARKETS DI {$PodProfile->podXml->reference->external} \n\r");

                    $params = [
                        'classname' => EenPartnershipProposal::className(),
                        'record_id' => $proposta['id'],
                        'root_id' => $moduleEen->book_ids['markets']
                    ];

                    EntitysTagsMm::deleteAll($params);

                    foreach ($tagsMarkets as $tag) {
                        Console::stdout("\t\t{$tag['codice']} - {$tag['nome']}");
                        $tagIds = $tag->getIds($moduleEen->root_id, $conversion);
                        if (!empty($tagIds)) {
                            Console::stdout("\tTROVATO\n\r");
                        foreach ($tagIds as $tagId){
                            $TagProposta = new EntitysTagsMm(ArrayHelper::merge($params,
                                [
                                    'tag_id' => $tagId
                                ]));
                            $TagProposta->save(false);
                        }

                        } else {
                            $tagsNotFound['markets'][] = $tag;
                            if ($conversion == true) {
                                $tag->setNotFound();
                            }
                            Console::stdout("\tNON TROVATO\n\r");
                            $notify=1;
                        }
                    }
                }

                $tagsNaces             = $PodProfile->getTagsNaces();
                $tagsNacesCount        = count($tagsNaces);
                $tagsNotFound['naces'] = [];

                if ($tagsNacesCount && in_array('naces', $moduleEen->tagsEenEnabled)) {
                    Console::stdout("SALVO I TAGS {$tagsNacesCount} NACES DI {$PodProfile->podXml->reference->external} \n\r");

                    $params = [
                        'classname' => EenPartnershipProposal::className(),
                        'record_id' => $proposta['id'],
                        'root_id' => $moduleEen->book_ids['naces']
                    ];

                    EntitysTagsMm::deleteAll($params);

                    foreach ($tagsNaces as $tag) {
                        Console::stdout("\t\t{$tag['codice']} - {$tag['nome']}");
                        $tagIds = $tag->getIds($moduleEen->root_id, $conversion);
                        if (!empty($tagIds)) {
                            Console::stdout("\tTROVATO\n\r");
                            foreach ($tagIds as $tagId){
                                $TagProposta = new EntitysTagsMm(ArrayHelper::merge($params,
                                    [
                                        'tag_id' => $tagId
                                    ]));
                                $TagProposta->save(false);
                            }
                        } else {
                            $tagsNotFound['naces'][] = $tag;
                            if ($conversion == true) {
                                $tag->setNotFound();
                            }
                            Console::stdout("\tNON TROVATO\n\r");
                            $notify=1;
                        }
                    }
                }

                $tagsTechnologies = $PodProfile->getTagsTechnologies();

                $tagsTechnologiesCount = count($tagsTechnologies);

                if ($tagsTechnologiesCount && in_array('tecnologies', $moduleEen->tagsEenEnabled)) {
                    Console::stdout("SALVO I TAGS {$tagsTechnologiesCount} TECHNOLOGIES DI {$PodProfile->podXml->reference->external} \n\r");

                    $params = [
                        'classname' => EenPartnershipProposal::className(),
                        'record_id' => $proposta['id'],
                        'root_id' => $moduleEen->book_ids['tecnologies']
                    ];
  
                    EntitysTagsMm::deleteAll($params);

                    foreach ($tagsTechnologies as $tag) {
                        Console::stdout("\t\t{$tag['codice']} - {$tag['nome']}");
                        $tagIds = $tag->getIds($moduleEen->root_id, $conversion);
                        if (!empty($tagIds)) {
                            Console::stdout("\tTROVATO\n\r");
                            foreach ($tagIds as $tagId){
                                $TagProposta = new EntitysTagsMm(ArrayHelper::merge($params,
                                    [
                                        'tag_id' => $tagId
                                    ]));
                                $TagProposta->save(false);
                            }
                        } else {
                            $tagsNotFound['tecnologies'][] = $tag;
                            if ($conversion == true) {
                                $tag->setNotFound();
                            }
                            Console::stdout("\tNON TROVATO\n\r");
                            $notify=1;
                        }
                    }
                }

                $proposta->tags_not_found = Json::encode($tagsNotFound, true);
                $proposta->detachBehavior('cwhBehavior');
                $ok                       = $proposta->save(false);

                if ($ok) {
                    //$cwhPubbId = 'een_partnership_proposal-' . $proposta->id;
                    $configContent    = CwhConfigContents::findOne(['tablename' => $proposta->tableName()])->id;
                    $cwhPubblicazioni = CwhPubblicazioni::findOne([
                            'cwh_config_contents_id' => $configContent,
                            'content_id' => $proposta->id,
                            'cwh_regole_pubblicazione_id' => 2
                    ]);
                    if (is_null($cwhPubblicazioni)) {
                        $cwhPubblicazioni                              = new CwhPubblicazioni();
                        $cwhPubblicazioni->cwh_config_contents_id      = $configContent;
                        $cwhPubblicazioni->content_id                  = $proposta->id;
                        $cwhPubblicazioni->cwh_regole_pubblicazione_id = 2;
                    }

                    $ok = $cwhPubblicazioni->save(false);
                    //se viene fatto un aggiornamento per via della proposta che scade in giornata non notifichiamo la proposta
                    if($proposta->datum_deadline != $proposta->datum_update && $proposta->datum_deadline > $proposta->datum_update){
Daniele Draganti's avatar
Daniele Draganti committed
323
                        $proposta->saveNotificationSendEmail($proposta->classname(), \arter\amos\notificationmanager\models\NotificationChannels::CHANNEL_MAIL, $proposta->id, true);
Daniele Draganti's avatar
Daniele Draganti committed
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
                    }
                    /* if ($ok) {
                      $eenUtility = new EenMailUtility();
                      $eenUtility->sendMails($proposta->id);
                      } */
                }
                foreach ($tagsNotFound as $tag)
                    print($tag);
                if($conversion == true && !empty($tagsNotFound)){
                    // EenMailUtility::sendEmailTagsNotFound();
                    $list_tags_not_found = true;
                }

                Console::stdout("{$profile->reference->external} => ID {$proposta['id']}  \n\r");
                Console::stdout(".................................................................\n\r\n\r");
            }
            
            if( $notify ) {
                EenMailUtility::sendEmailTagsNotFound();
            }

            Console::stdout($k++." TROVATE\n\r");

            Console::stdout("Saved!\n\r");
        } else {
            Console::stdout("NESSUNA PROPOSTA TROVATA\n\r");
        }

        return [
            'copde' => '1',
            'message' => '??'
        ];
    }

    private function normalizeArray($value, $separator = ',')
    {
        if (isset($value)) {
            return explode($separator, $value);
        }
        return null;
    }

    private function normalizeDate($date)
    {
        if (isset($date)) {
            return date('Ymd', strtotime(
                    date($date)
                )
            );
        }
        return null;
    }

    private function normalizeBoolean($value)
    {
        if (isset($value)) {
            if ($value == 1 || $value == '1' || $value == true || $value == 'true' || strtolower($value) == 'y' || strtolower($value)
                == 'yes') {
                return true;
            }
            return false;
        }
        return null;
    }

    private function normalizeString($value)
    {
        if (is_string($value)) {
            return trim($value);
        }
        return null;
    }

    private function explainRequest()
    {
        Console::stdout("\n\r\n\r==============================================\n\r\n\r");
        Console::stdout("This request returns EEN Collaboration Proposal:\n\r");

        foreach ($this->getPassedOptionValues() as $passedOption => $passedValue) {

            $help = $passedOption;
            if (array_key_exists($passedOption, $this->passedOptionsExplained)) {
                $help = $this->passedOptionsExplained[$passedOption];
            }

            $value = $passedValue;

            if (is_array($passedValue)) {
                $value = implode(',', $passedValue);
            }

            Console::stdout(\Yii::t('amoseen', "\t".$help."\n\r", [
                    'value' => $value
            ]));
        }

        Console::stdout("\n\r\n\r==============================================\n\r\n\r");
    }
}