-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlugin.php
425 lines (357 loc) · 16.8 KB
/
Plugin.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
111
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
323
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
423
424
425
<?php
namespace ClaimForm;
use DateTime;
use MapasCulturais\i;
use MapasCulturais\App;
use MapasCulturais\Definitions\FileGroup;
use MapasCulturais\Entities\Notification;
class Plugin extends \MapasCulturais\Plugin
{
public function __construct(array $config = array())
{
/** @var App $app */
$app = App::i();
$app->hook('app.modules.init:before', function (&$modules) use ($config) {
if (($key = array_search('OpportunityClaimForm', $modules)) !== false) {
unset($modules[$key]);
}
});
parent::__construct($config);
}
public function _init()
{
/** @var App $app */
$app = App::i();
//load css
$app->hook('GET(<<*>>.<<*>>)', function() use ($app) {
$app->view->enqueueStyle('app-v2', 'ClaimForm', 'css/plugin-claim-form.css');
});
$self = $this;
$app->_config['mailer.templates']['claim_refused'] = [
'title' => i::__("Arquivo de recurso rejeitado"),
'template' => 'claim_refused.html'
];
$app->hook("entity(RegistrationFile).remove:after", function() use ($app, $self){
if ($this->group === "formClaimUpload"){
$registration = $this->owner;
$app->disableAccessControl();
$registration->acceptClaim = 4;
$registration->save(true);
$message = sprintf(i::__("Vocẽ já pode inserir um novo arquivo de recurso para inscrição %s na oportunidade %s."),$registration->number, $registration->opportunity->firstPhase->name);
$self->createNotification($registration->owner->user, $message);
$self->sendMailEvolutionClaim($registration, $message, i::__("Recurso reaberto para a inscrição {$registration->number}"));
$app->enableAccessControl();
}
});
$app->hook("entity(Registration).save:after", function() use ($app, $self){
$registration = $this;
if($registration->acceptClaim == 3) {
$message = sprintf(i::__("O arquivo anexado ao recurso da sua inscrição %s na oportunidade %s foi rejeitado."),$registration->number, $registration->opportunity->firstPhase->name);
$self->createNotification($registration->owner->user, $message);
$self->sendMailEvolutionClaim($registration, $message, i::__("Arquivo de recurso rejeitado"));
}
if($registration->acceptClaim == 2) {
$message = sprintf(i::__("O arquivo anexado ao recurso da sua inscrição %s na oportunidade %s foi acaito."),$registration->number, $registration->opportunity->firstPhase->name);
$self->createNotification($registration->owner->user, $message);
$self->sendMailEvolutionClaim($registration, $message, i::__("Arquivo de recurso aceito"));
}
});
// Adiciona seção de configuração do formulário de recurso dentro da configuração do formulário
$app->hook("view.partial(singles/opportunity-registrations--export):after", function () {
$this->part('claim-configuration', ['opportunity' => $this->controller->requestedEntity]);
});
// Define a permissãopara inserir arquivos na inscrição apos a mesma estar fechada
$app->hook('can(RegistrationFile.<<*>>)', function ($user, &$result) use ($app, $self) {
/** @var \MapasCulturais\Entities\RegistrationFile $this */
if ($this->group === "formClaimUpload" && $this->owner->opportunity->publishedRegistrations) {
if(!$this->owner->acceptClaim || $this->owner->acceptClaim == 1 || $this->owner->acceptClaim == 4 || $this->owner->opportunity->canUser('@control')){
$result = true;
}
}
});
/** Altera permissão canUserView */
$app->hook('entity(Registration).canUser(sendClaimMessage)', function ($user, &$canUser) use ($self) {
$opportunity = $this->opportunity;
// se o status for maior que 0 significa que a inscrição foi enviada
if ($this->status > 0 && $opportunity->publishedRegistrations && $opportunity->claimDisabled && $this->canUser('view')) {
$canUser = true;
} else {
$canUser = false;
}
});
$app->hook('PATCH(registration.single):data', function() use ($app, $self) {
$request = $this->data;
$app->hook('entity(Registration).canUser(modify)', function ($user, &$canUser) use ($self, $request, $app) {
/** @var Registration $this */
$opportunity = $this->opportunity;
if (in_array('acceptClaim', array_keys($request)) && $this->status > 0 && $opportunity->publishedRegistrations && $opportunity->canUser('@control')) {
$canUser = true;
}
});
$app->hook('entity(RegistrationMeta).canUser(create)', function ($user, &$canUser) use ($self, $request, $app) {
/** @var Registration $this */
$opportunity = $this->opportunity;
if (in_array('acceptClaim', array_keys($request)) && $this->status > 0 && $opportunity->publishedRegistrations && $opportunity->canUser('@control')) {
$canUser = true;
}
});
});
/** Envia o e-mail de recurso para o administrador */
$app->hook('entity(Registration).file(formClaimUpload).insert:after', function () use ($self) {
$self->sendMailClaim($this);
$self->sendMailClaimCertificate($this);
});
$app->hook('app.plugins.preInit:before', function () use($app) {
$app->hook("component(opportunity-phase-config-data-collection):bottom", function(){
$this->part('opportunity-claim-config');
});
$app->hook('component(opportunity-phases-timeline).registration:end', function () {
$this->part('opportunity-claim-form-component');
});
});
$app->hook("module(OpportunityPhases).dataCollectionPhaseData", function(&$data) {
$data .= ',claimEmail,claimDisabled,claimFrom,claimTo';
});
$app->hook('mapas.printJsObject:before', function () use($app) {
if(isset($this->jsObject['registrationPhases'])) {
foreach($this->jsObject['registrationPhases'] as &$reg) {
$registration = $app->repo('Registration')->find($reg['id']);
$reg['currentUserPermissions'] = $reg['currentUserPermissions'] ?? $registration->currentUserPermissions;
$reg['currentUserPermissions']['sendClaimMessage'] = $registration->canUser('sendClaimMessage');
}
}
},1000);
$app->hook('view.requestedEntity(Registration).result', function (&$result) {
if($registration = $this->controller->requestedEntity) {
$result['currentUserPermissions']['sendClaimMessage'] = $registration->canUser('sendClaimMessage');
}
});
}
public function validateErros($controller)
{
$checkFields = [
'message' => i::__('Digite um texto explicando seu recurso'),
'fileId' => i::__('Anexe um arquivo')
];
$errors = [];
foreach($checkFields as $field => $message){
if(empty($controller->data[$field]) || $controller->data[$field] == ""){
$errors[] = $message;
}
}
return $errors;
}
public function register()
{
/** @var App $app */
$app = App::i();
$this->registerOpportunityMetadata('activateAttachment', [
'label' => i::__('Habilitar anexo de arquivo para recurso'),
'type' => 'select',
'options' => (object)[
'0' => i::__('Anexo habilitado'),
'1' => i::__('Anexo desabilitado'),
]
]);
$this->registerOpportunityMetadata('claimDisabled', [
'label' => i::__('Desabilitar formulário de recursos'),
'type' => 'select',
'options' => (object)[
'0' => i::__('formulário de recurso habilitado'),
'1' => i::__('formulário de recurso desabilitado'),
]
]);
$this->registerOpportunityMetadata('claimEmail', [
'label' => \MapasCulturais\i::__('Email de destino do formulário de recursos'),
'validations' => [
'v::email()' => \MapasCulturais\i::__('Email inválido')
]
]);
$this->registerOpportunityMetadata('claimFrom', [
'label' => \MapasCulturais\i::__('Data de inicio do recurso'),
'type' => 'datetime',
'unserialize' => function ($value) {
return $value ? new DateTime($value ?: 'now') : $value;
}
]);
$this->registerOpportunityMetadata('claimTo', [
'label' => \MapasCulturais\i::__('Data de fim do recurso'),
'type' => 'datetime',
'unserialize' => function ($value) {
return $value ? new DateTime($value ?: 'now') : $value;
}
]);
$this->registerRegistrationMetadata('acceptClaim', [
'label' => \MapasCulturais\i::__('Idicação de aceite do recurso por parte do administrador'),
'type' => 'int',
'default' => 1,
]);
$app->registerFileGroup(
'registration',
new FileGroup(
'formClaimUpload',
[
'application/pdf',
'image/(gif|jpeg|pjpeg|png)',
// ms office
'application/msword',
'application/vnd\.openxmlformats-officedocument\.wordprocessingml\.document',
'application/vnd\.ms-excel',
'application/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet',
'application/vnd\.ms-powerpoint',
'application/vnd\.openxmlformats-officedocument\.presentationml\.presentation',
'application/vnd\.openxmlformats-officedocument\.presentationml\.slideshow',
// libreoffice / openoffice
'application/vnd\.oasis\.opendocument\.chart',
'application/vnd\.oasis\.opendocument\.formula',
'application/vnd\.oasis\.opendocument\.graphics',
'application/vnd\.oasis\.opendocument\.image',
'application/vnd\.oasis\.opendocument\.presentation',
'application/vnd\.oasis\.opendocument\.spreadsheet',
'application/vnd\.oasis\.opendocument\.text',
'application/vnd\.oasis\.opendocument\.text-master',
'application/vnd\.oasis\.opendocument\.text-web',
],
'O arquivo não é um documento válido, verifique o tipo de arquivo.',
true,
private: true
)
);
$app->registerFileGroup(
'opportunity',
new FileGroup(
'formClaimUploadSample',
[
'^application/pdf',
'application/vnd\.openxmlformats-officedocument\.wordprocessingml\.document',
'application/vnd\.openxmlformats-officedocument\.wordprocessingml\.template',
'application/vnd\.ms-word\.document\.macroEnabled\.12',
'application/vnd\.ms-word\.template\.macroEnabled\.12',
'application/x-abiword',
'application/msword'
],
'O arquivo não é válido',
true,
)
);
}
public function createNotification($user, $message)
{
$message = $message;
$notification = new Notification;
$notification->user = $user;
$notification->message = $message;
$notification->save(true);
}
public function sendMailEvolutionClaim($registration, $message, $subject = null)
{
/** @var App $app */
$app = App::i();
$opportunity = $registration->opportunity;
$dataValue = [
'message' => $message,
'userName' => $registration->owner->name,
];
$message = $app->renderMailerTemplate('claim_refused', $dataValue);
if (array_key_exists('mailer.from', $app->config) && !empty(trim($app->config['mailer.from']))) {
/*
* Envia e-mail para o administrador da Oportunidade
*/
if($email = $registration->owner->emailPrivado ? $registration->owner->emailPrivado : $registration->owner->emailPublico) {
$app->createAndSendMailMessage([
'from' => $app->config['mailer.from'],
'to' => $email,
'subject' => $subject ?? $message['title'],
'body' => $message['body']
]);
}
}
}
public function sendMailClaim($entity)
{
/** @var App $app */
$app = App::i();
$registration = $entity->owner;
$registration->checkPermission('sendClaimMessage');
$opportunity = $registration->opportunity;
$dataValue = [
'opportunityName' => $opportunity->name,
'opportunityUrl' => $opportunity->singleUrl,
'registrationNumber' => $registration->number,
'registrationUrl' => $registration->singleUrl,
'date' => date('d/m/Y H:i:s', $_SERVER['REQUEST_TIME']),
'message' => $entity->description,
'userName' => $app->user->profile->name,
'userUrl' => $app->user->profile->url,
'file' => $entity->url
];
$message = $app->renderMailerTemplate('claim_form', $dataValue);
$email_to = $opportunity->claimEmail;
if (!$email_to) {
$email_to = $opportunity->owner->emailPrivado ? $opportunity->owner->emailPrivado : $opportunity->owner->emailPublico;
}
if (array_key_exists('mailer.from', $app->config) && !empty(trim($app->config['mailer.from']))) {
/*
* Envia e-mail para o administrador da Oportunidade
*/
$app->createAndSendMailMessage([
'from' => $app->config['mailer.from'],
'to' => $email_to,
'subject' => $message['title'],
'body' => $message['body']
]);
}
}
public function sendMailClaimCertificate($entity)
{
/** @var App $app */
$app = App::i();
$registration = $entity->owner;
$registration->checkPermission('sendClaimMessage');
$opportunity = $registration->opportunity;
$dataValue = [
'opportunityName' => $opportunity->name,
'opportunityUrl' => $opportunity->singleUrl,
'registrationNumber' => $registration->number,
'registrationUrl' => $registration->singleUrl,
'date' => date('d/m/Y H:i:s', $_SERVER['REQUEST_TIME']),
'message' => $entity->description,
'userName' => $registration->owner->name,
'userUrl' => $registration->owner->url ?: "#",
'file' => $entity->url
];
$message = $app->renderMailerTemplate('claim_certificate', $dataValue);
if (array_key_exists('mailer.from', $app->config) && !empty(trim($app->config['mailer.from']))) {
/*
* Envia e-mail para o administrador da Oportunidade
*/
$email = $registration->owner->emailPrivado ?: $registration->owner->emailPublico ?: $registration->owner->user->email;
$app->createAndSendMailMessage([
'from' => $app->config['mailer.from'],
'to' => $email,
'subject' => $message['title'],
'body' => $message['body']
]);
}
}
public function canManipulate($registration)
{
$app = App::i();
if ($this->claimOpen($registration)) {
if ((($app->user->profile->id == $registration->owner->id)) || ($app->user->profile->id == $registration->owner->user->profile->id) || $app->user->is('saasSuperAdmin')) {
if($registration->acceptClaim == 1 || $registration->acceptClaim == 4){
return true;
}
}
}
return false;
}
public function claimOpen($registration)
{
$today = new DateTime();
if ($today >= $registration->opportunity->claimFrom && $today <= $registration->opportunity->claimTo) {
return true;
}
return false;
}
}