Passed
Push — master ( 23e72e...dc62e4 )
by Aimeos
03:22
created

Standard::status()

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 10
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2015-2022
6
 * @package Controller
7
 * @subpackage Order
8
 */
9
10
11
namespace Aimeos\Controller\Jobs\Order\Email\Payment;
12
13
14
/**
15
 * Order payment e-mail job controller.
16
 *
17
 * @package Controller
18
 * @subpackage Order
19
 */
20
class Standard
21
	extends \Aimeos\Controller\Jobs\Base
22
	implements \Aimeos\Controller\Jobs\Iface
23
{
24
	use \Aimeos\Controller\Jobs\Mail;
25
26
27
	/**
28
	 * Returns the localized name of the job.
29
	 *
30
	 * @return string Name of the job
31
	 */
32
	public function getName() : string
33
	{
34
		return $this->context()->translate( 'controller/jobs', 'Order payment related e-mails' );
35
	}
36
37
38
	/**
39
	 * Returns the localized description of the job.
40
	 *
41
	 * @return string Description of the job
42
	 */
43
	public function getDescription() : string
44
	{
45
		return $this->context()->translate( 'controller/jobs', 'Sends order confirmation or payment status update e-mails' );
46
	}
47
48
49
	/**
50
	 * Executes the job.
51
	 *
52
	 * @throws \Aimeos\Controller\Jobs\Exception If an error occurs
53
	 */
54
	public function run()
55
	{
56
		$context = $this->context();
57
		$config = $context->config();
58
59
		$orderManager = \Aimeos\MShop::create( $context, 'order' );
60
61
		/** controller/jobs/order/email/payment/limit-days
62
		 * Only send payment e-mails of orders that were created in the past within the configured number of days
63
		 *
64
		 * The payment e-mails are normally send immediately after the payment
65
		 * status has changed. This option prevents e-mails for old order from
66
		 * being send in case anything went wrong or an update failed to avoid
67
		 * confusion of customers.
68
		 *
69
		 * @param integer Number of days
70
		 * @since 2014.03
71
		 * @category User
72
		 * @category Developer
73
		 * @see controller/jobs/order/email/delivery/limit-days
74
		 * @see controller/jobs/service/delivery/process/limit-days
75
		 */
76
		$limit = $config->get( 'controller/jobs/order/email/payment/limit-days', 30 );
77
		$limitDate = date( 'Y-m-d H:i:s', time() - $limit * 86400 );
78
79
		$default = [
80
			\Aimeos\MShop\Order\Item\Base::PAY_REFUND,
81
			\Aimeos\MShop\Order\Item\Base::PAY_PENDING,
82
			\Aimeos\MShop\Order\Item\Base::PAY_AUTHORIZED,
83
			\Aimeos\MShop\Order\Item\Base::PAY_RECEIVED,
84
		];
85
86
		/** controller/jobs/order/email/payment/status
87
		 * Only send order payment notification e-mails for these payment status values
88
		 *
89
		 * Notification e-mail about payment status changes can be sent for these
90
		 * status values:
91
		 *
92
		 * * 0: deleted
93
		 * * 1: canceled
94
		 * * 2: refused
95
		 * * 3: refund
96
		 * * 4: pending
97
		 * * 5: authorized
98
		 * * 6: received
99
		 * * 7: transferred
100
		 *
101
		 * User-defined status values are possible but should be in the private
102
		 * block of values between 30000 and 32767.
103
		 *
104
		 * @param integer Payment status constant
105
		 * @since 2014.03
106
		 * @category User
107
		 * @category Developer
108
		 * @see controller/jobs/order/email/delivery/status
109
		 * @see controller/jobs/order/email/payment/limit-days
110
		 */
111
		foreach( (array) $config->get( 'controller/jobs/order/email/payment/status', $default ) as $status )
112
		{
113
			$param = [\Aimeos\MShop\Order\Item\Status\Base::EMAIL_PAYMENT, (string) $status];
114
			$filter = $orderManager->filter();
115
			$filter->add( [
116
				$filter->compare( '>=', 'order.mtime', $limitDate ),
117
				$filter->compare( '==', 'order.statuspayment', $status ),
118
				$filter->compare( '==', $filter->make( 'order:status', $param ), 0 ),
119
			] );
120
121
			$start = 0;
122
			$domains = ['order/base', 'order/base/address', 'order/base/product', 'order/base/service'];
123
124
			do
125
			{
126
				$items = $orderManager->search( $filter->slice( $start ), $domains );
127
128
				$this->notify( $items, $status );
129
130
				$count = count( $items );
131
				$start += $count;
132
			}
133
			while( $count >= $filter->getLimit() );
134
		}
135
	}
136
137
138
	/**
139
	 * Returns the address item from the order
140
	 *
141
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Order including address items
142
	 * @return \Aimeos\MShop\Common\Item\Address\Iface Address item
143
	 * @throws \Aimeos\Controller\Jobs\Exception If no suitable address item is available
144
	 */
145
	protected function address( \Aimeos\MShop\Order\Item\Base\Iface $basket ) : \Aimeos\MShop\Common\Item\Address\Iface
146
	{
147
		if( ( $addr = current( $basket->getAddress( 'payment' ) ) ) !== false && $addr->getEmail() ) {
148
			return $addr;
149
		};
150
151
		$msg = sprintf( 'No address with e-mail found in order base with ID "%1$s"', $basket->getId() );
152
		throw new \Aimeos\Controller\Jobs\Exception( $msg );
153
	}
154
155
156
	/**
157
	 * Adds the given list of files as attachments to the mail message object
158
	 *
159
	 * @param \Aimeos\Base\Mail\Message\Iface $msg Mail message
160
	 * @param array $files List of absolute file paths
161
	 */
162
	protected function attachments( \Aimeos\Base\Mail\Message\Iface $msg ) : \Aimeos\Base\Mail\Message\Iface
163
	{
164
		$context = $this->context();
165
		$fs = $context->fs();
166
167
		/** client/html/email/payment/attachments
168
		 * List of file paths whose content should be attached to all payment e-mails
169
		 *
170
		 * This configuration option allows you to add files to the e-mails that are
171
		 * sent to the customer when the payment status changes, e.g. for the order
172
		 * confirmation e-mail. These files can't be customer specific.
173
		 *
174
		 * @param array List of absolute file paths
175
		 * @since 2016.10
176
		 * @see client/html/email/delivery/attachments
177
		 */
178
		$files = $context->config()->get( 'client/html/email/payment/attachments', [] );
179
180
		foreach( $files as $filepath )
181
		{
182
			if( $fs->has( $filepath ) ) {
183
				$msg->attach( $fs->read( $filepath ), basename( $filename ) );
184
			}
185
		}
186
187
		return $msg;
188
	}
189
190
191
	/**
192
	 * Sends the payment e-mail for the given orders
193
	 *
194
	 * @param \Aimeos\Map $items List of order items implementing \Aimeos\MShop\Order\Item\Iface with their IDs as keys
195
	 * @param int $status Delivery status value
196
	 */
197
	protected function notify( \Aimeos\Map $items, int $status )
198
	{
199
		$context = $this->context();
200
		$sites = $this->sites( $items->getBaseItem()->getSiteId()->unique() );
201
202
		foreach( $items as $id => $item )
203
		{
204
			try
205
			{
206
				$basket = $item->getBaseItem();
207
				$list = $sites->get( $basket->getSiteId(), map() );
208
209
				$view = $this->view( $basket, $list->getTheme()->filter()->last() );
210
				$view->summaryBasket = $basket;
211
				$view->orderItem = $item;
212
213
				$this->send( $view, $list->getLogo()->filter()->last() );
214
				$this->status( $id, $status );
215
216
				$email = $this->address( $basket )->getEmail();
217
				$str = sprintf( 'Sent order payment e-mail for status "%1$s" to "%2$s"', $status, $email );
218
				$context->logger()->info( $str, 'email/order/payment' );
219
			}
220
			catch( \Exception $e )
221
			{
222
				$str = 'Error while trying to send payment e-mail for order ID "%1$s" and status "%2$s": %3$s';
223
				$msg = sprintf( $str, $item->getId(), $item->getStatusPayment(), $e->getMessage() );
224
				$context->logger()->error( $msg . PHP_EOL . $e->getTraceAsString(), 'email/order/payment' );
225
			}
226
		}
227
	}
228
229
230
	/**
231
	 * Returns the generated PDF file for the order
232
	 *
233
	 * @param \Aimeos\MW\View\Iface $view View object with address and order item assigned
234
	 * @return string|null PDF content or NULL for no PDF file
235
	 */
236
	protected function pdf( \Aimeos\MW\View\Iface $view ) : ?string
237
	{
238
		$config = $this->context()->config();
239
240
		/** controller/jobs/order/email/payment/pdf
241
		 * Enables attaching the order confirmation PDF to the payment e-mail
242
		 *
243
		 * The order confirmation PDF contains the same information like the
244
		 * HTML e-mail and can be also used as invoice if possible.
245
		 *
246
		 * @param bool TRUE to enable attaching the PDF, FALSE to skip the PDF
247
		 * @since 2022.04
248
		 */
249
		if( !$config->get( 'controller/jobs/order/email/payment/pdf', true ) ) {
250
			return null;
251
		}
252
253
		$pdf = new class( PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false ) extends \TCPDF {
254
			private $headerFcn;
255
			private $footerFcn;
256
257
			public function Footer() { return ( $fcn = $this->footerFcn ) ? $fcn( $this ) : null; }
258
			public function Header() { return ( $fcn = $this->headerFcn ) ? $fcn( $this ) : null; }
259
			public function setFooterFunction( \Closure $fcn ) { $this->footerFcn = $fcn; }
260
			public function setHeaderFunction( \Closure $fcn ) { $this->headerFcn = $fcn; }
261
		};
262
		$pdf->setCreator( PDF_CREATOR );
263
		$pdf->setAuthor( 'Aimeos' );
264
265
		// Generate HTML before creating first PDF page to include header added in template
266
		$template = $config->get( 'controller/jobs/order/email/payment/template-pdf', 'order/email/payment/pdf' );
267
		$content = $view->set( 'pdf', $pdf )->render( $template );
268
269
		$pdf->addPage();
270
		$pdf->writeHtml( $content );
271
		$pdf->lastPage();
272
273
		return $pdf->output( '', 'S' );
274
	}
275
276
277
	/**
278
	 * Sends the payment related e-mail for a single order
279
	 *
280
	 * @param \Aimeos\MW\View\Iface $view Populated view object
281
	 * @param string|null $logoPath Relative path to the logo in the fs-media file system
282
	 */
283
	protected function send( \Aimeos\MW\View\Iface $view, string $logoPath = null )
284
	{
285
		$context = $this->context();
286
		$config = $context->config();
287
		$filename = $context->translate( 'client', 'Order' ) . '-' . $view->orderItem->getOrderNumber() . '.pdf';
288
289
		$msg = $this->call( 'mailTo', $view->addressItem );
290
		$msg = $this->attachments( $msg );
291
		$view->logo = $msg->embed( $this->call( 'mailLogo', $logoPath ), basename( (string) $logoPath ) );
292
293
		/** client/html/email/payment/bcc-email
294
		 * E-Mail address all payment e-mails should be also sent to
295
		 *
296
		 * Using this option you can send a copy of all payment related e-mails
297
		 * to a second e-mail account. This can be handy for testing and checking
298
		 * the e-mails sent to customers.
299
		 *
300
		 * It also allows shop owners with a very small volume of orders to be
301
		 * notified about payment changes. Be aware that this isn't useful if the
302
		 * order volumne is high or has peeks!
303
		 *
304
		 * @param string|array E-mail address or list of e-mail addresses
305
		 * @since 2014.03
306
		 */
307
		$msg->bcc( $config->get( 'client/html/email/payment/bcc-email', [] ) );
308
309
		$msg->subject( sprintf( $context->translate( 'client', 'Your order %1$s' ), $view->orderItem->getOrderNumber() ) )
310
			->html( $view->render( $config->get( 'controller/jobs/order/email/payment/template-html', 'order/email/payment/html' ) ) )
311
			->text( $view->render( $config->get( 'controller/jobs/order/email/payment/template-text', 'order/email/payment/text' ) ) )
312
			->attach( $this->pdf( $view ), $filename, 'application/pdf' )
313
			->send();
314
	}
315
316
317
	/**
318
	 * Adds the status of the delivered e-mail for the given order ID
319
	 *
320
	 * @param string $orderId Unique order ID
321
	 * @param int $value Status value
322
	 */
323
	protected function status( string $orderId, int $value )
324
	{
325
		$manager = \Aimeos\MShop::create( $this->context(), 'order/status' );
326
327
		$item = $manager->create()
328
			->setParentId( $orderId )
329
			->setType( \Aimeos\MShop\Order\Item\Status\Base::EMAIL_PAYMENT )
330
			->setValue( $value );
331
332
		$manager->save( $item );
333
	}
334
335
336
	/**
337
	 * Returns the site items for the given site codes
338
	 *
339
	 * @param iterable $siteIds List of site IDs
340
	 * @return \Aimeos\Map Site items with codes as keys
341
	 */
342
	protected function sites( iterable $siteIds ) : \Aimeos\Map
343
	{
344
		$map = [];
345
		$manager = \Aimeos\MShop::create( $this->context(), 'locale/site' );
346
347
		foreach( $siteIds as $siteId )
348
		{
349
			$list = explode( '.', trim( $siteId, '.' ) );
350
			$map[$siteId] = $manager->getPath( end( $list ) );
351
		}
352
353
		return map( $map );
354
	}
355
356
357
	/**
358
	 * Returns the view populated with common data
359
	 *
360
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $base Basket including addresses
361
	 * @param string|null $theme Theme name
362
	 * @return \Aimeos\MW\View\Iface View object
363
	 */
364
	protected function view( \Aimeos\MShop\Order\Item\Base\Iface $base, string $theme = null ) : \Aimeos\MW\View\Iface
365
	{
366
		$address = $this->address( $base );
367
		$langId = $address->getLanguageId() ?: $base->locale()->getLanguageId();
368
369
		$view = $this->call( 'mailView', $langId );
370
		$view->intro = $this->call( 'mailIntro', $address );
371
		$view->css = $this->call( 'mailCss', $theme );
372
		$view->address = $address;
373
		$view->urlparams = [
374
			'currency' => $base->getPrice()->getCurrencyId(),
375
			'site' => $base->getSiteCode(),
376
			'locale' => $langId,
377
		];
378
379
		return $view;
380
	}
381
}
382