PluginProbe
Packeta / trunk
Packeta vtrunk
2.3.2 2.3.1 trunk 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.3.0 1.3.1 1.3.2 1.4 1.4.1 1.4.2 1.4.3 1.5.0 1.5.1 1.5.2 1.5.3 1.5.4 1.6.0 1.6.1 1.6.2 1.6.3 1.6.4 All 56 releases
packeta / src / Packetery / Module / Carrier / CountryListingPage.php

CountryListingPage.php in Packeta trunk, at src/Packetery/Module/Carrier/CountryListingPage.php

396 lines 11.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Class CountryListingPage
4 *
5 * @package Packetery\Carrier
6 */
7
8 declare( strict_types=1 );
9
10 namespace Packetery\Module\Carrier;
11
12 use Packetery\Core\Log\Record;
13 use Packetery\Latte\Engine;
14 use Packetery\Module\CronService;
15 use Packetery\Module\FormFactory;
16 use Packetery\Module\Log;
17 use Packetery\Module\ModuleHelper;
18 use Packetery\Module\Options\OptionsProvider;
19 use Packetery\Module\Shipping\ShippingMethodGenerator;
20 use Packetery\Module\Transients;
21 use Packetery\Module\Views\UrlBuilder;
22 use Packetery\Nette\Forms\Form;
23 use Packetery\Nette\Http\Request;
24
25 /**
26 * Class CountryListingPage
27 *
28 * @package Packetery\Carrier
29 */
30 class CountryListingPage {
31
32 public const DATA_KEY_COUNTRY_CODE = 'countryCode';
33 public const PARAM_CARRIER_FILTER = 'carrier_query_filter';
34
35 /**
36 * PacketeryLatteEngine.
37 *
38 * @var Engine PacketeryLatte engine.
39 */
40 private $latteEngine;
41
42 /**
43 * Carrier repository.
44 *
45 * @var Repository Carrier repository.
46 */
47 private $carrierRepository;
48
49 /**
50 * Carrier downloader.
51 *
52 * @var CarrierUpdater
53 */
54 private $carrierUpdater;
55
56 /**
57 * Http request.
58 *
59 * @var Request
60 */
61 private $httpRequest;
62
63 /**
64 * Options provider
65 *
66 * @var OptionsProvider
67 */
68 private $optionsProvider;
69
70 /**
71 * Log Page
72 *
73 * @var Log\Page
74 */
75 private $logPage;
76
77 /**
78 * Internal pickup points config.
79 *
80 * @var PacketaPickupPointsConfig
81 */
82 private $pickupPointsConfig;
83
84 /**
85 * Carrier entity repository.
86 *
87 * @var EntityRepository
88 */
89 private $carrierEntityRepository;
90
91 /**
92 * Car delivery config.
93 *
94 * @var CarDeliveryConfig
95 */
96 private $carDeliveryConfig;
97
98 /**
99 * Carrier options factory.
100 *
101 * @var CarrierOptionsFactory
102 */
103 private $carrierOptionsFactory;
104
105 /**
106 * @var ModuleHelper
107 */
108 private $moduleHelper;
109
110 /**
111 * @var UrlBuilder
112 */
113 private $urlBuilder;
114
115 /**
116 * @var FormFactory
117 */
118 private $formFactory;
119
120 /**
121 * @var CarrierActivityBridge
122 */
123 private $carrierActivityBridge;
124
125 public function __construct(
126 Engine $latteEngine,
127 Repository $carrierRepository,
128 CarrierUpdater $carrierUpdater,
129 Request $httpRequest,
130 OptionsProvider $optionsProvider,
131 Log\Page $logPage,
132 PacketaPickupPointsConfig $pickupPointsConfig,
133 EntityRepository $carrierEntityRepository,
134 CarDeliveryConfig $carDeliveryConfig,
135 CarrierOptionsFactory $carrierOptionsFactory,
136 ModuleHelper $moduleHelper,
137 UrlBuilder $urlBuilder,
138 FormFactory $formFactory,
139 CarrierActivityBridge $carrierActivityBridge
140 ) {
141 $this->latteEngine = $latteEngine;
142 $this->carrierRepository = $carrierRepository;
143 $this->carrierUpdater = $carrierUpdater;
144 $this->httpRequest = $httpRequest;
145 $this->optionsProvider = $optionsProvider;
146 $this->logPage = $logPage;
147 $this->pickupPointsConfig = $pickupPointsConfig;
148 $this->carrierEntityRepository = $carrierEntityRepository;
149 $this->carDeliveryConfig = $carDeliveryConfig;
150 $this->carrierOptionsFactory = $carrierOptionsFactory;
151 $this->moduleHelper = $moduleHelper;
152 $this->urlBuilder = $urlBuilder;
153 $this->formFactory = $formFactory;
154 $this->carrierActivityBridge = $carrierActivityBridge;
155 }
156
157 /**
158 * Renders page.
159 */
160 public function render(): void {
161 $redirectUrl = add_query_arg( [ 'page' => OptionsPage::SLUG ], get_admin_url( null, 'admin.php' ) );
162 $this->carrierUpdater->startUpdate( $redirectUrl );
163 $carriersUpdateParams = $this->carrierUpdater->runUpdate();
164
165 $carriersUpdateParams['link'] = add_query_arg(
166 [
167 'page' => OptionsPage::SLUG,
168 'update_carriers' => '1',
169 ],
170 get_admin_url( null, 'admin.php' )
171 );
172 $carriersUpdateParams['lastUpdate'] = $this->carrierUpdater->getLastUpdate();
173
174 $form = $this->formFactory->create();
175 $form->setAction( 'admin.php?page=' . OptionsPage::SLUG );
176 $form->setMethod( Form::GET );
177 $form->addText( self::PARAM_CARRIER_FILTER );
178 $form->addSubmit( 'filter', __( 'Filter', 'packeta' ) );
179
180 $isApiPasswordSet = false;
181 if ( $this->optionsProvider->get_api_password() !== null ) {
182 $isApiPasswordSet = true;
183 }
184
185 $nextScheduledRun = null;
186 $nextScheduledRunTimestamp = as_next_scheduled_action( CronService::CRON_CARRIERS_HOOK );
187 if ( is_int( $nextScheduledRunTimestamp ) ) {
188 $date = new \DateTime();
189 $date->setTimezone( wp_timezone() );
190 $date->setTimestamp( $nextScheduledRunTimestamp );
191 $nextScheduledRun = $date->format( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) );
192 }
193
194 $carrierChanges = get_transient( Transients::CARRIER_CHANGES );
195 $settingsChangedMessage = null;
196 if ( $carrierChanges !== false ) {
197 $settingsChangedMessage = sprintf( // translators: 1: link start 2: link end.
198 esc_html__( 'The carrier settings have changed since the last carrier update. %1$sShow logs%2$s', 'packeta' ),
199 '<a href="' . $this->logPage->createLogListUrl( null, Record::ACTION_CARRIER_LIST_UPDATE ) . '">',
200 '</a>'
201 );
202 }
203
204 $hasCarriers = false;
205 $countries = $this->getActiveCountries();
206 foreach ( $countries as $country ) {
207 if ( isset( $country['allCarriers'] ) ) {
208 $hasCarriers = true;
209
210 break;
211 }
212 }
213
214 $translations = [
215 'packeta' => __( 'Packeta', 'packeta' ),
216 'title' => __( 'Carriers', 'packeta' ),
217 'carriersUpdate' => __( 'Carriers update', 'packeta' ),
218 'countries' => __( 'Countries', 'packeta' ),
219 'activeCarrier' => __( 'Active carrier', 'packeta' ),
220 'action' => __( 'Action', 'packeta' ),
221 'countryName' => __( 'Country name', 'packeta' ),
222 'carrier' => __( 'Carrier', 'packeta' ),
223 'countryCode' => __( 'Country code', 'packeta' ),
224 'setUp' => __( 'Set up', 'packeta' ),
225 'status' => __( 'Status', 'packeta' ),
226 'active' => __( 'Active', 'packeta' ),
227 'inactive' => __( 'Inactive', 'packeta' ),
228 'noActiveCountries' => __( 'No active countries.', 'packeta' ),
229 'noCarriersFound' => __( 'No results found!', 'packeta' ),
230 'searchPlaceholder' => __( 'Search carriers', 'packeta' ),
231 'lastCarrierUpdateDatetime' => __( 'Date of the last update of carriers', 'packeta' ),
232 'carrierListNeverDownloaded' => __( 'Carrier list was not yet downloaded. Continue by clicking the Run update of carriers button.', 'packeta' ),
233 'runCarrierUpdate' => __( 'Run update of carriers', 'packeta' ),
234 'pleaseCompleteSetupFirst' => __( 'Before updating the carriers, please complete the plugin setup first.', 'packeta' ),
235 'nextScheduledRunPlannedAt' => __( 'The next automatic update will occur at', 'packeta' ),
236 ];
237
238 if ( $this->optionsProvider->isWcCarrierConfigEnabled() ) {
239 $settingsTemplate = PACKETERY_PLUGIN_DIR . '/template/carrier/wcNativeSettings.latte';
240 } else {
241 $settingsTemplate = PACKETERY_PLUGIN_DIR . '/template/carrier/countries.latte';
242 }
243
244 $this->latteEngine->render(
245 $settingsTemplate,
246 new CountryListingTemplateParams(
247 $carriersUpdateParams,
248 $countries,
249 $isApiPasswordSet,
250 $nextScheduledRun,
251 $settingsChangedMessage,
252 $this->moduleHelper->isCzechLocale(),
253 $this->urlBuilder->buildAssetUrl( 'public/images/logo-zasilkovna.svg' ),
254 $this->urlBuilder->buildAssetUrl( 'public/images/logo-packeta.svg' ),
255 $translations,
256 $hasCarriers,
257 $form
258 )
259 );
260 }
261
262 /**
263 * Returns Sorted data for template.
264 *
265 * @return array Data.
266 */
267 private function getActiveCountries(): array {
268 $countries = $this->carrierRepository->getCountriesWithUnavailable();
269
270 $internalCountries = $this->pickupPointsConfig->getInternalCountries();
271 $countries = array_unique( array_merge( $internalCountries, $countries ) );
272
273 $countriesFinal = [];
274 foreach ( $countries as $country ) {
275 $allCarriers = $this->getCarriersDataByCountry( $country, true );
276 $activeCarriers = array_filter(
277 $allCarriers,
278 static function ( array $carrierData ): bool {
279 return $carrierData['isActive'];
280 }
281 );
282 $wcCountries = \WC()->countries->get_countries();
283 $countriesFinal[] = [
284 self::DATA_KEY_COUNTRY_CODE => $country,
285 'name' => $wcCountries[ strtoupper( $country ) ],
286 'url' => add_query_arg(
287 [
288 'page' => OptionsPage::SLUG,
289 OptionsPage::PARAMETER_COUNTRY_CODE => $country,
290 ],
291 get_admin_url( null, 'admin.php' )
292 ),
293 'activeCarriers' => $activeCarriers,
294 'allCarriers' => $allCarriers,
295 'flag' => $this->urlBuilder->buildAssetUrl( sprintf( 'public/images/flags/%s.png', $country ) ),
296 ];
297 }
298
299 usort(
300 $countriesFinal,
301 static function ( $a, $b ) {
302 if ( $a[ self::DATA_KEY_COUNTRY_CODE ] === 'cz' ) {
303 return - 1;
304 }
305 if ( $b[ self::DATA_KEY_COUNTRY_CODE ] === 'cz' ) {
306 return 1;
307 }
308 if ( $a[ self::DATA_KEY_COUNTRY_CODE ] === 'sk' ) {
309 return - 1;
310 }
311 if ( $b[ self::DATA_KEY_COUNTRY_CODE ] === 'sk' ) {
312 return 1;
313 }
314
315 return strnatcmp( (string) $a['name'], (string) $b['name'] );
316 }
317 );
318
319 return $countriesFinal;
320 }
321
322 /**
323 * Gets options of active carriers.
324 *
325 * @return array
326 */
327 public function getCarriersForOptionsExport(): array {
328 $carriersWithSomeOptions = [];
329 $allCarriers = $this->carrierEntityRepository->getAllCarriersIncludingNonFeed();
330 foreach ( $allCarriers as $carrier ) {
331 $carrierId = $carrier->getId();
332 $optionId = OptionPrefixer::getOptionId( $carrierId );
333 $carrierOptions = get_option( $optionId );
334 if ( $carrierOptions !== false ) {
335 unset( $carrierOptions['id'] );
336 $originalName = $carrier->getName();
337 $cartName = $carrierOptions['name'];
338 unset( $carrierOptions['name'] );
339 $addition = [
340 'original_name' => $originalName,
341 'cart_name' => $cartName,
342 ];
343 $carrierOptions = array_merge( $addition, $carrierOptions );
344 $carriersWithSomeOptions[ $optionId ] = $carrierOptions;
345 }
346 }
347
348 return $carriersWithSomeOptions;
349 }
350
351 /**
352 * Gets array of carriers data by country code.
353 *
354 * @param string $countryCode Country code.
355 * @param bool $includeUnavailable Include unavailable carriers.
356 *
357 * @return array
358 */
359 private function getCarriersDataByCountry( string $countryCode, bool $includeUnavailable ): array {
360 $carriersData = [];
361 $keyword = $this->httpRequest->getQuery( self::PARAM_CARRIER_FILTER ) ?? '';
362 $countryCarriers = $this->carrierEntityRepository->getByCountryIncludingNonFeed( $countryCode, $includeUnavailable );
363 foreach ( $countryCarriers as $carrier ) {
364 if ( $carrier->isCarDelivery() && $this->carDeliveryConfig->isDisabled() ) {
365 continue;
366 }
367
368 if ( $this->optionsProvider->isWcCarrierConfigEnabled() && ! ShippingMethodGenerator::classExists( $carrier->getId() ) ) {
369 continue;
370 }
371
372 if ( $keyword !== '' && stripos( $carrier->getName(), $keyword ) === false ) {
373 continue;
374 }
375
376 $carrierId = $carrier->getId();
377 $carrierOptions = $this->carrierOptionsFactory->createByCarrierId( $carrierId );
378
379 $carriersData[ $carrierId ] = [
380 'name' => $carrier->getName(),
381 'isActivatedByUser' => $carrierOptions->isActive(),
382 'isActive' => $this->carrierActivityBridge->isActive( $carrier, $carrierOptions ),
383 'detailUrl' => add_query_arg(
384 [
385 'page' => OptionsPage::SLUG,
386 OptionsPage::PARAMETER_CARRIER_ID => $carrierId,
387 ],
388 get_admin_url( null, 'admin.php' )
389 ),
390 ];
391 }
392
393 return $carriersData;
394 }
395 }
396