Commit 1c6459cd authored by Stephane Bouvry's avatar Stephane Bouvry
Browse files

Refonte des versements (UI de recherche)

parent b43ec3b2
Loading
Loading
Loading
Loading
Loading
+123 −3
Original line number Diff line number Diff line
@@ -126,16 +126,136 @@ class ActivityPaymentController extends AbstractOscarController implements UseSe
    }


    public function indexAction()
    {
        $idActivity = $this->params()->fromRoute('idactivity', null);
        $page = $this->params()->fromQuery('page', 1);

        if ($idActivity) {
            $activity = $this->getProjectGrantService()->getActivityById($idActivity);
            $this->getOscarUserContextService()->check(Privileges::ACTIVITY_PAYMENT_SHOW, $activity);

            $method = $this->getHttpXMethod();

            if ($method != "GET" && !$this->getOscarUserContextService()->hasPrivileges(
                    Privileges::ACTIVITY_PAYMENT_MANAGE,
                    $activity
                )) {
                $this->getResponseBadRequest("Vous ne disposez pas des droits suffisants pour gérer les versements");
            }

            switch ($method) {
                case 'DELETE':
                    try {
                        /** @var ActivityPayment $payment */
                        $payment = $this->getProjectGrantService()->getActivityPaymentById(
                            $this->params()->fromQuery('id')
                        );
                        $this->getProjectGrantService()->deleteActivityPayment($payment);
                        return $this->getResponseOk("Le versement a bien été supprimé");
                    } catch (\Exception $e) {
                        $this->getLoggerService()->error($e->getTraceAsString());
                        return $this->getResponseInternalError(
                            sprintf(_("Impossible de supprimer le payment : %s"), $e->getMessage())
                        );
                    }


                case 'PUT':
                    return $this->getResponseDeprecated();


                case 'POST':
                    $action = $this->params()->fromPost('action');

                    $postedDatas = [
                        'amount'          => $this->params()->fromPost('amount'),
                        'activity'        => $activity,
                        'comment'         => $this->params()->fromPost('comment'),
                        'codeTransaction' => $this->params()->fromPost('codeTransaction'),
                        'currencyId'      => $this->params()->fromPost('currencyId'),
                        'status'          => $this->params()->fromPost('status'),
                        'rate'            => $this->params()->fromPost('rate'),
                        'datePredicted'   => $this->params()->fromPost('datePredicted'),
                        'datePayment'     => $this->params()->fromPost('datePayment'),
                    ];

                    if ($action == 'create') {
                        try {
                            $this->getProjectGrantService()->addNewActivityPayment($postedDatas);
                            return $this->getResponseOk("Le versement a bien été ajouté");
                        } catch (\Exception $e) {
                            $this->getLoggerService()->error($e->getTraceAsString());
                            return $this->getResponseInternalError(
                                sprintf(_("Impossible d'ajouter le payment : %s"), $e->getMessage())
                            );
                        }
                    }

                    elseif ($action == 'update') {
                        try {
                            $postedDatas['id'] = $this->params()->fromPost('id');
                            $this->getProjectGrantService()->updateActivityPayment($postedDatas);
                            return $this->getResponseOk("Le versement a bien été modifié");
                        } catch (\Exception $e) {
                            return $this->getResponseInternalError(
                                sprintf(_("Impossible de modifier le payment : %s"), $e->getMessage())
                            );
                        }
                    }

                    else {
                        return $this->getResponseBadRequest('Action inconnue');
                    }
            }

            $view = new JsonModel($this->getProjectGrantService()->getListActivityPaymentByActivity($activity));

            return $view;
        }

        // Page "Liste"
        else {
            $search = $this->params()->fromQuery('q', '');
            $page = $this->params()->fromQuery('page', 1);
            $type = $this->params()->fromQuery('type', "");
            $from = $this->params()->fromQuery('from', "");
            $to = $this->params()->fromQuery('to', "");
            $options = [
              'search' => $search,
              'page' => $page,
              'type' => $type,
              'from' => $from,
              'to' => $to,
            ];

            $out = [
                'params' => $this->vueJsParamJsonBase64([
                    'url_activity' => $this->url()->fromRoute('contract/show', ['id' => '']),
                ]),
            ];

            if( $this->isAjax() || $this->params()->fromQuery('f') === 'json' ) {
                $out['results'] = $this->getProjectGrantService()->getListPayments($options);
                return $this->jsonOutput($out);
            } else {
                return $out;
            }


//            return $this->getProjectGrantService()->getListPayments($options);
        }
    }

    /**
     * @return JsonModel
     */
    public function indexAction()
    public function indexOldAction()
    {
        die("POUET");
        $idActivity = $this->params()->fromRoute('idactivity', null);
        $page = $this->params()->fromQuery('page', 1);

        // Appel avec une idActivity => appel ajax depuis la fiche détaillée de
        // l'activité.
        if ($idActivity) {
            $activity = $this->getProjectGrantService()->getActivityById($idActivity);
            $this->getOscarUserContextService()->check(Privileges::ACTIVITY_PAYMENT_SHOW, $activity);
+107 −2
Original line number Diff line number Diff line
@@ -27,6 +27,111 @@ class ActivityPaymentRepository extends EntityRepository
        return $qb->getQuery()->getResult();
    }

    public function getPayments(array $options = []): array
    {

        $out = [];
        $out['page'] = $page = isset($options['page']) ? $options['page'] : 1;
        $out['limit'] = $limit = isset($options['limit']) ? $options['limit'] : 50;
        $out['from'] = $from = isset($options['from']) ? $options['from'] : null;
        $out['to'] = $to = isset($options['to']) ? $options['to'] : null;
        $out['type'] = $type = isset($options['type']) ? $options['type'] : null;
        $out['search'] = $search = isset($options['search']) ? $options['search'] : null;
        $out['total'] = 0;
        $out['entities'] = [];


        $params = [
            'page' => ($out['page'] - 1) * $limit,
            'limit' => $out['limit'],
        ];

        $types = [];

        $querySelectCount = "
        SELECT 
            count(p.id) as total 
        FROM activitypayment p 
            INNER JOIN activity a ON p.activity_id = a.id 
            LEFT JOIN project prj ON a.project_id = prj.id
        ";

        $querySelectFields = "
        SELECT
            p.id,
            p.amount,
            p.status,
            p.datepredicted,
            p.datepayment,
            p.comment,
            p.codetransaction,
            a.label as activity_label,
            a.codeEOTP as activity_numfinancier,
            a.oscarNum as activity_oscarnum,
            prj.acronym as project_acronym,
            COALESCE(p.datepayment, p.datepredicted) as dateref
            FROM activitypayment p
            INNER JOIN activity a ON p.activity_id = a.id
            LEFT JOIN project prj ON a.project_id = prj.id
        ";

        $where = [];
        if ($from) {
            $where[] = ' COALESCE(p.datepayment, p.datepredicted) >= :from';
            $params['from'] = $from;
        }
        if ($to) {
            $where[] = ' COALESCE(p.datepayment, p.datepredicted) <= :to';
            $params['to'] = $to;
        }
        if ($type) {
            $where[] = ' p.status = :type';
            $params['type'] = $type;
        }

        if( $search ){
            $where[] = ' (a.codeEOTP = :search OR a.oscarNum = :search OR a.label LIKE :searchLike OR prj.acronym LIKE :searchLike)';
            $params['search'] = $search;
            $params['searchLike'] = '%'.$search.'%';
        }

        $selectData = $querySelectFields;
        $selectCount = $querySelectCount;

        if (count($where)) {
            // $sql .= ' WHERE ' . implode(' AND ', $where);
            $whereAdded = ' WHERE ' . implode(' AND ', $where);
            $querySelectCount .= $whereAdded;
            $querySelectFields .= $whereAdded;
        }


        $querySelectFields .= " ORDER BY dateref DESC LIMIT :limit OFFSET :page ";
        //$sql .= " ORDER BY dateref DESC LIMIT :limit OFFSET :page ";

        $totalQueryResult = $this->getEntityManager()
            ->getConnection()
            ->executeQuery(
                $querySelectCount, $params
            )->fetchAssociative();

        $out['total'] = $totalQueryResult['total'];

        try {
            $result = $this->getEntityManager()
                ->getConnection()
                ->executeQuery(
                    $querySelectFields, $params
                )->fetchAllAssociative();
            $out['entities'] = $result;
        } catch (\Exception $e) {
            $out['query_error'] = $e->getMessage();
        }

        return $out;

    }

    public function getPaymentsPersonTodo(int $personId, string $dateRef = 'now'): array
    {
        $sql = file_get_contents(__DIR__ . '/../../../../sql/payments-person-todo.sql');
+21 −2
Original line number Diff line number Diff line
@@ -2866,11 +2866,29 @@ class ProjectGrantService implements UseGearmanJobLauncherService, UseOscarConfi
        return $result;
    }

    public function getListPayments(array $options = [])
    {
        try {
                /** @var ActivityPaymentRepository $repo */
                $repo = $this->getEntityManager()->getRepository(ActivityPayment::class);

                $payments = $repo->getPayments($options);

                return [
                    'payments' => $payments
                ];
        } catch (\Exception $e) {
            $this->getLoggerService()->error(json_encode($options, JSON_PRETTY_PRINT));
            throw new \Exception("Impossible d'afficher les versements : " . $e->getMessage());
        }
    }

    public function getListActivityPayment($search = '', $page = 1)
    {
        $qb = $this->getEntityManager()->getRepository(ActivityPayment::class)->createQueryBuilder('p')
            ->addSelect('c, COALESCE(p.datePredicted, p.datePayment) as HIDDEN dateSort')
            ->addSelect('c, a.oscarNum, a.id, prj.acronym, a.label, COALESCE(p.datePredicted, p.datePayment) as HIDDEN dateSort')
            ->innerJoin('p.activity', 'a')
            ->leftJoin('a.project', 'prj')
            ->innerJoin('p.currency', 'c')
            ->addOrderBy('dateSort', 'DESC');

@@ -2881,7 +2899,8 @@ class ProjectGrantService implements UseGearmanJobLauncherService, UseOscarConfi
                    ->setParameter('ids', $ids);
            }
        }

        var_dump($qb->getQuery()->getArrayResult());
        die("LA");
        return [
            'search' => $search,
            'payments' => new UnicaenDoctrinePaginator($qb, $page, 50)
+3 −3
Original line number Diff line number Diff line
@@ -261,9 +261,9 @@ echo getenv('APPLICATION_ENV') ?: 'development' ?>">

                                <?php if ($this->grant()->privilege(\Oscar\Provider\Privileges::ACTIVITY_PAYMENT_SHOW)): ?>
                                    <li role="presentation" class="dropdown-header"><i class="icon-bank"></i> <?= $this->translate("Finance") ?></li>
                                    <li><a class="dropdown-item" href="<?= $this->url('payment/income') ?>"><?= $this->translate("Prochains versements") ?></a></li>
                                    <li><a class="dropdown-item" href="<?= $this->url('payment/late') ?>"><?= $this->translate("Versements en retard") ?></a></li>
                                    <li><a class="dropdown-item" href="<?= $this->url('payment/difference') ?>"><?= $this->translate("Écarts de paiement") ?></a></li>
                                    <li><a class="dropdown-item" href="<?= $this->url('payment') ?>?preset=coming"><?= $this->translate("Prochains versements") ?></a></li>
                                    <li><a class="dropdown-item" href="<?= $this->url('payment') ?>?preset=late"><?= $this->translate("Versements en retard") ?></a></li>
                                    <li><a class="dropdown-item" href="<?= $this->url('payment') ?>?preset=ecarts"><?= $this->translate("Écarts de paiement") ?></a></li>
                                    <li><a class="dropdown-item" href="<?= $this->url('payment') ?>"><?= $this->translate("Tous les versements") ?></a></li>
                                <?php endif; ?>
                            <?php endif; ?>
+2 −214
Original line number Diff line number Diff line
<section class="container">
    <h1><i class="icon-bank"></i> Versements</h1>

    <form action="<?= $this->url() ?>" method="get" class="form" id="search">
        <div class="input-group input-group-lg">
            <input placeholder="Rechercher dans l'intitulé, code PFI, N°Oscar..."
                   type="search"
                   class="form-control input-lg"
                   name="q"
                   value="<?= isset($search) ? htmlentities($search) : "" ?>"/>

                <span class="input-group-btn">
                    <button type="submit" class="btn btn-primary">Rechercher</button>
                </span>
        </div>
    </form>


    <?php if( count($payments) ): ?>
        <?php
        $annee = '';
        $mois = '';
        /** @var \Oscar\Entity\ActivityPayment $payment */
        foreach ($payments as $payment):

            // 2018 Janvier :
            // Les écarts de payements ne sont pas datés et sont une donnée spécifique
            // qui n'est pas lieu dans cette écran (dixit : Agence Comptable)
            if( $payment->getStatus() == \Oscar\Entity\ActivityPayment::STATUS_ECART ) continue;

            $dateRef = $payment->getStatus() ==
                \Oscar\Entity\ActivityPayment::STATUS_REALISE ?
                $payment->getDatePayment() :
                $payment->getDatePredicted();

            // En cas de problème de date
            if( $dateRef ) {
                if ($annee != $dateRef->format('Y')) {
                    $annee = $dateRef->format('Y');
                    $mois = '';
                    echo "<h2>$annee</h2>";
                }

                $currentMois = ucfirst($this->moment($dateRef, 'F'));
                if ($mois != $currentMois) {
                    $mois = $currentMois;
                    echo "<h3>$mois</h3>";
                }
            }


            ?>

            <?php if( $payment->getActivity() ): ?>
            <?= $this->partial('/oscar/activity-payment/payment-item.phtml', ['payment' => $payment ]) ?>
        <?php endif; ?>
        <?php endforeach; ?>
        <?= $this->pager($payments, preg_replace("/\\??&page=[0-9]*/", '', $_SERVER['REQUEST_URI']) . '?&page=%s') ?>

    <?php else: ?>
        <div class="alert alert-info">
            Aucun versement prévu pour le mois à venir
        </div>
    <?php endif; ?>
    <div id="payments" data-params="<?= $params ?>"></div>
    <?php $this->Vite()->addJs('src/ActivityPayments.js') ?>
</section>
<script>

            require(['bootbox','modalform'], function(bootbox, ModalForm) {
                $('.payment-delete-btn').on('click', function (e) {
                    e.preventDefault();
                    var   url = $(this).attr('href')
                        , modal = ModalForm.modal()
                        , modalContent = modal.content;

                    modalContent.empty().unbind();

                    bootbox.confirm("Supprimer le versement ?", function(response){
                        if( response ){
                            var jqxhr = $.ajax({
                                'type': 'DELETE',
                                'url': url
                            }).done(function(content) {
                                document.location.reload();
                            }).fail(function(){
                                Oscar.waitScreen('Erreur lors du traitement des données', 'error');
                            });
                        }
                    });
                });

                $('.payment-edit-btn').on('click', function (e) {
                        e.preventDefault();
                        var   url = $(this).attr('href')
                            , modal = ModalForm.modal()
                            , modalContent = modal.content;

                        modalContent.empty().unbind();

                        var jqxhr = $.ajax({
                            'type': 'GET',
                            'url': url
                        }).done(function(content){
                            var title = "Modification"
                                , $title
                                , modalContent = $(content);

                            if(modalContent && ($title = modalContent.find('h1')) ){
                                title = $title.html();
                                //modalContent.find('h1').remove();
                            }

                            ModalForm.show(title, modalContent);

                            modalContent.on('click', '.button-back', function(e){
                                e.preventDefault();
                                ModalForm.hide();
                            });

                            modalContent.on('click', '[type="submit"]', function(e){
                                e.preventDefault();
                                var form = $('form', modalContent)
                                    , formMethod = (form.attr('method') || 'get')
                                    , urlPost = (form.attr('action') || url) ;

                                require(['jquery-serialize'], function(){
                                    var datas = $('form', modalContent).serializeObject();
                                    $.ajax({
                                        'url': urlPost,
                                        'method': formMethod,
                                        'data': datas
                                    }, datas).done(function(content){
                                        modalContent.html(content);
                                        document.location.reload();
                                    }).fail(function(){
                                        Oscar.waitScreen('Erreur lors du traitement des données', 'error');
                                    });
                                });
                            });
                        }).fail(function( xhr, status, response){
                            var title = 'Erreur Oscar',
                                content = 'Le serveur à retourné une erreur non-identifiée';
                            if( xhr.status === 400 ){
                                title = 'Erreur de saisie';
                                content = "Votre requète n'a pas été traitée !";
                            }
                            if( xhr.responseJSON && xhr.responseJSON.error ){ content = xhr.responseJSON.error;}
                            Oscar.waitScreen('<h1><i class="icon-attention-1"></i>' + title + '</h1>' + content, 'error');
                        });
                        jqxhr.always(function(){console.log('always()', arguments)});
                    });
                });
                /*// Données
                var url = this.model.collection.urlEdit +this.model.get('id')
                    , modal = ModalForm.modal()
                    , modalContainer = modal.container
                    , modalTitle = modal.title
                    , modalContent = modal.content;

                // On supprime l'ancien contenu de la modale
                modalContent.empty().unbind();

                var jqxhr = $.ajax({
                    'type': 'GET',
                    'url': url
                }).done(function(content){
                    var title = "Modification"
                        , $title
                        , modalContent = $(content);

                    if(modalContent && ($title = modalContent.find('h1')) ){
                        title = $title.html();
                        //modalContent.find('h1').remove();
                    }

                    ModalForm.show(title, modalContent);

                    modalContent.on('click', '.button-back', function(e){
                        e.preventDefault();
                        ModalForm.hide();
                    });

                    modalContent.on('click', '[type="submit"]', function(e){
                        e.preventDefault();
                        var form = $('form', modalContent)
                            , formMethod = (form.attr('method') || 'get')
                            , urlPost = (form.attr('action') || url) ;

                        require(['jquery-serialize'], function(){
                            var datas = $('form', modalContent).serializeObject();
                            console.log('Send', datas, 'to', urlPost);
                            $.ajax({
                                'url': urlPost,
                                'method': formMethod,
                                'data': datas
                            }, datas).done(function(content){
                                modalContent.html(content);
                                model.collection.fetch();
                            }).fail(function(){
                                Oscar.waitScreen('Erreur lors du traitement des données', 'error');
                            });
                        });
                    });
                }).fail(function( xhr, status, response){
                    var title = 'Erreur Oscar',
                        content = 'Le serveur à retourné une erreur non-identifiée';
                    if( xhr.status === 400 ){
                        title = 'Erreur de saisie';
                        content = "Votre requète n'a pas été traitée !";
                    }
                    if( xhr.responseJSON && xhr.responseJSON.error ){ content = xhr.responseJSON.error;}
                    Oscar.waitScreen('<h1><i class="icon-attention-1"></i>' + title + '</h1>' + content, 'error');
                });
                jqxhr.always(function(){console.log('always()', arguments)});
            });*/

</script>
 No newline at end of file
Loading