]> _ Git - fluidbook-toolbox.git/commitdiff
wip #7898
authorsoufiane <soufiane@cubedesigners.com>
Mon, 19 Jan 2026 09:50:24 +0000 (10:50 +0100)
committersoufiane <soufiane@cubedesigners.com>
Mon, 19 Jan 2026 09:50:24 +0000 (10:50 +0100)
app/Http/Controllers/Admin/Operations/FluidbookPublication/Services/KimplayOperation.php

index 61b23f9a9399af8613b36a1bb2865116b6677c50..d152aa103fa9da0cb20c3bcbe371fef81fedb208 100644 (file)
@@ -5,10 +5,23 @@ namespace App\Http\Controllers\Admin\Operations\FluidbookPublication\Services;
 use App\Http\Middleware\Authenticate;
 use App\Http\Middleware\CheckIfAdmin;
 use App\Http\Middleware\VerifyCsrfToken;
+use App\Mail\Base;
+use Cubist\Util\Files\Files;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Mail;
 use Illuminate\Support\Facades\Route;
 use Cubist\Backpack\Middleware\CORSMiddleware;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Validator;
+use PhpOffice\PhpSpreadsheet\Cell\DataType;
+use PhpOffice\PhpSpreadsheet\Exception;
+use PhpOffice\PhpSpreadsheet\Spreadsheet;
+use PhpOffice\PhpSpreadsheet\Style\Alignment;
+use PhpOffice\PhpSpreadsheet\Style\Border;
+use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
+use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
+use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
+use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
 
 trait KimplayOperation
 {
@@ -28,21 +41,189 @@ trait KimplayOperation
             'phone' => 'required',
         ], [
             'required' => 'Ce champ est obligatoire',
-            'email' => 'Veuillez indiquer une adresse email correcte'
+            'email' => 'Adresse email est incorrecte'
         ]);
 
         $validated = $validator->validated();
 
         $formData = [
-            'nom de l\'entreprise' => request('company'),
-            'nom' => request('name'),
-            'prénom' => request('firstname'),
-            'email' => request('mail'),
-            'téléphone' => request('phone'),
-            'adresse' => request('address'),
-            'message' => request('message'),
+            'Nom de l\'entreprise' => request('company'),
+            'Nom' => request('name'),
+            'Prénom' => request('firstname'),
+            'Email' => request('mail'),
+            'Téléphone' => request('phone'),
+            'Adresse' => request('address'),
+            'Message' => request('message'),
         ];
 
-        $productsData = request('products');
+        if (empty(request('cart_items'))) {
+            die('Error: invalid data received');
+        }
+
+        $cart_items = json_decode(request('cart_items'), true);
+        $file = $this->getCsv($cart_items, $formData);
+        $this->sendMail($file, request('mail'));
+    }
+
+    public function getCsv($cart_items, $user_details) {
+        $column_headings = [
+            'ref' => 'Réference',
+            'name' => 'Désignation',
+            'quantity' => 'Quantité',
+            'comment' => 'Commentaire'
+        ];
+
+        $excel = new Spreadsheet();
+        $excel->setActiveSheetIndex(0);
+        $defaultStyle = $excel->getDefaultStyle();
+        $defaultStyle->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
+        $defaultStyle->getAlignment()->setWrapText(true);
+        $defaultStyle->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
+        $sheet = $excel->getActiveSheet();
+        $sheet->setTitle('Récapitulatif de demande');
+        $sheet->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
+        $sheet->getPageSetup()->setFitToPage(true);
+
+        // Setup column headings
+        $current_column_index = 1;
+        $current_row = 1;
+        $sheet->getRowDimension(1)->setRowHeight(22); // Larger row height for headings
+        foreach ($column_headings as $column_heading) {
+            $sheet->setCellValueByColumnAndRow($current_column_index, $current_row, $column_heading);
+            $cell_style = $sheet->getStyleByColumnAndRow($current_column_index, $current_row);
+            $cell_style->getFont()->setBold(true);
+            $cell_style->getBorders()->getBottom()->setBorderStyle(Border::BORDER_MEDIUM);
+            $current_column_index++;
+        }
+
+        // Output cart data
+        foreach ($cart_items as $key => $cart_item) {
+            $current_row++;
+
+            // Set a slightly larger row height to give better vertical spacing
+            $sheet->getRowDimension($current_row)->setRowHeight(22);
+
+            // Look up the value by the column keys to ensure the correct order of values
+            foreach (array_keys($column_headings) as $column_index => $column_key) {
+
+                $current_cell_style = $sheet->getStyleByColumnAndRow($column_index + 1, $current_row);
+
+                switch ($column_key) {
+                    case 'ref':
+                        $sheet->setCellValueByColumnAndRow($column_index + 1, $current_row, $key);
+                        break;
+                    case 'quantity':
+                        $sheet->setCellValueByColumnAndRow($column_index + 1, $current_row, $cart_item[$column_key]);
+                        $current_cell_style->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_NUMBER);
+                        break;
+                    default:
+                        $sheet->setCellValueByColumnAndRow($column_index + 1, $current_row, $cart_item[$column_key]);
+                }
+
+            }
+        }
+
+        // Autosize columns once the data has been added
+        for ($i = 1; $i <= count($column_headings); $i++) {
+            $sheet->getColumnDimensionByColumn($i)->setAutoSize(true);
+        }
+
+        $details_sheet = $excel->addSheet(new Worksheet($excel, 'Coordonnées'), 0); // Setting index to zero will put this sheet first in the workbook
+
+        $current_row = 1;
+        foreach ($user_details as $key => $value) {
+            // User details are displayed as Label: Value in the A & B columns
+            $details_label_style = $details_sheet->getStyleByColumnAndRow(1, $current_row);
+            $details_label_style->getFont()->setBold(true);
+            $details_label_style->getAlignment()->setWrapText(false);
+            $details_label_style->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
+            $details_label_style->getAlignment()->setVertical(Alignment::VERTICAL_TOP);
+
+            // Top align the values because we'll be using a slightly larger row height
+            $details_value_style = $details_sheet->getStyleByColumnAndRow(2, $current_row);
+            $details_value_style->getAlignment()->setVertical(Alignment::VERTICAL_TOP);
+
+            // Set values
+            $details_sheet->setCellValueByColumnAndRow(1, $current_row, $key . ' :');
+            $details_sheet->setCellValueByColumnAndRow(2, $current_row, $value);
+
+            // $details_sheet->getStyleByColumnAndRow(1, $current_row)->getAlignment()->setWrapText(true);
+            // $details_sheet->getRowDimension($current_row)->setRowHeight(-1); // Auto row height from content
+
+            // Unfortunately, LibreOffice has a long-standing bug where auto row height doesn't work :(
+            // Ref: https://github.com/PHPOffice/PHPExcel/issues/588#issuecomment-249544915
+            // Since we may have multi-line text for the address and message, we need to figure out how high
+            // the row should be, based on the number of lines. The default row height is 12.75pt
+            // Ref: https://github.com/PHPOffice/PHPExcel/blob/1.8/Documentation/markdown/Overview/08-Recipes.md#setting-a-rows-height
+            $single_row_height = 12.75; // Basis for a single line of text
+            $line_count = count(explode("\n", $value));
+            // Add a slight extra buffer to row height (+3) so it isn't tight against the next one
+            $details_sheet->getRowDimension($current_row)->setRowHeight($line_count * $single_row_height + 3);
+
+            $current_row++;
+        }
+
+        // Auto-size both columns
+        $details_sheet->getColumnDimensionByColumn(1)->setAutoSize(true);
+        $details_sheet->getColumnDimensionByColumn(2)->setAutoSize(true);
+
+        $xls_writer = new Xlsx($excel);
+        $xls_file = Files::tempnam();
+        $xls_writer->save($xls_file);
+
+        return $xls_file;
+    }
+
+    public function sendMail($xls_file, $user_email) {
+        $email_for_kimplay = 'postmaster@fluidbook.com';
+        $return_address = 'postmaster@fluidbook.com';
+        $email_from_name = "Kim'Play";
+        $email_reply_to = "info@cofalu.com";
+        $email_kimplay_subject = 'Demande catalogue Kim\'Play';
+        $email_user_subject = 'Récapitulatif de votre demande Kim\'Play';
+        $email_to_user_body = "Bonjour,<br><br>Votre demande est en cours de traitement (récapitulatif en pièce jointe). Nous vous recontacterons dans les meilleurs délais. D’ici là nous restons joignables pour toute question à l’adresse : info@cofalu.com<br><br>Cordialement,<br><br>L'équipe commerciale";
+        $email_to_kimplay_body = "Bonjour,<br><br>Une commande a été passée (récapitulatif en pièce jointe).<br><br>Cordialement<br><br>";
+
+        // Filename for attachment (without extension)
+        $orderId = date('YmdHis');
+        $attachment_basename = "Kim'Play" . $orderId;
+
+        //=== Send the email
+        // There are two almost identical e-mails sent:
+        // - E-mail to Bastide, containing the request details in XLS format
+        // - E-mail to the user, containing the same information but converted to PDF format
+        $mail_to_kimplay = new Base();
+        $mail_to_kimplay->from($return_address, $email_from_name);
+        $mail_to_kimplay->replyTo($email_reply_to, $email_from_name);
+        $mail_to_kimplay->subject($email_kimplay_subject);
+        $mail_to_kimplay->html($email_to_kimplay_body);
+
+        // Duplicate the common e-mail settings and apply them to the user e-mail
+        $mail_to_user = clone $mail_to_kimplay;
+        $mail_to_user->to($user_email);
+        $mail_to_user->subject($email_user_subject);
+        $mail_to_user->html($email_to_user_body);
+
+        // Back to setting up the mail for Bastide
+        $mail_to_kimplay->to($email_for_kimplay);
+        $mail_to_kimplay->attach($xls_file, ['as' => $attachment_basename . '.xlsx', 'mime' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']);
+
+        // When the recipient isn't the default Bastide address, we add them in as a BCC so they can track the messages
+        // See: https://redmine.cubedesigners.com/issues/5345#note-36
+        /*if ($email_for_bastide !== $default_bastide_address) {
+            $mail_to_bastide->bcc($default_bastide_address);
+        }*/
+
+        //=== Send the e-mails
+        try {
+            Mail::send($mail_to_kimplay);
+            Mail::send($mail_to_user);
+            return true;
+        } catch (Exception $e) {
+            Log::warn('#### Bastide: Failed sending message via Mailjet ####');
+            Log::warn('ERROR: ' . $e->getMessage());
+            return false;
+        }
+
     }
 }