JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | FacturesController.php
  • File: FacturesController.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/crm/controllers/FacturesController.php
  • File size: 20.75 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php
// controllers/FacturesController.php
require_once __DIR__ . '/../models/Facture.php';
require_once __DIR__ . '/../models/Client.php';
require_once __DIR__ . '/../models/FactureLigne.php';
require_once __DIR__ . '/../models/Projet.php';
require_once __DIR__ . '/../models/ProjetDocumentLink.php';
require_once __DIR__ . '/../models/ImportMask.php';
require_once __DIR__ . '/../lib/CsvService.php';
require_once __DIR__ . '/../lib/ImportAssistant.php';
require_once __DIR__ . '/../models/ReglagesGestion.php';

class FacturesController {
    private $model;
    private $clientModel;
    private $projectModel;
    private $projectLinkModel;
    private $importMaskModel;
    private const IMPORT_ENTITY = 'factures';
    public function __construct() {
        $this->model = new Facture();
        $this->clientModel = new Client();
        $this->projectModel = new Projet();
        $this->projectLinkModel = new ProjetDocumentLink();
        $this->importMaskModel = new ImportMask();
    }

    public function handleRequest() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_import_mask'])) {
            $this->saveImportMask();
            return;
        }

        $action = $_GET['action'] ?? '';
        switch ($action) {
            case 'add':
                $this->add(); break;
            case 'edit':
                $this->edit(); break;
            case 'apercu':
                $this->apercu(); break;
            case 'pdf':
                require_once __DIR__ . '/PdfFactureController.php';
                $pdfCtrl = new PdfFactureController();
                $pdfCtrl->generate($_GET['id'] ?? null); break;
            case 'xml':
                require_once __DIR__ . '/FactureXmlController.php';
                $xmlCtrl = new FactureXmlController();
                $xmlCtrl->generate($_GET['id'] ?? null); break;
            case 'delete':
                $this->delete(); break;
            case 'export_csv':
                $this->exportCsv(); break;
            case 'template_csv':
                $this->downloadTemplate(); break;
            case 'import_csv':
                $this->importCsv(); break;
            case 'reset_increment':
                $this->resetIncrement(); break;
            default:
                $this->list(); break;
        }
    }

    private function getExportFields() {
        return [
            'id' => 'ID',
            'numero' => 'Numero',
            'client_id' => 'Client ID',
            'client_prenom' => 'Prénom client',
            'client_nom' => 'Client',
            'date_facture' => 'Date de la facture',
            'montant' => 'Montant total',
            'montant_regle' => 'Montant regle',
            'statut' => 'Statut',
            'description' => 'Description',
            'remise_generale' => 'Remise generale',
            'type_remise_generale' => 'Type remise generale',
        ];
    }

    private function getImportFields() {
        return [
            'client_id' => 'Client ID',
            'client_prenom' => 'Prénom client',
            'numero' => 'Numero',
            'date_facture' => 'Date de la facture',
            'montant' => 'Montant total',
            'montant_regle' => 'Montant regle',
            'statut' => 'Statut',
            'description' => 'Description',
            'remise_generale' => 'Remise generale',
            'type_remise_generale' => 'Type remise generale',
        ];
    }

    private function exportCsv() {
        $fields = CsvService::sanitizeSelectedFields($this->getExportFields(), $_GET['fields'] ?? null);
        CsvService::downloadCsv('factures.csv', $fields, $this->model->getAll());
    }

    private function downloadTemplate() {
        CsvService::downloadTemplate('factures_template.csv', array_keys($this->getImportFields()));
    }

    private function importCsv() {
        try {
            $rows = CsvService::parseUploadedCsv($_FILES['csv_file'] ?? null);
            $mask = $this->resolveImportMaskFromRequest();
            $mappings = $this->resolveImportMappings($mask);
            $savedMaskName = $this->persistImportMaskIfRequested($mappings);
            $imported = 0;

            foreach ($rows as $row) {
                $mappedRow = ImportAssistant::mapRow($row, $this->getImportFields(), $mappings);
                $clientId = trim((string) ($mappedRow['client_id'] ?? ''));
                if ($clientId === '') {
                    continue;
                }

                $typeRemise = trim((string) ($mappedRow['type_remise_generale'] ?? 'euro'));
                $this->model->create([
                    'client_id' => $clientId,
                    'date_facture' => trim((string) ($mappedRow['date_facture'] ?? '')) ?: date('Y-m-d'),
                    'numero' => trim((string) ($mappedRow['numero'] ?? '')),
                    'montant' => (float) ($mappedRow['montant'] ?? 0),
                    'montant_regle' => (float) ($mappedRow['montant_regle'] ?? 0),
                    'statut' => trim((string) ($mappedRow['statut'] ?? '')) ?: 'En attente',
                    'description' => trim((string) ($mappedRow['description'] ?? '')),
                    'remise_generale' => (float) ($mappedRow['remise_generale'] ?? 0),
                    'type_remise_generale' => in_array($typeRemise, ['euro', 'pourcent'], true) ? $typeRemise : 'euro',
                ]);
                $imported++;
            }

            $message = $imported . ' facture(s) importe(s).';
            if ($savedMaskName !== '') {
                $message .= ' Masque enregistre : ' . $savedMaskName . '.';
            }
            $this->redirectWithMessage('success', $message);
        } catch (RuntimeException $e) {
            $this->redirectWithMessage('error', $e->getMessage());
        }
    }

    private function saveImportMask() {
        try {
            $mappings = ImportAssistant::extractMappingsFromRequest($this->getImportFields());
            if (count(array_filter($mappings, static function ($value) {
                return $value !== '';
            })) === 0) {
                throw new RuntimeException('Renseignez au moins une correspondance de champ.');
            }

            $this->importMaskModel->save(
                self::IMPORT_ENTITY,
                trim((string) ($_POST['mask_name'] ?? '')),
                $mappings
            );

            $this->redirectWithMessage('success', 'Masque d\'import enregistre.');
        } catch (RuntimeException $e) {
            $this->redirectWithMessage('error', $e->getMessage());
        }
    }

    private function apercu() {
        $id = $_GET['id'] ?? null;
        if (!$id) return;
        $facture = $this->model->getById($id);
        if (!$facture) {
            return;
        }
        $client = null;
        if (isset($facture['client_id'])) {
            $stmt = Database::getInstance()->getConnection()->prepare('SELECT * FROM clients WHERE id = ?');
            $stmt->execute([$facture['client_id']]);
            $client = $stmt->fetch(PDO::FETCH_ASSOC);
        }
        if ($client) {
            foreach ($client as $k => $v) {
                if ($k === 'id') {
                    continue;
                }
                $facture[$k] = $v;
            }
        }
        require_once __DIR__ . '/../models/FactureLigne.php';
        $factureLigneModel = new FactureLigne();
        $facture_lignes = $factureLigneModel->getByFactureId($id);
        require_once __DIR__ . '/../models/ReglagesEntreprise.php';
        require_once __DIR__ . '/../models/ReglagesGestion.php';
        $db = Database::getInstance()->getConnection();
        $reglagesModel = new ReglagesEntreprise($db);
        $infos_entreprise = $reglagesModel->get();
        $reglagesGestionModel = new ReglagesGestion($db);
        $infos_gestion = $reglagesGestionModel->get();
        include __DIR__ . '/../views/factures_apercu.php';
    }

    private function list() {
        $db = Database::getInstance()->getConnection();
        $reglagesGestionModel = new ReglagesGestion($db);
        $infos_gestion = $reglagesGestionModel->get();
        $clients = $this->clientModel->getAll();
        $importMasks = $this->importMaskModel->getAllForEntity(self::IMPORT_ENTITY);

        // Filtrage par exercice fiscal si activé
        if (!empty($infos_gestion['filtre_exercice'])) {
            $mode = isset($_GET['exercice_mode']) ? trim((string)$_GET['exercice_mode']) : '';
            $year = isset($_GET['exercice_year']) ? (int)$_GET['exercice_year'] : 0;
            $quarter = isset($_GET['exercice_quarter']) ? (int)$_GET['exercice_quarter'] : 0;
            if ($mode === 'year' && $year > 0) {
                $facturesList = $this->model->getAllByExercice($year, null);
            } elseif ($mode === 'quarter' && $year > 0 && $quarter >= 1 && $quarter <= 4) {
                $facturesList = $this->model->getAllByExercice($year, $quarter);
            } else {
                $currentYear = (int)date('Y');
                $facturesList = $this->model->getAllByExercice($currentYear, null);
            }
        } else {
            $facturesList = $this->model->getAll();
        }
        include __DIR__ . '/../views/factures.php';
    }

    private function redirectWithMessage(string $status, string $message) {
        header('Location: index.php?page=factures&csv_status=' . urlencode($status) . '&csv_message=' . urlencode($message));
        exit;
    }

    private function resolveImportMaskFromRequest(): ?array {
        $maskId = isset($_POST['import_mask_id']) ? (int) $_POST['import_mask_id'] : 0;
        if ($maskId <= 0) {
            return null;
        }

        $mask = $this->importMaskModel->getById($maskId);
        if (!$mask || ($mask['entity_type'] ?? '') !== self::IMPORT_ENTITY) {
            throw new RuntimeException('Masque d\'import introuvable.');
        }

        return $mask;
    }

    private function resolveImportMappings(?array $mask): array {
        $maskMappings = is_array($mask['mappings'] ?? null) ? $mask['mappings'] : [];
        $requestMappings = ImportAssistant::extractMappingsFromRequest($this->getImportFields());

        return ImportAssistant::normalizeMappings(
            $this->getImportFields(),
            array_merge($maskMappings, $requestMappings)
        );
    }

    private function persistImportMaskIfRequested(array $mappings): string {
        $maskName = trim((string) ($_POST['save_mask_name'] ?? ''));
        if ($maskName === '') {
            return '';
        }

        if (count(array_filter($mappings, static function ($value) {
            return trim((string) $value) !== '';
        })) === 0) {
            throw new RuntimeException('Impossible d\'enregistrer un masque vide. Renseignez au moins une correspondance de champ.');
        }

        $this->importMaskModel->save(self::IMPORT_ENTITY, $maskName, $mappings);
        return $maskName;
    }

    private function resetIncrement() {
        $requestedValue = isset($_GET['value']) ? (int) $_GET['value'] : 0;
        if ($requestedValue <= 0) {
            header('Location: index.php?page=factures&increment_status=error&increment_message=' . urlencode('Valeur d\'incrément invalide.'));
            exit;
        }

        try {
            $success = $this->model->resetAutoIncrement($requestedValue);
            $status = $success ? 'success' : 'error';
            $message = $success
                ? 'Le prochain ID facture a été repositionné à ' . $requestedValue . '.'
                : 'Impossible de réinitialiser l\'auto-incrément des factures.';
        } catch (Throwable $e) {
            $status = 'error';
            $message = 'Réinitialisation impossible : ' . $e->getMessage();
        }

        header('Location: index.php?page=factures&increment_status=' . urlencode($status) . '&increment_message=' . urlencode($message));
        exit;
    }

    private function calculateTotal(array $lignes, $remiseGenerale, $typeRemiseGenerale) {
        $totalGeneral = 0;

        foreach ($lignes as $ligne) {
            $q = floatval($ligne['quantite'] ?? 1);
            $pu = floatval($ligne['prix_unitaire'] ?? 0);
            $rem = floatval($ligne['remise'] ?? 0);
            $typeRem = $ligne['type_remise'] ?? 'euro';
            $totalLigne = $q * $pu;

            if ($typeRem === 'euro') {
                $totalLigne -= $rem;
            } else {
                $totalLigne -= ($totalLigne * $rem / 100);
            }

            if ($totalLigne < 0) {
                $totalLigne = 0;
            }

            $totalGeneral += $totalLigne;
        }

        $remiseGenerale = floatval($remiseGenerale ?? 0);
        $typeRemiseGenerale = $typeRemiseGenerale ?? 'euro';

        if ($typeRemiseGenerale === 'euro') {
            $totalGeneral -= $remiseGenerale;
        } else {
            $totalGeneral -= ($totalGeneral * $remiseGenerale / 100);
        }

        return $totalGeneral < 0 ? 0 : $totalGeneral;
    }


    private function add() {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Initialize variables for POST requests to prevent undefined variable notices
            $facture = [];
            $facture_lignes = [];
            $linkedProject = [];
            if (isset($_POST['ajouter_ligne'])) {
                $lignes = $_POST['lignes'] ?? [];
                $lignes[] = [
                    'intitule' => '',
                    'quantite' => 1,
                    'prix_unitaire' => 0,
                    'remise' => 0,
                    'type_remise' => 'euro',
                ];
                $_POST['lignes'] = $lignes;
            } elseif (isset($_POST['supprimer_ligne'])) {
                $lignes = $_POST['lignes'] ?? [];
                $idx = intval($_POST['supprimer_ligne']);
                if (isset($lignes[$idx])) {
                    array_splice($lignes, $idx, 1);
                }
                $_POST['lignes'] = $lignes;
            } else if (isset($_POST['lignes']) && !isset($_POST['enregistrer_facture'])) {
                $clients = $this->clientModel->getAll();
                $facturesList = $this->model->getAll();
                $projects = $this->projectModel->getAll();
                include __DIR__ . '/../views/factures.php';
                return;
            } else {
                if (!isset($_POST['montant_regle']) || $_POST['montant_regle'] === '') {
                    $_POST['montant_regle'] = 0;
                }
                $lignes = isset($_POST['lignes']) && is_array($_POST['lignes']) ? $_POST['lignes'] : [];
                $_POST['montant'] = $this->calculateTotal(
                    $lignes,
                    $_POST['remise_generale'] ?? 0,
                    $_POST['type_remise_generale'] ?? 'euro'
                );
                $this->model->create($_POST);
                $pdo = Database::getInstance()->getConnection();
                $facture_id = $pdo->lastInsertId();
                if ($lignes) {
                    $ligneModel = new FactureLigne();
                    foreach ($lignes as $ligne) {
                        $q = floatval($ligne['quantite'] ?? 1);
                        $pu = floatval($ligne['prix_unitaire'] ?? 0);
                        $rem = floatval($ligne['remise'] ?? 0);
                        $type_rem = $ligne['type_remise'] ?? 'euro';
                        $total_ligne = $q * $pu;
                        if ($type_rem === 'euro') $total_ligne -= $rem;
                        else $total_ligne -= ($total_ligne * $rem / 100);
                        if ($total_ligne < 0) $total_ligne = 0;
                        $ligneModel->add($facture_id, $ligne['intitule'], $q, $pu, $rem, $type_rem, $total_ligne);
                    }
                }
                $linkedProjectId = isset($_POST['linked_project_id']) ? (int) $_POST['linked_project_id'] : 0;
                $this->projectLinkModel->assign($linkedProjectId > 0 ? $linkedProjectId : null, 'facture', (int) $facture_id);
                header('Location: index.php?page=factures');
                exit;
            }
            $clients = $this->clientModel->getAll();
            $facturesList = $this->model->getAll();
            $projects = $this->projectModel->getAll();
            include __DIR__ . '/../views/factures.php';
            return;
        }
        // Pré-remplir le numéro de facture pour la création avec F-[année]-00[prochain id]
        $facture = [];
        try {
            $nextId = $this->model->getNextId();
            if ($nextId) {
                $year = date('Y');
                $db = Database::getInstance()->getConnection();
                $reglagesGestionModel = new ReglagesGestion($db);
                $infos_gestion = $reglagesGestionModel->get();
                $prefix = isset($infos_gestion['prefixe_facture']) && $infos_gestion['prefixe_facture'] !== '' ? $infos_gestion['prefixe_facture'] : 'F-{year}-00';
                $resolved = str_replace('{year}', $year, $prefix);
                $facture['numero'] = $resolved . $nextId;
            }
        } catch (Throwable $e) {
            // En cas d'erreur on laisse le champ vide
        }
        $clients = $this->clientModel->getAll();
        $facturesList = $this->model->getAll();
        $projects = $this->projectModel->getAll();
        include __DIR__ . '/../views/factures.php';
    }

    private function edit() {
        $id = $_GET['id'] ?? null;
        if (!$id) return;
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (isset($_POST['ajouter_ligne'])) {
                $lignes = $_POST['lignes'] ?? [];
                $lignes[] = [
                    'intitule' => '',
                    'quantite' => 1,
                    'prix_unitaire' => 0,
                    'remise' => 0,
                    'type_remise' => 'euro',
                ];
                $_POST['lignes'] = $lignes;
            } elseif (isset($_POST['supprimer_ligne'])) {
                $lignes = $_POST['lignes'] ?? [];
                $idx = intval($_POST['supprimer_ligne']);
                if (isset($lignes[$idx])) {
                    array_splice($lignes, $idx, 1);
                }
                $_POST['lignes'] = $lignes;
            } else {
                if (!isset($_POST['montant_regle']) || $_POST['montant_regle'] === '') {
                    $_POST['montant_regle'] = 0;
                }
                $ligneModel = new FactureLigne();
                $ligneModel->deleteByFactureId($id);
                $lignes = isset($_POST['lignes']) && is_array($_POST['lignes']) ? $_POST['lignes'] : [];
                if ($lignes) {
                    foreach ($lignes as $ligne) {
                        $q = floatval($ligne['quantite'] ?? 1);
                        $pu = floatval($ligne['prix_unitaire'] ?? 0);
                        $rem = floatval($ligne['remise'] ?? 0);
                        $type_rem = $ligne['type_remise'] ?? 'euro';
                        $total_ligne = $q * $pu;
                        if ($type_rem === 'euro') $total_ligne -= $rem;
                        else $total_ligne -= ($total_ligne * $rem / 100);
                        if ($total_ligne < 0) $total_ligne = 0;
                        $ligneModel->add($id, $ligne['intitule'], $q, $pu, $rem, $type_rem, $total_ligne);
                    }
                }
                $_POST['montant'] = $this->calculateTotal(
                    $lignes,
                    $_POST['remise_generale'] ?? 0,
                    $_POST['type_remise_generale'] ?? 'euro'
                );
                $this->model->update($id, $_POST);
                $linkedProjectId = isset($_POST['linked_project_id']) ? (int) $_POST['linked_project_id'] : 0;
                $this->projectLinkModel->assign($linkedProjectId > 0 ? $linkedProjectId : null, 'facture', (int) $id);
                header('Location: index.php?page=factures');
                exit;
            }
            $facture = $this->model->getById($id);
            $clients = $this->clientModel->getAll();
            $facturesList = $this->model->getAll();
            $projects = $this->projectModel->getAll();
            $linkedProject = $this->projectLinkModel->getForEntity('facture', (int) $id);
            include __DIR__ . '/../views/factures.php';
            return;
        }
        $facture = $this->model->getById($id);
        $clients = $this->clientModel->getAll();
        $facturesList = $this->model->getAll();
        $projects = $this->projectModel->getAll();
        $linkedProject = $this->projectLinkModel->getForEntity('facture', (int) $id);
        $factureLigneModel = new FactureLigne();
        $facture_lignes = $factureLigneModel->getByFactureId($id);
        include __DIR__ . '/../views/factures.php';
    }

    private function delete() {
        $id = $_GET['id'] ?? null;
        if ($id) {
            $this->projectLinkModel->deleteByEntity('facture', (int) $id);
            $this->model->delete($id);
        }
        header('Location: index.php?page=factures');
        exit;
    }
}