GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — user-entity ( 83f5aa...127474 )
by Luis Ramón
03:41
created

GroupController::apiNewUserAction()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 31
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 31
rs 8.8571
cc 3
eloc 19
nc 2
nop 1
1
<?php
2
/*
3
  ÁTICA - Aplicación web para la gestión documental de centros educativos
4
5
  Copyright (C) 2015-2016: Luis Ramón López López
6
7
  This program is free software: you can redistribute it and/or modify
8
  it under the terms of the GNU Affero General Public License as published by
9
  the Free Software Foundation, either version 3 of the License, or
10
  (at your option) any later version.
11
12
  This program is distributed in the hope that it will be useful,
13
  but WITHOUT ANY WARRANTY; without even the implied warranty of
14
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
  GNU Affero General Public License for more details.
16
17
  You should have received a copy of the GNU Affero General Public License
18
  along with this program.  If not, see [http://www.gnu.org/licenses/].
19
*/
20
21
namespace AppBundle\Controller;
22
23
use AppBundle\Entity\Agreement;
24
use AppBundle\Entity\Group;
25
use AppBundle\Entity\User;
26
use AppBundle\Entity\Workday;
27
use AppBundle\Form\Model\Calendar;
28
use Doctrine\Common\Collections\ArrayCollection;
29
use Doctrine\ORM\EntityManager;
30
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
31
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
32
use Symfony\Component\HttpFoundation\JsonResponse;
33
use Symfony\Component\HttpFoundation\Request;
34
35
/**
36
 * @Route("/alumnado")
37
 * @Security("is_granted('ROLE_GROUP_TUTOR')")
38
 */
39
class GroupController extends BaseController
40
{
41
    /**
42
     * @Route("", name="admin_tutor_group", methods={"GET"})
43
     */
44
    public function groupIndexAction(Request $request)
45
    {
46
        /** @var EntityManager $em */
47
        $em = $this->getDoctrine()->getManager();
48
49
        /** @var User $user */
50
        $user = $this->getUser();
51
52
        $qb = $em->getRepository('AppBundle:Group')
53
            ->createQueryBuilder('g')
54
            ->innerJoin('g.training', 't')
55
            ->innerJoin('t.department', 'd')
56
            ->orderBy('d.name')
57
            ->addOrderBy('t.name')
58
            ->addOrderBy('g.name');
59
60
        if (!$user->isGlobalAdministrator()) {
61
            $qb = $qb
62
                ->where('g.id IN (:groups)')
63
                ->orWhere('d.head = :user')
64
                ->setParameter('groups', $user->getTutorizedGroups()->toArray())
65
                ->setParameter('user', $user);
66
        }
67
68
        $items = $qb->getQuery()->getResult();
69
70
        if (count($items) == 1) {
71
            return $this->groupDetailIndexAction($items[0], $request);
72
        }
73
74
        return $this->render('group/group_index.html.twig',
75
            [
76
                'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
77
                'title' => null,
78
                'elements' => $items
79
            ]);
80
    }
81
82
    /**
83
     * @Route("/grupo/{id}", name="admin_group_students", methods={"GET"})
84
     * @Security("is_granted('GROUP_MANAGE', group)")
85
     */
86
    public function groupDetailIndexAction(Group $group, Request $request)
87
    {
88
        /** @var EntityManager $em */
89
        $em = $this->getDoctrine()->getManager();
90
91
        $usersQuery = $em->createQuery('SELECT u FROM AppBundle:User u WHERE u.studentGroup = :group')
92
            ->setParameter('group', $group);
93
94
        $paginator = $this->get('knp_paginator');
95
        $pagination = $paginator->paginate(
96
            $usersQuery,
97
            $request->query->getInt('page', 1),
98
            $this->getParameter('page.size'),
99
            [
100
                'defaultSortFieldName' => 'u.lastName',
101
                'defaultSortDirection' => 'asc'
102
            ]
103
        );
104
105
        return $this->render('group/manage_students.html.twig', [
106
            'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
107
            'breadcrumb' => [
108
                ['fixed' => (string) $group],
109
            ],
110
            'title' => $group->getName(),
111
            'pagination' => $pagination
112
        ]);
113
114
    }
115
116
    /**
117
     * @Route("/alumnado/estudiante/{id}", name="student_detail", methods={"GET", "POST"})
118
     * @Security("is_granted('GROUP_MANAGE', student.getStudentGroup())")
119
     */
120
    public function studentIndexAction(User $student, Request $request)
121
    {
122
        $form = $this->createForm('AppBundle\Form\Type\StudentUserType', $student, [
123
            'admin' => $this->isGranted('ROLE_ADMIN')
124
        ]);
125
126
        $form->handleRequest($request);
127
128
        if ($form->isSubmitted() && $form->isValid()) {
129
130
            // Guardar el usuario en la base de datos
131
132
            // Probar a guardar los cambios
133
            try {
134
                $this->getDoctrine()->getManager()->flush();
135
                $this->addFlash('success', $this->get('translator')->trans('alert.saved', [], 'student'));
136
                return $this->redirectToRoute('admin_group_students', ['id' => $student->getStudentGroup()->getId()]);
137
            } catch (\Exception $e) {
138
                $this->addFlash('error', $this->get('translator')->trans('alert.not_saved', [], 'student'));
139
            }
140
        }
141
        return $this->render('group/form_student.html.twig',
142
            [
143
                'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
144
                'breadcrumb' => [
145
                    ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
146
                    ['fixed' => (string) $student],
147
                ],
148
                'title' => (string) $student,
149
                'user' => $student,
150
                'form' => $form->createView()
151
            ]);
152
    }
153
154
    /**
155
     * @Route("/seguimiento/seleccion/{id}", name="admin_group_student_agreements", methods={"GET"})
156
     * @Security("is_granted('GROUP_MANAGE', student.getStudentGroup())")
157
     */
158
    public function studentAgreementIndexAction(User $student)
159
    {
160
        $agreements = $student->getStudentAgreements();
161
162
        return $this->render('group/calendar_agreement_select.html.twig',
163
            [
164
                'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
165
                'breadcrumb' => [
166
                    ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
167
                    ['fixed' => (string) $student],
168
                ],
169
                'student' => $student,
170
                'elements' => $agreements,
171
                'route_name' => 'admin_group_student_calendar'
172
            ]);
173
    }
174
175
    /**
176
     * @Route("/seguimiento/acuerdo/{id}", name="admin_group_student_calendar", methods={"GET"})
177
     * @Security("is_granted('AGREEMENT_ACCESS', agreement)")
178
     */
179
    public function studentCalendarAgreementIndexAction(Agreement $agreement)
180
    {
181
        $student = $agreement->getStudent();
182
183
        $calendar = $this->getDoctrine()->getManager()->getRepository('AppBundle:Workday')->getArrayCalendar($agreement->getWorkdays());
184
        $title = (string) $agreement->getWorkcenter();
185
186
        return $this->render('group/calendar_agreement.html.twig',
187
            [
188
                'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
189
                'breadcrumb' => [
190
                    ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
191
                    ['fixed' => (string) $student, 'path' => 'admin_group_student_agreements', 'options' => ['id' => $student->getId()]],
192
                    ['fixed' => $title],
193
                ],
194
                'title' => $title,
195
                'user' => $this->getUser(),
196
                'calendar' => $calendar,
197
                'agreement' => $agreement,
198
                'route_name' => 'admin_group_student_tracking'
199
            ]);
200
    }
201
202
    public function deleteWorkdayAction(Agreement $agreement, Request $request)
203
    {
204
        $this->denyAccessUnlessGranted('AGREEMENT_MANAGE', $agreement);
205
206
        $em = $this->getDoctrine()->getManager();
207
208
        if ($request->request->has('ids')) {
209
            try {
210
                $ids = $request->request->get('ids');
211
212
                $dates = $em->getRepository('AppBundle:Workday')->createQueryBuilder('w')
213
                    ->where('w.id IN (:ids)')
214
                    ->andWhere('w.agreement = :agreement')
215
                    ->setParameter('ids', $ids)
216
                    ->setParameter('agreement', $agreement)
217
                    ->getQuery()
218
                    ->getResult();
219
220
                /** @var Workday $date */
221
                foreach ($dates as $date) {
222
                    if ($date->getTrackedHours() === 0) {
223
                        $em->remove($date);
224
                    }
225
                }
226
                $em->flush();
227
228
                $agreement->setFromDate($this->getDoctrine()->getManager()->getRepository('AppBundle:Agreement')->getRealFromDate($agreement));
229
                $agreement->setToDate($this->getDoctrine()->getManager()->getRepository('AppBundle:Agreement')->getRealToDate($agreement));
230
231
                $em->flush();
232
                $this->addFlash('success', $this->get('translator')->trans('alert.deleted', [], 'calendar'));
233
            } catch (\Exception $e) {
234
                $this->addFlash('error', $this->get('translator')->trans('alert.not_deleted', [], 'calendar'));
235
            }
236
        }
237
        return $this->redirectToRoute('admin_group_student_calendar', ['id' => $agreement->getId()]);
238
    }
239
240
    /**
241
     * @Route("/seguimiento/acuerdo/{id}/operacion", name="admin_group_student_workday_operation", methods={"POST"})
242
     * @Security("is_granted('AGREEMENT_ACCESS', agreement)")
243
     */
244
    public function operationWorkdayAction(Agreement $agreement, Request $request)
245
    {
246
        if ($request->request->has('delete')) {
247
            return $this->deleteWorkdayAction($agreement, $request);
248
        } elseif ($request->request->has('week_lock') || ($request->request->has('week_unlock'))) {
249
            return $this->lockWeekAction($agreement, $request, $request->request->has('week_lock'), 'admin_group_student_calendar');
250
        } else {
251
            return $this->lockWorkdayAction($agreement, $request, $request->request->has('lock'), 'admin_group_student_calendar');
252
        }
253
    }
254
255
    /**
256
     * @Route("/seguimiento/acuerdo/{id}/incorporar", name="admin_group_student_workday_add", methods={"GET", "POST"})
257
     * @Security("is_granted('AGREEMENT_MANAGE', agreement)")
258
     */
259
    public function addAgreementCalendarAction(Agreement $agreement, Request $request)
260
    {
261
        $totalHours = $agreement->getStudent()->getStudentGroup()->getTraining()->getProgramHours();
262
        $agreementHours = $this->getDoctrine()->getManager()->getRepository('AppBundle:Agreement')->countHours($agreement);
263
        $studentHours = $this->getDoctrine()->getManager()->getRepository('AppBundle:User')->countAgreementHours($agreement->getStudent());
264
265
        $calendar = new Calendar(max(0, $totalHours - $studentHours));
266
267
        $form = $this->createForm('AppBundle\Form\Type\CalendarType', $calendar, [
268
            'program_hours' => $totalHours
269
        ]);
270
271
        $form->handleRequest($request);
272
273
        $workdays = new ArrayCollection();
274
275
        if ($form->isValid() && $form->isSubmitted()) {
276
            $workdays = $this->getDoctrine()->getManager()->getRepository('AppBundle:Workday')->createCalendar($calendar, $agreement);
277
278
            if ($request->request->has('submit')) {
279
                $this->getDoctrine()->getManager()->flush();
280
                $agreement->setFromDate($this->getDoctrine()->getManager()->getRepository('AppBundle:Agreement')->getRealFromDate($agreement));
281
                $agreement->setToDate($this->getDoctrine()->getManager()->getRepository('AppBundle:Agreement')->getRealToDate($agreement));
282
                $this->getDoctrine()->getManager()->flush();
283
                $this->addFlash('success', $this->get('translator')->trans('alert.saved', [], 'calendar'));
284
                return $this->redirectToRoute('admin_group_student_calendar', ['id' => $agreement->getId()]);
285
            }
286
        }
287
288
        $student = $agreement->getStudent();
289
290
        $calendar = $this->getDoctrine()->getManager()->getRepository('AppBundle:Workday')->getArrayCalendar($workdays);
291
292
        return $this->render('group/calendar_agreement_workday_add.html.twig', [
293
            'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
294
            'breadcrumb' => [
295
                ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
296
                ['fixed' => (string) $student, 'path' => 'admin_group_student_agreements', 'options' => ['id' => $student->getId()]],
297
                ['fixed' => (string) $agreement->getWorkcenter()],
298
                ['fixed' => $this->get('translator')->trans('form.add', [], 'calendar')]
299
            ],
300
            'agreement' => $agreement,
301
            'total_hours' => $totalHours,
302
            'agreement_hours' => $agreementHours,
303
            'student_hours' => $studentHours,
304
            'form' => $form->createView(),
305
            'calendar' => $calendar
306
        ]);
307
    }
308
309
    /**
310
     * @Route("/seguimiento/acuerdo/jornada/{id}", name="admin_group_student_tracking", methods={"GET", "POST"})
311
     * @Security("is_granted('AGREEMENT_ACCESS', workday.getAgreement())")
312
     */
313
    public function studentWorkdayAction(Workday $workday, Request $request)
314
    {
315
        $student = $workday->getAgreement()->getStudent();
316
317
        return $this->baseWorkdayAction($workday, $request, [
318
            'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
319
            'breadcrumb' => [
320
                ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
321
                ['fixed' => (string) $student, 'path' => 'admin_group_student_agreements', 'options' => ['id' => $student->getId()]],
322
                ['fixed' => (string) $workday->getAgreement()->getWorkcenter(), 'path' => 'admin_group_student_calendar', 'options' => ['id' => $workday->getAgreement()->getId()]],
323
                ['fixed' => $workday->getDate()->format('d/m/Y')]
324
            ],
325
            'back_route_name' => 'admin_group_student_calendar'
326
        ]);
327
    }
328
329
    /**
330
     * @Route("/seguimiento/acuerdo/jornada/modificar/{id}", name="admin_group_student_workday_form", methods={"GET", "POST"})
331
     * @Security("is_granted('AGREEMENT_MANAGE', workday.getAgreement())")
332
     */
333
    public function agreementCalendarFormAction(Workday $workday, Request $request)
334
    {
335
        $form = $this->createForm('AppBundle\Form\Type\WorkdayType', $workday);
336
        $form->handleRequest($request);
337
338
        if ($form->isValid() && $form->isSubmitted()) {
339
            $this->getDoctrine()->getManager()->flush();
340
            $this->addFlash('success', $this->get('translator')->trans('alert.saved', [], 'calendar'));
341
            return $this->redirectToRoute('admin_group_student_calendar', ['id' => $workday->getAgreement()->getId()]);
342
        }
343
        $student = $workday->getAgreement()->getStudent();
344
345
        $dow = ((6 + (int) $workday->getDate()->format('w')) % 7);
346
        $title = $this->get('translator')->trans('dow' . $dow, [], 'calendar') . ', ' . $workday->getDate()->format('d/m/Y');
347
348
        return $this->render('group/calendar_agreement_workday_form.html.twig', [
349
            'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
350
            'breadcrumb' => [
351
                ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
352
                ['fixed' => (string) $student, 'path' => 'admin_group_student_agreements', 'options' => ['id' => $student->getId()]],
353
                ['fixed' => (string) $workday->getAgreement()->getWorkcenter(), 'path' => 'admin_group_student_calendar', 'options' => ['id' => $workday->getAgreement()->getId()]],
354
                ['fixed' => $title],
355
            ],
356
            'form' => $form->createView(),
357
            'workday' => $workday
358
        ]);
359
    }
360
361
    /**
362
     * @Route("/seguimiento/acuerdo/nuevo/{id}", name="admin_group_student_agreement_new", methods={"GET", "POST"})
363
     * @Security("is_granted('GROUP_CREATE_AGREEMENT', user.getStudentGroup())")
364
     */
365
    public function agreementNewFormAction(User $user, Request $request)
366
    {
367
        $agreement = new Agreement();
368
        $agreement->setStudent($user);
369
        $this->getDoctrine()->getManager()->persist($agreement);
370
371
        return $this->agreementFormAction($agreement, $request);
372
    }
373
374
    /**
375
     * @Route("/seguimiento/acuerdo/modificar/{id}", name="admin_group_student_agreement_form", methods={"GET", "POST"})
376
     * @Security("is_granted('AGREEMENT_MANAGE', agreement)")
377
     */
378
    public function agreementFormAction(Agreement $agreement, Request $request)
379
    {
380
        $form = $this->createForm('AppBundle\Form\Type\AgreementType', $agreement);
381
382
        $form->handleRequest($request);
383
384
        $student = $agreement->getStudent();
385
386
        if ($form->isValid() && $form->isSubmitted()) {
387
            // Probar a guardar los cambios
388
            try {
389
                $this->getDoctrine()->getManager()->flush();
390
                $this->addFlash('success', $this->get('translator')->trans('alert.saved', [], 'group'));
391
                return $this->redirectToRoute('admin_group_student_agreements', ['id' => $student->getId()]);
392
            } catch (\Exception $e) {
393
                $this->addFlash('error', $this->get('translator')->trans('alert.not_saved', [], 'group'));
394
            }
395
        }
396
397
        $title = (null === $agreement->getId())
398
            ? $this->get('translator')->trans('form.new_agreement', [], 'group')
399
            : (string) $agreement->getWorkcenter();
400
401
        return $this->render('group/form_agreement.html.twig',
402
            [
403
                'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
404
                'breadcrumb' => [
405
                    ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
406
                    ['fixed' => (string) $student, 'path' => 'admin_group_student_agreements', 'options' => ['id' => $student->getId()]],
407
                    ['fixed' => $title]
408
                ],
409
                'form' => $form->createView(),
410
                'agreement' => $agreement
411
            ]);
412
    }
413
414
    /**
415
     * @Route("/seguimiento/acuerdo/eliminar/{id}", name="admin_group_student_agreement_delete", methods={"GET", "POST"})
416
     * @Security("is_granted('AGREEMENT_MANAGE', agreement)")
417
     */
418
    public function agreementDeleteAction(Agreement $agreement, Request $request)
419
    {
420
        $student = $agreement->getStudent();
421
422
        if ('POST' === $request->getMethod() && $request->request->has('delete')) {
423
424
            // Eliminar el acuerdo de la base de datos
425
            $this->getDoctrine()->getManager()->getRepository('AppBundle:Agreement')->delete($agreement);
426
            try {
427
                $this->getDoctrine()->getManager()->flush();
428
                $this->addFlash('success', $this->get('translator')->trans('alert.agreement_deleted', [], 'group'));
429
            } catch (\Exception $e) {
430
                $this->addFlash('error', $this->get('translator')->trans('alert.agreement_not_deleted', [], 'group'));
431
            }
432
            return $this->redirectToRoute('admin_group_student_agreements', ['id' => $student->getId()]);
433
        }
434
435
        $title = (string) $agreement->getWorkcenter();
436
437
        return $this->render('group/delete_agreement.html.twig', [
438
            'menu_item' => $this->get('app.menu_builders_chain')->getMenuItemByRouteName('admin_tutor_group'),
439
            'breadcrumb' => [
440
                ['fixed' => $student->getStudentGroup()->getName(), 'path' => 'admin_group_students', 'options' => ['id' => $student->getStudentGroup()->getId()]],
441
                ['fixed' => (string) $student, 'path' => 'admin_group_student_agreements', 'options' => ['id' => $student->getId()]],
442
                ['fixed' => $title]
443
            ],
444
            'title' => $title,
445
            'agreement' => $agreement
446
        ]);
447
    }
448
449
    /**
450
     * @Route("/api/usuario/crear", name="api_user_new", methods={"GET", "POST"})
451
     * @Security("is_granted('ROLE_DEPARTMENT_HEAD')")
452
     */
453
    public function apiNewUserAction(Request $request)
454
    {
455
        $em = $this->getDoctrine()->getManager();
456
        
457
        $newUser = new User();
458
        
459
        $form = $this->createForm('AppBundle\Form\Type\NewUserType', $newUser, [
460
            'action' => $this->generateUrl('api_user_new'),
461
            'method' => 'POST'
462
        ]);
463
        $form->handleRequest($request);
464
465
        if ($form->isValid() && $form->isSubmitted()) {
466
            $newUser
467
                ->setEnabled(true)
468
                ->setGlobalAdministrator(false);
469
            
470
            $em->persist($newUser);
471
            $em->flush();
472
473
            return new JsonResponse([
474
                'success' => true,
475
                'id' => $newUser->getId(),
476
                'name' => $newUser->getFullPersonDisplayName()
477
            ]);
478
        }
479
480
        return $this->render('group/new_user_partial.html.twig', [
481
            'form' => $form->createView()
482
        ]);
483
    }
484
}
485