Analytics.php
3 years ago
AutomatedLatestContent.php
2 months ago
AutomaticEmails.php
3 years ago
Captcha.php
1 year ago
Coupons.php
2 years ago
CustomFields.php
2 months ago
DynamicProducts.php
1 year ago
DynamicSegments.php
2 months ago
FeatureFlags.php
3 years ago
Forms.php
2 months ago
Help.php
1 year ago
ImportExport.php
2 months ago
Mailer.php
1 year ago
NewsletterLinks.php
2 months ago
NewsletterTemplates.php
2 months ago
Newsletters.php
2 months ago
Premium.php
10 months ago
RedirectResponse.php
1 year ago
Segments.php
2 months ago
SendingQueue.php
2 months ago
Services.php
6 months ago
Settings.php
2 months ago
Setup.php
1 year ago
StatisticsExport.php
3 months ago
SubscriberStats.php
1 month ago
Subscribers.php
2 months ago
Tags.php
3 years ago
UserFlags.php
2 years ago
WoocommerceProductVariations.php
2 months ago
WoocommerceSettings.php
3 years ago
index.php
3 years ago
DynamicSegments.php
268 lines
| 1 | <?php declare(strict_types = 1); |
| 2 | |
| 3 | namespace MailPoet\API\JSON\v1; |
| 4 | |
| 5 | if (!defined('ABSPATH')) exit; |
| 6 | |
| 7 | |
| 8 | use MailPoet\API\JSON\Endpoint as APIEndpoint; |
| 9 | use MailPoet\API\JSON\Error; |
| 10 | use MailPoet\API\JSON\Response; |
| 11 | use MailPoet\API\JSON\ResponseBuilders\DynamicSegmentsResponseBuilder; |
| 12 | use MailPoet\Config\AccessControl; |
| 13 | use MailPoet\ConflictException; |
| 14 | use MailPoet\Doctrine\Validator\ValidationException; |
| 15 | use MailPoet\Entities\SegmentEntity; |
| 16 | use MailPoet\Newsletter\Segment\NewsletterSegmentRepository; |
| 17 | use MailPoet\Segments\DynamicSegments\Exceptions\InvalidFilterException; |
| 18 | use MailPoet\Segments\DynamicSegments\FilterDataMapper; |
| 19 | use MailPoet\Segments\DynamicSegments\SegmentSaveController; |
| 20 | use MailPoet\Segments\SegmentsRepository; |
| 21 | use MailPoet\Segments\SegmentSubscribersRepository; |
| 22 | use Throwable; |
| 23 | |
| 24 | class DynamicSegments extends APIEndpoint { |
| 25 | |
| 26 | public $permissions = [ |
| 27 | 'global' => AccessControl::PERMISSION_MANAGE_SEGMENTS, |
| 28 | ]; |
| 29 | |
| 30 | /** @var SegmentsRepository */ |
| 31 | private $segmentsRepository; |
| 32 | |
| 33 | /** @var DynamicSegmentsResponseBuilder */ |
| 34 | private $segmentsResponseBuilder; |
| 35 | |
| 36 | /** @var SegmentSaveController */ |
| 37 | private $saveController; |
| 38 | |
| 39 | /** @var SegmentSubscribersRepository */ |
| 40 | private $segmentSubscribersRepository; |
| 41 | |
| 42 | /** @var FilterDataMapper */ |
| 43 | private $filterDataMapper; |
| 44 | |
| 45 | /** @var NewsletterSegmentRepository */ |
| 46 | private $newsletterSegmentRepository; |
| 47 | |
| 48 | public function __construct( |
| 49 | DynamicSegmentsResponseBuilder $segmentsResponseBuilder, |
| 50 | SegmentsRepository $segmentsRepository, |
| 51 | SegmentSubscribersRepository $segmentSubscribersRepository, |
| 52 | FilterDataMapper $filterDataMapper, |
| 53 | SegmentSaveController $saveController, |
| 54 | NewsletterSegmentRepository $newsletterSegmentRepository |
| 55 | ) { |
| 56 | $this->segmentsResponseBuilder = $segmentsResponseBuilder; |
| 57 | $this->segmentsRepository = $segmentsRepository; |
| 58 | $this->saveController = $saveController; |
| 59 | $this->segmentSubscribersRepository = $segmentSubscribersRepository; |
| 60 | $this->filterDataMapper = $filterDataMapper; |
| 61 | $this->newsletterSegmentRepository = $newsletterSegmentRepository; |
| 62 | } |
| 63 | |
| 64 | public function get($data = []) { |
| 65 | if (isset($data['id'])) { |
| 66 | $id = (int)$data['id']; |
| 67 | } else { |
| 68 | return $this->errorResponse([ |
| 69 | Error::BAD_REQUEST => __('Missing mandatory argument `id`.', 'mailpoet'), |
| 70 | ]); |
| 71 | } |
| 72 | |
| 73 | $segment = $this->segmentsRepository->findOneById($id); |
| 74 | if (!$segment instanceof SegmentEntity) { |
| 75 | return $this->errorResponse([ |
| 76 | Error::NOT_FOUND => __('This segment does not exist.', 'mailpoet'), |
| 77 | ]); |
| 78 | } |
| 79 | |
| 80 | return $this->successResponse($this->segmentsResponseBuilder->build($segment)); |
| 81 | } |
| 82 | |
| 83 | public function getCount($data = []) { |
| 84 | try { |
| 85 | $filterData = $this->filterDataMapper->map($data); |
| 86 | $count = $this->segmentSubscribersRepository->getDynamicSubscribersCount($filterData); |
| 87 | return $this->successResponse([ |
| 88 | 'count' => $count, |
| 89 | ]); |
| 90 | } catch (InvalidFilterException $e) { |
| 91 | return $this->errorResponse([ |
| 92 | Error::BAD_REQUEST => $this->getErrorString($e), |
| 93 | ], [], Response::STATUS_BAD_REQUEST); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | public function save($data) { |
| 98 | try { |
| 99 | $data['name'] = isset($data['name']) ? sanitize_text_field($data['name']) : ''; |
| 100 | $data['description'] = isset($data['description']) ? sanitize_textarea_field($data['description']) : ''; |
| 101 | $segment = $this->saveController->save($data); |
| 102 | return $this->successResponse($this->segmentsResponseBuilder->build($segment)); |
| 103 | } catch (InvalidFilterException $e) { |
| 104 | return $this->errorResponse([ |
| 105 | Error::BAD_REQUEST => $this->getErrorString($e), |
| 106 | ], [], Response::STATUS_BAD_REQUEST); |
| 107 | } catch (ConflictException $e) { |
| 108 | return $this->badRequest([ |
| 109 | Error::BAD_REQUEST => __('Another record already exists. Please specify a different "name".', 'mailpoet'), |
| 110 | ]); |
| 111 | } catch (ValidationException $exception) { |
| 112 | return $this->badRequest([ |
| 113 | Error::BAD_REQUEST => __('Please specify a name.', 'mailpoet'), |
| 114 | ]); |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | public function duplicate($data = []) { |
| 119 | $segment = $this->getSegment($data); |
| 120 | |
| 121 | if ($segment instanceof SegmentEntity) { |
| 122 | try { |
| 123 | $duplicate = $this->saveController->duplicate($segment); |
| 124 | } catch (Throwable $e) { |
| 125 | return $this->errorResponse([ |
| 126 | // translators: %s is the error message |
| 127 | Error::UNKNOWN => sprintf(__('Duplicating of segment failed: %s', 'mailpoet'), $e->getMessage()), |
| 128 | ], [], Response::STATUS_UNKNOWN); |
| 129 | } |
| 130 | return $this->successResponse( |
| 131 | $this->segmentsResponseBuilder->build($duplicate), |
| 132 | ['count' => 1] |
| 133 | ); |
| 134 | } else { |
| 135 | return $this->errorResponse([ |
| 136 | Error::NOT_FOUND => __('This segment does not exist.', 'mailpoet'), |
| 137 | ]); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | private function getErrorString(InvalidFilterException $e) { |
| 142 | switch ($e->getCode()) { |
| 143 | case InvalidFilterException::MISSING_TYPE: |
| 144 | return __('The segment type is missing.', 'mailpoet'); |
| 145 | case InvalidFilterException::INVALID_TYPE: |
| 146 | return __('The segment type is unknown.', 'mailpoet'); |
| 147 | case InvalidFilterException::MISSING_ROLE: |
| 148 | return __('Please select a user role.', 'mailpoet'); |
| 149 | case InvalidFilterException::MISSING_ACTION: |
| 150 | case InvalidFilterException::INVALID_EMAIL_ACTION: |
| 151 | return __('Please select an email action.', 'mailpoet'); |
| 152 | case InvalidFilterException::MISSING_NEWSLETTER_ID: |
| 153 | return __('Please select an email.', 'mailpoet'); |
| 154 | case InvalidFilterException::MISSING_PRODUCT_ID: |
| 155 | return __('Please select a product.', 'mailpoet'); |
| 156 | case InvalidFilterException::MISSING_COUNTRY: |
| 157 | return __('Please select a country.', 'mailpoet'); |
| 158 | case InvalidFilterException::MISSING_CATEGORY_ID: |
| 159 | return __('Please select a category.', 'mailpoet'); |
| 160 | case InvalidFilterException::MISSING_VALUE: |
| 161 | return __('Please fill all required values.', 'mailpoet'); |
| 162 | case InvalidFilterException::MISSING_NUMBER_OF_ORDERS_FIELDS: |
| 163 | return __('Please select a type for the comparison, a number of orders and a number of days.', 'mailpoet'); |
| 164 | case InvalidFilterException::MISSING_TOTAL_SPENT_FIELDS: |
| 165 | case InvalidFilterException::MISSING_SINGLE_ORDER_VALUE_FIELDS: |
| 166 | case InvalidFilterException::MISSING_AVERAGE_SPENT_FIELDS: |
| 167 | return __('Please select a type for the comparison, an amount and a number of days.', 'mailpoet'); |
| 168 | case InvalidFilterException::MISSING_FILTER: |
| 169 | return __('Please add at least one condition for filtering.', 'mailpoet'); |
| 170 | case InvalidFilterException::MISSING_OPERATOR: |
| 171 | return __('Please select a type for the comparison.', 'mailpoet'); |
| 172 | default: |
| 173 | return __('An error occurred while saving data.', 'mailpoet'); |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | public function trash($data = []) { |
| 178 | if (!isset($data['id'])) { |
| 179 | return $this->errorResponse([ |
| 180 | Error::BAD_REQUEST => __('Missing mandatory argument `id`.', 'mailpoet'), |
| 181 | ]); |
| 182 | } |
| 183 | |
| 184 | $segment = $this->getSegment($data); |
| 185 | if ($segment === null) { |
| 186 | return $this->errorResponse([ |
| 187 | Error::NOT_FOUND => __('This segment does not exist.', 'mailpoet'), |
| 188 | ]); |
| 189 | } |
| 190 | |
| 191 | $activelyUsedErrors = $this->getErrorMessagesForSegmentsUsedInActiveNewsletters([$segment->getId()]); |
| 192 | if (count($activelyUsedErrors) > 0) { |
| 193 | return $this->badRequest($activelyUsedErrors); |
| 194 | } |
| 195 | |
| 196 | $this->segmentsRepository->bulkTrash([$segment->getId()], SegmentEntity::TYPE_DYNAMIC); |
| 197 | return $this->successResponse( |
| 198 | $this->segmentsResponseBuilder->build($segment), |
| 199 | ['count' => 1] |
| 200 | ); |
| 201 | } |
| 202 | |
| 203 | public function getErrorMessagesForSegmentsUsedInActiveNewsletters(array $segmentIds): array { |
| 204 | $errors = []; |
| 205 | $activelyUsedNewslettersSubjects = $this->newsletterSegmentRepository->getSubjectsOfActivelyUsedEmailsForSegments($segmentIds); |
| 206 | foreach ($segmentIds as $segmentId) { |
| 207 | if (isset($activelyUsedNewslettersSubjects[$segmentId])) { |
| 208 | $segment = $this->getSegment(['id' => $segmentId]); |
| 209 | if ($segment) { |
| 210 | $errors[] = sprintf( |
| 211 | // translators: %1$s is the name of the segment, %2$s is a comma-separated list of emails for which the segment is used. |
| 212 | _x('Segment \'%1$s\' cannot be deleted because it’s used for \'%2$s\' email', 'Alert shown when trying to delete segment, which is assigned to any automatic emails.', 'mailpoet'), |
| 213 | $segment->getName(), |
| 214 | join("', '", $activelyUsedNewslettersSubjects[$segmentId]) |
| 215 | ); |
| 216 | } |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | return $errors; |
| 221 | } |
| 222 | |
| 223 | public function restore($data = []) { |
| 224 | if (!isset($data['id'])) { |
| 225 | return $this->errorResponse([ |
| 226 | Error::BAD_REQUEST => __('Missing mandatory argument `id`.', 'mailpoet'), |
| 227 | ]); |
| 228 | } |
| 229 | |
| 230 | $segment = $this->getSegment($data); |
| 231 | if ($segment === null) { |
| 232 | return $this->errorResponse([ |
| 233 | Error::NOT_FOUND => __('This segment does not exist.', 'mailpoet'), |
| 234 | ]); |
| 235 | } |
| 236 | |
| 237 | $this->segmentsRepository->bulkRestore([$segment->getId()], SegmentEntity::TYPE_DYNAMIC); |
| 238 | return $this->successResponse( |
| 239 | $this->segmentsResponseBuilder->build($segment), |
| 240 | ['count' => 1] |
| 241 | ); |
| 242 | } |
| 243 | |
| 244 | public function delete($data = []) { |
| 245 | if (!isset($data['id'])) { |
| 246 | return $this->errorResponse([ |
| 247 | Error::BAD_REQUEST => __('Missing mandatory argument `id`.', 'mailpoet'), |
| 248 | ]); |
| 249 | } |
| 250 | |
| 251 | $segment = $this->getSegment($data); |
| 252 | if ($segment === null) { |
| 253 | return $this->errorResponse([ |
| 254 | Error::NOT_FOUND => __('This segment does not exist.', 'mailpoet'), |
| 255 | ]); |
| 256 | } |
| 257 | |
| 258 | $this->segmentsRepository->bulkDelete([$segment->getId()], SegmentEntity::TYPE_DYNAMIC); |
| 259 | return $this->successResponse(null, ['count' => 1]); |
| 260 | } |
| 261 | |
| 262 | private function getSegment(array $data): ?SegmentEntity { |
| 263 | return isset($data['id']) |
| 264 | ? $this->segmentsRepository->findOneById((int)$data['id']) |
| 265 | : null; |
| 266 | } |
| 267 | } |
| 268 |