Browse code

Remove the random temporary prefix from the filename of the email attachment

Benjamin Roth authored on18/03/2025 14:31:25
Showing1 changed files
... ...
@@ -166,7 +166,8 @@ class ShopwareExportNewsletterJob extends AbstractController
166 166
             ];
167 167
         }
168 168
 
169
-        $filename = $srcDir . '/' . (!empty($email) && Validator::isEmail($email) ? substr(md5(uniqid()), 0, 10) . '_' : '') . 'recipients_' . date("Ymd", $intStart) . '_' . date("Ymd", $intEnd) . '.csv';
169
+        $strRandomPrefix = (!empty($email) && Validator::isEmail($email) ? substr(md5(uniqid()), 0, 10) . '_' : '');
170
+        $filename = $srcDir . '/' . $strRandomPrefix . 'recipients_' . date("Ymd", $intStart) . '_' . date("Ymd", $intEnd) . '.csv';
170 171
         \file_put_contents($filename, $this->serializer->encode($arrCSV, 'csv', $this->csvContext));
171 172
 
172 173
         // If email is provided, send the CSV file
... ...
@@ -180,7 +181,7 @@ class ShopwareExportNewsletterJob extends AbstractController
180 181
                 ->to($email)
181 182
                 ->subject('Newsletter Export')
182 183
                 ->text('Attached is the exported list of newsletter recipients.')
183
-                ->attachFromPath($filename, basename($filename), 'text/csv');
184
+                ->attachFromPath($filename, str_replace($strRandomPrefix,'',basename($filename)), 'text/csv');
184 185
 
185 186
             try
186 187
             {
Browse code

Add random temporary prefix to filename if email was provided to not delete an official export

Benjamin Roth authored on18/03/2025 14:26:59
Showing1 changed files
... ...
@@ -166,7 +166,7 @@ class ShopwareExportNewsletterJob extends AbstractController
166 166
             ];
167 167
         }
168 168
 
169
-        $filename = $srcDir . '/recipients_' . date("Ymd", $intStart) . '_' . date("Ymd", $intEnd) . '.csv';
169
+        $filename = $srcDir . '/' . (!empty($email) && Validator::isEmail($email) ? substr(md5(uniqid()), 0, 10) . '_' : '') . 'recipients_' . date("Ymd", $intStart) . '_' . date("Ymd", $intEnd) . '.csv';
170 170
         \file_put_contents($filename, $this->serializer->encode($arrCSV, 'csv', $this->csvContext));
171 171
 
172 172
         // If email is provided, send the CSV file
Browse code

Delete export file if email option was used

Benjamin Roth authored on18/03/2025 14:22:33
Showing1 changed files
... ...
@@ -185,6 +185,12 @@ class ShopwareExportNewsletterJob extends AbstractController
185 185
             try
186 186
             {
187 187
                 $mailer->send($emailMessage);
188
+
189
+                // Delete the file after sending the email
190
+                if (file_exists($filename))
191
+                {
192
+                    unlink($filename);
193
+                }
188 194
                 if ($isCli)
189 195
                 {
190 196
                     $io->success('CSV file has been successfully sent to ' . $email);
Browse code

Initial commit

Benjamin Roth authored on18/03/2025 13:06:28
Showing1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,202 @@
1
+<?php
2
+
3
+declare(strict_types=1);
4
+
5
+/*
6
+ * This file is part of vonRotenberg WMFGO Cevisio Bundle.
7
+ *
8
+ * (c) vonRotenberg
9
+ *
10
+ * @license proprietary
11
+ */
12
+
13
+namespace vonRotenberg\AldegottSwNlBundle\Cron;
14
+
15
+use Contao\Config;
16
+use Contao\CoreBundle\Controller\AbstractController;
17
+use Contao\Date;
18
+use Contao\StringUtil;
19
+use Contao\System;
20
+use Contao\Validator;
21
+use Doctrine\DBAL\Connection;
22
+use Psr\Log\LoggerInterface;
23
+use Symfony\Component\Console\Helper\ProgressBar;
24
+use Symfony\Component\Console\Output\ConsoleOutput;
25
+use Symfony\Component\Console\Style\SymfonyStyle;
26
+use Symfony\Component\Finder\Finder;
27
+use Symfony\Component\Serializer\Encoder\CsvEncoder;
28
+use Symfony\Component\Serializer\Encoder\XmlEncoder;
29
+use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
30
+use Symfony\Component\Serializer\Serializer;
31
+use Symfony\Component\Serializer\SerializerInterface;
32
+use vonRotenberg\ShopwareApiBundle\API\Shopware;
33
+use vonRotenberg\ShopwareApiBundle\Helper\ShopwareMappings;
34
+use vonRotenberg\AldegottSwNlBundle\Model\Import\ProductModel;
35
+
36
+class ShopwareExportNewsletterJob extends AbstractController
37
+{
38
+    /** @var LoggerInterface */
39
+    private $logger;
40
+
41
+    /** @var SerializerInterface */
42
+    private $serializer;
43
+
44
+    /** @var Shopware */
45
+    private $shopware;
46
+
47
+    /** @var ShopwareMappings */
48
+    private $mappings;
49
+
50
+    private $csvContext = [];
51
+
52
+    /** @var Finder */
53
+    private $finder;
54
+
55
+    /** @var Connection */
56
+    private $db;
57
+
58
+    /**
59
+     * Remote
60
+     * @var Connection
61
+     */
62
+    private $rdb;
63
+
64
+    public function __construct(Finder $finder, Shopware $shopware, ShopwareMappings $mappings, Connection $db, LoggerInterface $logger)
65
+    {
66
+        $this->finder = $finder;
67
+        $this->db = $db;
68
+        $this->logger = $logger;
69
+        $this->shopware = $shopware;
70
+        $this->mappings = $mappings;
71
+
72
+        $encoder      = [new CsvEncoder()];
73
+        $normalizer   = [new ObjectNormalizer()];
74
+        $this->serializer = new Serializer($normalizer,$encoder);
75
+
76
+        $this->csvContext = [
77
+            'csv_delimiter' => ';',
78
+            'csv_enclosure' => '"',
79
+            'no_headers' => true
80
+        ];
81
+    }
82
+
83
+    public function export(string $scope, ?string $start=null, ?string $stop=null, ?string $email, ?SymfonyStyle &$io = null): void
84
+    {
85
+        $intCounter = 0;
86
+        $isCli = false;
87
+        if (strtolower($scope) == 'cli' && $io !== null) {
88
+            $isCli = true;
89
+        }
90
+        $translator = System::getContainer()->get('translator');
91
+        $translator->setLocale('de');
92
+//        date_default_timezone_set('Europe/Berlin');
93
+        $projectDir = System::getContainer()->getParameter('kernel.project_dir');
94
+        $srcDir = $projectDir.'/export/newsletter_recipients';
95
+        if (!file_exists($srcDir)) {
96
+            mkdir($srcDir, 0777,true);
97
+        }
98
+
99
+        $Today = new Date();
100
+
101
+        if (($start || $stop) && ($start === null || $stop === null))
102
+        {
103
+            return;
104
+        }
105
+
106
+        // Set working period
107
+        if ($start && $stop) {
108
+            $StartDate = new Date($start,'Y-m-d');
109
+            $StopDate = new Date($stop,'Y-m-d');
110
+            $intStart = $StartDate->dayBegin;
111
+            $intEnd = $StopDate->dayEnd;
112
+        } else {
113
+            $WorkingDate = new Date($Today->dayBegin);
114
+            $intStart = strtotime(date('Y-m-d',$WorkingDate->dayBegin) . ' -1 day');
115
+            $intEnd = $WorkingDate->dayBegin;
116
+        }
117
+
118
+        if ($isCli) {
119
+            $io->definitionList('Using export timeframe:',['Start'=>Date::parse(Date::getNumericDateFormat(),$intStart)],['End'=>Date::parse(Date::getNumericDateFormat(),$intEnd)]);
120
+        }
121
+
122
+        $arrBody = [
123
+            'filter' => [
124
+                [
125
+                    'type'=> 'range',
126
+                    'field'=> 'createdAt',
127
+                    'parameters'=> [
128
+                        'gte'=> date(\DateTime::ATOM,$intStart),
129
+                        'lte'=> date(\DateTime::ATOM,$intEnd),
130
+                    ],
131
+                ],
132
+                [
133
+                    'type'=> 'equals',
134
+                    'field'=> 'status',
135
+                    'value'=> 'optIn'
136
+                ]
137
+            ],
138
+        ];
139
+
140
+        $Response = $this->shopware->queryAPI('search/newsletter-recipient',$arrBody,'POST',true);
141
+
142
+        if ($Response->getStatusCode() !== 200 || !json_validate($Response->getContent())) {
143
+            if ($isCli) $io->error('Could not export newsletter recipients');
144
+            dump($Response->getContent(false));
145
+        }
146
+
147
+        $Content = json_decode($Response->getContent(), true);
148
+
149
+        $arrCSV = [
150
+            [
151
+                'email',
152
+                'firstName',
153
+                'lastName',
154
+                'status',
155
+                'confirmedAt'
156
+            ]
157
+        ];
158
+        foreach ($Content['data'] as $recipient)
159
+        {
160
+            $arrCSV[] = [
161
+                $recipient['email'],
162
+                $recipient['firstName'],
163
+                $recipient['lastName'],
164
+                $recipient['status'],
165
+                $recipient['confirmedAt']
166
+            ];
167
+        }
168
+
169
+        $filename = $srcDir . '/recipients_' . date("Ymd", $intStart) . '_' . date("Ymd", $intEnd) . '.csv';
170
+        \file_put_contents($filename, $this->serializer->encode($arrCSV, 'csv', $this->csvContext));
171
+
172
+        // If email is provided, send the CSV file
173
+        if (!empty($email) && Validator::isEmail($email))
174
+        {
175
+
176
+            list($fromName,$fromMail) = StringUtil::splitFriendlyEmail(Config::get('adminEmail'));
177
+            $mailer = System::getContainer()->get('mailer');
178
+            $emailMessage = (new \Symfony\Component\Mime\Email())
179
+                ->from($fromMail) // Change this to your desired "from" address
180
+                ->to($email)
181
+                ->subject('Newsletter Export')
182
+                ->text('Attached is the exported list of newsletter recipients.')
183
+                ->attachFromPath($filename, basename($filename), 'text/csv');
184
+
185
+            try
186
+            {
187
+                $mailer->send($emailMessage);
188
+                if ($isCli)
189
+                {
190
+                    $io->success('CSV file has been successfully sent to ' . $email);
191
+                }
192
+            } catch (\Exception $e)
193
+            {
194
+                if ($isCli)
195
+                {
196
+                    $io->error('Failed to send email: ' . $e->getMessage());
197
+                }
198
+                $this->logger->error('Failed to send the email with the CSV file.', ['exception' => $e]);
199
+            }
200
+        }
201
+    }
202
+}