Skip to content

Commit

Permalink
Merge branch 'checkout-fixes' into 'main'
Browse files Browse the repository at this point in the history
Checkout fixes

See merge request ecommerce_modules/cms/wordpress/wordpress!44
  • Loading branch information
vermorag committed Nov 22, 2024
2 parents 794af78 + 542ee92 commit 41f708a
Show file tree
Hide file tree
Showing 58 changed files with 1,628 additions and 1,759 deletions.
103 changes: 48 additions & 55 deletions src/Actions/CalculateDeliveryAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
class CalculateDeliveryAction
{
use CanBeCreated;

private ShippingMethod $method;
private array $rates = [];

Expand All @@ -33,7 +34,7 @@ class CalculateDeliveryAction
public function __invoke(array $package, int $instanceID, bool $addTariffsToOffice = true): array
{
$this->method = ShippingMethod::factory($instanceID);
$api = new CdekApi($instanceID);
$api = new CdekApi($instanceID);

if (empty($this->method->city_code) || !$api->checkAuth()) {
return [];
Expand All @@ -43,12 +44,13 @@ public function __invoke(array $package, int $instanceID, bool $addTariffsToOffi
'from' => [
'code' => $this->method->city_code,
],
'to' => [
'to' => [
'postal_code' => trim($package['destination']['postcode']),
'city' => trim($package['destination']['city']),
'address' => trim($package['destination']['city']),
'country_code' => trim($package['destination']['country']),
]
],
'packages' => $this->getPackagesData($package['contents']),
];

try {
Expand All @@ -58,18 +60,13 @@ public function __invoke(array $package, int $instanceID, bool $addTariffsToOffi
// do nothing
}

$deliveryParam['packages'] = $this->getPackagesData($package['contents']);
unset($deliveryParam['packages']['weight_orig_unit']);

if ($this->method->insurance) {
$deliveryParam['services'][] = [
'code' => 'INSURANCE',
'parameter' => (int)$package['contents_cost'],
];
}

$tariffList = $this->method->get_option('tariff_list');

$priceRules = json_decode($this->method->delivery_price_rules, true) ?: [
'office' => [['type' => 'percentage', 'to' => null, 'value' => 100]],
'door' => [['type' => 'percentage', 'to' => null, 'value' => 100]],
Expand Down Expand Up @@ -101,34 +98,33 @@ static function ($carry, $item) use ($package) {
continue;
}

if (isset($delivery['errors'])) {
continue;
}

foreach ($calcResult['tariff_codes'] as $tariff) {
if (isset($this->rates[$tariff['tariff_code']]) ||
!in_array((string)$tariff['tariff_code'], $tariffList ?: [], true)) {
!in_array((string)$tariff['tariff_code'], $this->method->tariff_list ?: [], true)) {
continue;
}

if (!$addTariffsToOffice && Tariff::isToOffice($tariff['tariff_code'])) {
if (!$addTariffsToOffice && Tariff::isToOffice((int)$tariff['tariff_code'])) {
continue;
}

$minDay = (int)$tariff['period_min'] + (int)$this->method->extra_day;
$maxDay = (int)$tariff['period_max'] + (int)$this->method->extra_day;
$cost = (int)$tariff['delivery_sum'];

if ((!isset($officeData['city']) && Tariff::isFromOffice($tariff['tariff_code'])) ||
(!isset($doorData['city']) && Tariff::isFromDoor($tariff['tariff_code']))) {
continue;
if ($maxDay < $minDay) {
$maxDay = $minDay;
}

$this->rates[$tariff['tariff_code']] = [
'id' => sprintf('%s:%s', Config::DELIVERY_NAME, $tariff['tariff_code']),
'label' => sprintf(
esc_html__('CDEK: %s, (%s-%s days)', 'cdekdelivery'),
Tariff::getNameByCode($tariff['tariff_code']),
'label' => ($minDay === $maxDay) ? sprintf(
esc_html__('%s, (%s day)', 'cdekdelivery'),
Tariff::getName($tariff['tariff_code'], $tariff['tariff_name']),
$minDay,
) : sprintf(
esc_html__('%s, (%s-%s days)', 'cdekdelivery'),
Tariff::getName($tariff['tariff_code'], $tariff['tariff_name']),
$minDay,
$maxDay,
),
Expand All @@ -150,59 +146,53 @@ static function ($carry, $item) use ($package) {
}
}

$deliveryMethod = $this->method;

return array_map(static function ($tariff) use (
return array_map(function ($tariff) use (
$priceRules,
$api,
$deliveryParam,
$deliveryMethod
$deliveryParam
) {
$rule = Tariff::isToOffice($tariff['meta_data'][MetaKeys::TARIFF_CODE]) ? $priceRules['office'] :
$rule = Tariff::isToOffice((int)$tariff['meta_data'][MetaKeys::TARIFF_CODE]) ? $priceRules['office'] :
$priceRules['door'];
if (isset($rule['type']) && $rule['type'] === 'free') {
$tariff['cost'] = 0;

return $tariff;
}
if (isset($rule['type'])) {
if ($rule['type'] === 'free') {
$tariff['cost'] = 0;

return $tariff;
}

if (isset($rule['type']) && $rule['type'] === 'fixed') {
$tariff['cost'] = max(
function_exists('wcml_get_woocommerce_currency_option') ?
apply_filters('wcml_raw_price_amount', $rule['value'], 'RUB') : $rule['value'],
0,
);
if ($rule['type'] === 'fixed') {
$tariff['cost'] = max(
function_exists('wcml_get_woocommerce_currency_option') ?
apply_filters('wcml_raw_price_amount', $rule['value'], 'RUB') : $rule['value'],
0,
);

return $tariff;
return $tariff;
}
}

$deliveryParam['tariff_code'] = $tariff['meta_data'][MetaKeys::TARIFF_CODE];
$deliveryParam['type'] = Tariff::getType($deliveryParam['tariff_code']);
$deliveryParam['type'] = Tariff::getType((int)$deliveryParam['tariff_code']);

$serviceList = Service::factory($deliveryMethod, $deliveryParam['tariff_code']);
$serviceList = Service::factory($this->method, $deliveryParam['tariff_code']);

if (!empty($serviceList)) {
$deliveryParam['services'] = array_merge($serviceList, $deliveryParam['services'] ?? []);
}

$tariffInfo = $api->calculateGet($deliveryParam);

if (empty($tariffInfo)) {
return $tariff;
}

$cost = $tariffInfo['total_sum'];
$cost = $api->calculateGet($deliveryParam) ?? $tariff['cost'];

if (isset($rule['type']) && $rule['type'] === 'amount') {
$cost += $rule['value'];
} elseif (isset($rule['type']) && $rule['type'] === 'percentage') {
$cost *= $rule['value'] / 100;
if (isset($rule['type'])) {
if ($rule['type'] === 'amount') {
$cost += $rule['value'];
} elseif ($rule['type'] === 'percentage') {
$cost *= $rule['value'] / 100;
}
}

if (function_exists('wcml_get_woocommerce_currency_option')) {
$costTMP = apply_filters('wcml_raw_price_amount', $cost, 'RUB');
$coef = $costTMP / $cost;
$cost /= $coef;
$cost /= apply_filters('wcml_raw_price_amount', $cost, 'RUB') / $cost;
}

$tariff['cost'] = max(ceil($cost), 0);
Expand All @@ -217,11 +207,14 @@ private function getPackagesData(array $contents): array
$lengthList = [];
$widthList = [];
$heightList = [];

$dimensionsInMM = get_option('woocommerce_dimension_unit') === 'mm';

foreach ($contents as $productGroup) {
$quantity = $productGroup['quantity'];
$weight = $productGroup['data']->get_weight();

$dimensions = get_option('woocommerce_dimension_unit') === 'mm' ? [
$dimensions = $dimensionsInMM ? [
(int)((int)$productGroup['data']->get_length() / 10),
(int)((int)$productGroup['data']->get_width() / 10),
(int)((int)$productGroup['data']->get_height() / 10),
Expand All @@ -243,7 +236,7 @@ private function getPackagesData(array $contents): array
$heightList[] = $dimensions[1];
$widthList[] = $dimensions[2];

$weight = WeightConverter::getWeight($weight);
$weight = WeightConverter::applyFallback($weight);
$totalWeight += $quantity * $weight;
}

Expand Down
105 changes: 28 additions & 77 deletions src/Actions/IntakeCreateAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use Cdek\Model\ValidationResult;
use Cdek\Note;
use Cdek\Traits\CanBeCreated;
use Cdek\Validator\IntakeValidator;
use DateTimeImmutable;

class IntakeCreateAction
{
Expand All @@ -35,32 +35,39 @@ public function __construct()
* @throws \Cdek\Exceptions\ShippingNotFoundException
* @throws \Cdek\Exceptions\OrderNotFoundException
*/
public function __invoke(int $orderId, array $data): ValidationResult
public function __invoke(Order $order, array $data): ValidationResult
{
$validate = IntakeValidator::validate($data);
if (!$validate->state) {
return $validate;
}

$order = new Order($orderId);
$shipping = $order->getShipping();

if ($shipping === null) {
throw new ShippingNotFoundException;
}

$tariffId = $shipping->tariff ?: $order->tariff_id;
$method = $shipping->getMethod();

if (Tariff::isFromDoor($tariffId)) {
$orderNumber = $order->number;
$param = $this->createRequestDataWithOrderNumber($data, $orderNumber);
} else {
$validate = IntakeValidator::validatePackage($data);
if (!$validate->state) {
return $validate;
}
$param = [
'need_call' => $data['call'] === 'true',
'intake_date' => (new DateTimeImmutable($data['date']))->format('Y-m-d'),
'intake_time_from' => $data['from'],
'intake_time_to' => $data['to'],
'comment' => $data['comment'] ?? null,
];

$param = $this->createRequestData($data);
if (Tariff::isFromDoor((int)($shipping->tariff ?: $order->tariff_id))) {
$param['cdek_number'] = $order->number;
} else {
$param['name'] = $data['desc'];
$param['weight'] = $data['weight'];
$param['from_location'] = [
'address' => $method->address,
'code' => $method->city_code,
];
$param['sender'] = [
'name' => $method->seller_name,
'phones' => [
'number' => $method->seller_phone,
],
];
}

$result = $this->api->intakeCreate($param);
Expand Down Expand Up @@ -118,74 +125,18 @@ public function __invoke(int $orderId, array $data): ValidationResult
$intake->save();

Note::send(
$orderId,
$order->id,
sprintf(
esc_html__(/* translators: 1: number of intake 2: uuid of intake*/
'Intake has been created: Number: %1$s | Uuid: %2$s',
'cdekdelivery',
),
$courierInfo['entity']['intake_number'],
$courierInfo['intake_number'],
$courierInfo['uuid'],
),
);

return new ValidationResult(
true, sprintf(
esc_html__(/* translators: %s: uuid of application*/ 'Intake number: %s', 'cdekdelivery'),
$courierInfo['intake_number'],
),
);
}

private function createRequestDataWithOrderNumber(array $data, string $orderNumber): array
{
$param['cdek_number'] = $orderNumber;
$param['intake_date'] = $data['date'];
$param['intake_time_from'] = $data['starttime'];
$param['intake_time_to'] = $data['endtime'];
$param['comment'] = $data['comment'];
$param['sender'] = [
'name' => $data['name'],
'phones' => [
'number' => $data['phone'],
],
];
$param['from_location'] = [
'address' => $data['address'],
];
if ($data['need_call'] === "true") {
$param['need_call'] = true;
} else {
$param['need_call'] = false;
}

return $param;
}

private function createRequestData(array $data): array
{
$param['intake_date'] = $data['date'];
$param['intake_time_from'] = $data['starttime'];
$param['intake_time_to'] = $data['endtime'];
$param['name'] = $data['desc'];
$param['weight'] = $data['weight'];
$param['length'] = $data['length'];
$param['width'] = $data['width'];
$param['height'] = $data['height'];
$param['comment'] = $data['comment'];
$param['sender'] = [
'name' => $data['name'],
'phones' => [
'number' => $data['phone'],
],
];
$param['from_location'] = [
'address' => $data['address'],
];

$param['need_call'] = $data['need_call'] === 'true';

return $param;
return new ValidationResult(true);
}
}
}
Loading

0 comments on commit 41f708a

Please sign in to comment.