Skip to content

Commit

Permalink
Merge branch 'checkout-fixes'
Browse files Browse the repository at this point in the history
  • Loading branch information
vermorag committed Nov 25, 2024
2 parents 41f708a + bcf86cf commit 61646cf
Show file tree
Hide file tree
Showing 8 changed files with 141 additions and 81 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"start": "wp-scripts start",
"env": "wp-env start --update"
"env": "wp-env start --update",
"destroy": "wp-env destroy"
},
"dependencies": {
"@cdek-it/widget": "^3.11.0",
Expand Down
37 changes: 30 additions & 7 deletions src/Controllers/IntakeController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
use Cdek\Exceptions\External\InvalidRequestException;
use Cdek\Model\Order;
use Cdek\Model\Tariff;
use DateTimeImmutable;
use JsonException;

class IntakeController
Expand All @@ -33,12 +32,28 @@ public static function create(): void
wp_die(-2, 403);
}

$id = (int)$_REQUEST['id'];
$id = (int)wp_unslash($_REQUEST['id']);

try {
$order = new Order($id);
} catch (ExceptionContract $e) {
AdminOrderBox::createOrderMetaBox(
$id,
['errors' => [$e->getMessage()]],
);

wp_die();
}

try {
$body = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
wp_die($e->getMessage());
AdminOrderBox::createOrderMetaBox(
$order,
['errors' => [$e->getMessage()]],
);

wp_die();
}

$val = rest_validate_object_value_from_schema($body, [
Expand Down Expand Up @@ -84,10 +99,13 @@ public static function create(): void
], 'intake');

if (is_wp_error($val)) {
wp_die($val);
}
AdminOrderBox::createOrderMetaBox(
$order,
['errors' => $val->get_error_messages()],
);

$order = new Order($id);
wp_die();
}

$shipping = $order->getShipping();
$tariff = $shipping !== null ? $shipping->tariff : null;
Expand All @@ -105,7 +123,12 @@ public static function create(): void
], 'intake');

if (is_wp_error($val)) {
wp_die($val);
AdminOrderBox::createOrderMetaBox(
$order,
['errors' => $val->get_error_messages()],
);

wp_die();
}
}

Expand Down
25 changes: 23 additions & 2 deletions src/Controllers/OrderController.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,26 @@ public static function create(): void

$id = (int)wp_unslash($_REQUEST['id']);

try {
$order = new Order($id);
} catch (ExceptionContract $e) {
AdminOrderBox::createOrderMetaBox(
$id,
['errors' => [$e->getMessage()]],
);

wp_die();
}

try {
$body = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
wp_die($e->getMessage());
AdminOrderBox::createOrderMetaBox(
$order,
['errors' => [$e->getMessage()]],
);

wp_die();
}

$val = rest_validate_array_value_from_schema($body, [
Expand Down Expand Up @@ -109,7 +125,12 @@ public static function create(): void
], 'packages');

if (is_wp_error($val)) {
wp_die($val);
AdminOrderBox::createOrderMetaBox(
$order,
['errors' => $val->get_error_messages()],
);

wp_die();
}

try {
Expand Down
31 changes: 25 additions & 6 deletions src/Frontend/AdminOrder/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,29 @@ $(document).ready(() => {
e.preventDefault();
e.stopPropagation();

const len = metaBox.find('input[name=length]').val();
const wid = metaBox.find('input[name=width]').val();
const hei = metaBox.find('input[name=height]').val();

if (isNaN(len) || len === '') {
alert(__('Package length not specified', 'cdekdelivery'));
return;
}

if (isNaN(wid) || wid === '') {
alert(__('Package width not specified', 'cdekdelivery'));
return;
}

if (isNaN(hei) || hei === '') {
alert(__('Package height not specified', 'cdekdelivery'));
return;
}

const packageData = {
length: parseInt(metaBox.find('input[name=length]').val()),
width: parseInt(metaBox.find('input[name=width]').val()),
height: parseInt(metaBox.find('input[name=height]').val()),
length: parseInt(len),
width: parseInt(wid),
height: parseInt(hei),
items: metaBox.find(`.item[data-id][aria-hidden=false]`)
.map((i, e) => ({
id: parseInt(e.dataset.id),
Expand All @@ -78,15 +97,15 @@ $(document).ready(() => {
};

if (packageData.length < 1) {
alert(__('Package length not specified', 'cdekdelivery'));
alert(__('Package length should be greater 1', 'cdekdelivery'));
return;
}
if (packageData.width < 1) {
alert(__('Package width not specified', 'cdekdelivery'));
alert(__('Package width be greater 1', 'cdekdelivery'));
return;
}
if (packageData.height < 1) {
alert(__('Package height not specified', 'cdekdelivery'));
alert(__('Package height be greater 1', 'cdekdelivery'));
return;
}
if (packageData.items.length < 1) {
Expand Down
102 changes: 50 additions & 52 deletions src/Frontend/CheckoutMapShortcode/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ import { debounce } from 'lodash';
const billingCityInput = $('#billing_city');
const shippingCityInput = $('#shipping_city');
let widget = null;
let el;



if ((billingCityInput.val() || '') !== '' || (shippingCityInput.val() || '') !== '') {
if ((billingCityInput.val() || '') !== '' || (shippingCityInput.val() || '') !==
'') {
console.debug('[CDEK-MAP] City has value, initiating checkout update');
$(document.body).trigger('update_checkout');
}

const closeMap = (el, errorMessage = null) => {
const closeMap = (e, errorMessage = null) => {
console.debug('[CDEK-MAP] Removing selected office info');

$('.cdek-office-info').remove();
el.html(__('Choose pick-up', 'cdekdelivery'));
e.find('a').html(__('Choose pick-up', 'cdekdelivery'));
$('.cdek-office-code').val('');

if (widget !== null) {
Expand All @@ -35,19 +35,18 @@ const closeMap = (el, errorMessage = null) => {
}
};

let el;

const onChoose = (_type, _tariff, address) => {
$('.cdek-office-code').val(address.code);
el.html(__('Re-select pick-up', 'cdekdelivery'));
el.find('a').html(__('Re-select pick-up', 'cdekdelivery'));

const officeInfo = el.parent().children('.cdek-office-info');
if (officeInfo.length === 0) {
el.before(
`<div class="cdek-office-info">${address.name}</div>`);
el.before($('<div class="cdek-office-info"></div>').text(address.name));
} else {
officeInfo.html(`${address.name}`);
officeInfo.text(address.name);
}
if ($('.cdek-office-code').data('map-auto-close')) {

if (window.cdek.close) {
widget.close();
}
};
Expand All @@ -74,48 +73,47 @@ $(document.body)
widget.clearSelection();
}
})
.on('change', '.shipping_method', () => {
$(document.body).trigger('update_checkout');
})
.on('change', '.shipping_method',
() => $(document.body).trigger('update_checkout'))
.on('click', '.open-pvz-btn', null, (e) => {
el = $(e.target);
el = e.target.tagName === 'A' ? $(e.target.parentElement) : $(e.target);
closeMap(el);

const points = el.data('points');
console.debug('[CDEK-MAP] Got points from backend:', points);

if (typeof points !== 'object') {
console.error('[CDEK_MAP] backend points not object');
closeMap(el,
__('CDEK was unable to load the list of available pickup points, please select another delivery method', 'cdekdelivery'));

return;
} else if (!points.length) {
console.warn('[CDEK_MAP] backend points are empty');
closeMap(el,
__('There are no CDEK pick-up points available in this direction, please select another delivery method')
);

return;
try {
const points = JSON.parse(el.find('script').text());
console.debug('[CDEK-MAP] Got points from backend', points);

if (!points.length) {
console.warn('[CDEK-MAP] Backend points are empty');
closeMap(el, __(
'There are no CDEK pick-up points available in this direction, please select another delivery method'));

return;
}

if (widget === null) {
widget = new cdekWidget({
apiKey: window.cdek.key,
popup: true,
debug: true,
lang: window.cdek.lang,
defaultLocation: el.data('city'),
officesRaw: points,
hideDeliveryOptions: {
door: true,
},
onChoose,
});
} else {
widget.updateOfficesRaw(points);
widget.updateLocation(el.data('city'));
}

widget.open();
} catch (SyntaxError) {
console.error('[CDEK-MAP] SyntaxError during points parse');

closeMap(el, __(
'There are no CDEK pick-up points available in this direction, please select another delivery method'));
}

if (widget === null) {
widget = new cdekWidget({
apiKey: window.cdek.apiKey,
popup: true,
debug: true,
lang: el.data('lang'),
defaultLocation: el.data('city'),
officesRaw: points,
hideDeliveryOptions: {
door: true,
},
onChoose,
});
} else {
widget.updateOfficesRaw(points);
widget.updateLocation(el.data('city'));
}

widget.open();
});
2 changes: 1 addition & 1 deletion src/Transport/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static function sendJsonRequest(
}

if ($result->isClientError()) {
throw new HttpClientException($result->error());
throw new HttpClientException($result->error() ?? []);
}

return $result;
Expand Down
6 changes: 5 additions & 1 deletion src/UI/CdekWidget.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@ public static function registerScripts(): void
{
wp_register_script('cdek-widget', Loader::getPluginUrl('build/cdek-widget.umd.js'));

$shipping = ShippingMethod::factory();

wp_localize_script('cdek-widget', 'cdek', [
'apiKey' => ShippingMethod::factory()->yandex_map_api_key,
'key' => $shipping->yandex_map_api_key,
'close' => $shipping->map_auto_close,
'lang' => mb_strpos(get_user_locale(), 'en') === 0 ? 'eng' : 'rus',
]);
}

Expand Down
16 changes: 5 additions & 11 deletions src/UI/CheckoutMap.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use Cdek\Config;
use Cdek\Helpers\CheckoutHelper;
use Cdek\Model\Tariff;
use Cdek\ShippingMethod;

class CheckoutMap
{
Expand All @@ -34,19 +33,14 @@ public function __invoke($shippingMethodCurrent): void

$city = $api->cityCodeGet($cityInput, $postcodeInput);

$points = $city !== null ? $api->officeListRaw($city) : '[]';

echo '<div class="open-pvz-btn" data-points="'.
esc_attr($points).
'" data-city="'.
echo '<div class="open-pvz-btn" data-city="'.
esc_attr($cityInput).
'" data-lang="'.
(mb_strpos(get_user_locale(), 'en') === 0 ? 'eng' : 'rus').
'">'.
'<script type="application/cdek-offices">'.
wc_esc_json($city !== null ? $api->officeListRaw($city) : '[]', true).
'</script><a>'.
esc_html__('Choose pick-up', 'cdekdelivery').
'</div><input name="office_code" class="cdek-office-code" type="hidden" data-map-auto-close="'.
esc_attr(ShippingMethod::factory()->map_auto_close).
'">';
'</a></div><input name="office_code" class="cdek-office-code" type="hidden">';
}

private function isTariffDestinationCdekOffice($shippingMethodCurrent): bool
Expand Down

0 comments on commit 61646cf

Please sign in to comment.