Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
mintsuro committed Jul 12, 2019
1 parent 8af92fb commit e71526d
Show file tree
Hide file tree
Showing 14 changed files with 167 additions and 134 deletions.
33 changes: 21 additions & 12 deletions cabinet/cart/cost/Cost.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,23 +53,22 @@ public function getTotalDiscSizeProd(int $size): float
if($size == $discount->size_products){
return $this->getOrigin() - $discount->value;
}
/*elseif($size <= $discount->size_products){
return $this->getOrigin() - $discount->value;
}*/
}

//return $this->getOrigin() - 300;
return $this->getOrigin();
}

/**
* Значение скидки
* @param int $size
* @return float
*/
public function getValueDisc(int $size): float
{
/** @var EntityDiscount $discount */
foreach($this->getEntityDiscounts() as $discount){
if($size == $discount->size_products){
return $discount->value;
}elseif($size > 3){
return 300; // временная загушка (добавить поле скидка по умолчанию)
}
}

Expand All @@ -84,6 +83,8 @@ public function getValueDisc(int $size): float
*/
public function getTotalDiscCode($code, $size)
{
$session = \Yii::$app->session;

/** @var $discount EntityDiscount */
try{
if($discount = EntityDiscount::find()->active() // Рассчет в процентном соотношении
Expand All @@ -93,10 +94,14 @@ public function getTotalDiscCode($code, $size)
->andWhere(['code' => $code])
->one())
{
$sum = ceil($this->getTotalDiscSizeProd($size) * $discount->value / 100); // (int) 35
$session['promo_code'] = [
'code' => $code,
'value' => $discount->value,
'type' => $discount->type_value,
];
$sum = ceil($this->getTotalDiscSizeProd($size) * $discount->value / 100);
$total = $this->getTotalDiscSizeProd($size) - $sum;
\Yii::$app->session->set('promo_code', $sum);
return Json::encode($sum);
return $sum;

}else if($discount = EntityDiscount::find()->active() // Рассчет в числовом соотношении
->andWhere(['AND',
Expand All @@ -105,9 +110,13 @@ public function getTotalDiscCode($code, $size)
->andWhere(['code' => $code])
->one())
{
$session['promo_code'] = [
'code' => $code,
'value' => $discount->value,
'type' => $discount->type_value,
];
$sum = ceil($this->getTotalDiscSizeProd($size) - $discount->value);
\Yii::$app->session->set('promo_code', $sum);
return Json::encode($sum);
return $sum;
}
}catch(\DomainException $e){
throw new \DomainException('Такой промокод не найден.');
Expand All @@ -122,7 +131,7 @@ public function getDiscounts(): array
return $this->discounts;
}

// Получить все скидки на товары при выборе n-ых чисел товаров
// Получить автоматические скидки на выборку n-ое число товаров
public function getEntityDiscounts(): array
{
if($discounts = EntityDiscount::find()->active()
Expand Down
3 changes: 0 additions & 3 deletions cabinet/readModels/cabinet/RaceReadRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ public function getByStartDate(): ActiveQuery
$query->where(['<=', 'date_start', date('Y-m-d H:i:s')]);
$query->andWhere(['>=', 'date_end', date('Y-m-d H:i:s')]);
//$query->andWhere(['status' => Race::STATUS_REGISTRATION]);
$query->orderBy(['date_start', SORT_ASC]);
return $query;
}

Expand All @@ -31,7 +30,6 @@ public function getByFinishDate(): ActiveQuery
$query = Race::find()->active();
$query->where(['<=', 'date_end', date('Y-m-d H:i:s')]);
//$query->andWhere(['status' => Race::STATUS_WAIT]);
$query->orderBy(['date_start', SORT_ASC]);
return $query;
}

Expand All @@ -41,7 +39,6 @@ public function getAllByStartReg(): DataProviderInterface
//$query->join('INNER JOIN', 'cabinet_user_participation us', 'us.user_id != :user_id', [':user_id' => $user->id]);
$query->where(['<=', 'date_reg_from', date('Y-m-d H:i:s')]);
$query->andWhere(['>=', 'date_reg_to', date('Y-m-d H:i:s')]);
$query->orderBy('date_end');
$query->all();
return $this->getProvider($query);
}
Expand Down
2 changes: 1 addition & 1 deletion cabinet/services/cabinet/RaceService.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,6 @@ public function registrationUser($userId, $raceId): void
$user = $this->users->get($userId);

$race->assignUser($user->id, $race->id);
// $this->email->sendEmailRegRace($user, $race);
$this->email->sendEmailRegRace($user, $race);
}
}
12 changes: 6 additions & 6 deletions cabinet/services/manage/cabinet/RaceManageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,11 @@ public function notifyStart(array $races): string
$race->save();
endforeach;

$res = 'Notifications all sent out';
$res = 'Новых уведомлений нет';

if($messages){
$this->email->mailer->sendMultiple($messages);
$res = 'Sent start race notification';
$res = 'Уведомление отправлено';
}

return $res;
Expand All @@ -128,11 +128,11 @@ public function notifyEnd(array $races): string
}
endforeach;

$res = 'Notifications all sent out';
$res = 'Новых уведомлений нет';

if($messages){
$this->email->mailer->sendMultiple($messages);
$res = 'Sent end race notification';
$res = 'Уведомление отправлено';
}

return $res;
Expand Down Expand Up @@ -161,11 +161,11 @@ public function notifyFinish(array $races): string
$race->save();
endforeach;

$res = 'Notifications all sent out';
$res = 'Новых уведомлений нет';

if($messages){
$this->email->mailer->sendMultiple($messages);
$res = 'Sent end race notification';
$res = 'Уведомление отправлено';
}

return $res;
Expand Down
8 changes: 4 additions & 4 deletions cabinet/services/manage/shop/OrderManageService.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,18 +137,18 @@ public function setSent($id, OrderSentForm $form): void
}

/**
* Уведомление о напоминании об оплате
* Уведомление о напоминании об оплате заказа после 6 часов
* @param Order[] $orders
* @return string
*/
public function notifyPay(array $orders): string
{
$messages = [];
$res = 'Unpaid orders not found';
$res = 'Неоплаченный заказ не найден';

try{
foreach($orders as $order):
if($order->created_at < time()){
if($order->created_at + 3600 * 6 < time()){
$messages[] = $this->email->emailNotifyPay($order->user, $order);
$order->notify_send = 1;
$order->update(false);
Expand All @@ -157,7 +157,7 @@ public function notifyPay(array $orders): string

if($messages){
$this->email->mailer->sendMultiple($messages);
$res = 'Send email for notify pay';
$res = 'Уведомление об оплате отправлено';
}
}catch(\DomainException $e){
\Yii::$app->errorHandler->logException($e);
Expand Down
28 changes: 21 additions & 7 deletions cabinet/services/shop/CartService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use cabinet\cart\Cart;
use cabinet\cart\CartItem;
use cabinet\cart\cost\Discount;
use cabinet\entities\shop\Discount as EntityDiscount;
use cabinet\repositories\shop\ProductRepository;
use cabinet\helpers\PriceHelper;
use yii\helpers\Json;
Expand Down Expand Up @@ -46,21 +48,34 @@ public function clear(): void
$this->cart->clear();
}

public function ajaxCalculateTotal($id = null){
// Рассчет общей стоимости выбранных товаров при добавлении товара
public function ajaxCalculateTotal($id = null)
{
$session = \Yii::$app->session;
$cart = $this->cart;
$cost = $cart->getCost();
$items = $cart->getItems();
$flag = $items ? true : false;
$data = [];
$data['url'] = Url::to(['/shop/cart/add', 'id' => $id]); // дополнить параметр id
$data['url'] = Url::to(['/shop/cart/add', 'id' => $id]);
$data['flag'] = $flag;
$data['amount'] = $cart->getAmount();

if($session->has('promo_code') && $items){
$data['discount'] = PriceHelper::format($cost->getValueDisc($cart->getAmount()) + $session->get('promo_code'));
$data['total'] = PriceHelper::format($cost->getTotalDiscSizeProd($cart->getAmount()) - $session->get('promo_code'));
}elseif ($items){
if(isset($session['promo_code']) && $items){
if($session['promo_code']['type'] == EntityDiscount::TYPE_VALUE_NUMBER){
$data['discount'] = PriceHelper::format($cost->getValueDisc($cart->getAmount()) + $session['promo_code']['value']);
$data['total'] = PriceHelper::format($cost->getTotalDiscSizeProd($cart->getAmount()) - $session['promo_code']['value']);
}elseif($session['promo_code']['type'] == EntityDiscount::TYPE_VALUE_PERCENT){
$data['discount'] = PriceHelper::format(ceil($cost->getValueDisc($cart->getAmount())
+ $cost->getValueDisc($cart->getAmount()) * $session['promo_code']['value'] / 100));
$data['total'] = PriceHelper::format(ceil($cost->getTotalDiscSizeProd($cart->getAmount())
- $cost->getTotalDiscSizeProd($cart->getAmount()) * $session['promo_code']['value'] / 100));
}else{
$data['discount'] = PriceHelper::format($cost->getValueDisc($cart->getAmount()) + $session['promo_code']['value']);
$data['total'] = PriceHelper::format($cost->getTotalDiscSizeProd($cart->getAmount()) - $session['promo_code']['value']);
}

}elseif($items){
$data['discount'] = PriceHelper::format($cost->getValueDisc($cart->getAmount()));
$data['total'] = PriceHelper::format($cost->getTotalDiscSizeProd($cart->getAmount()));
}else{
Expand All @@ -71,7 +86,6 @@ public function ajaxCalculateTotal($id = null){
foreach($cart->getItems() as $item){
if($item->getProductId() == $id){
$data['url'] = Url::to(['/shop/cart/remove', 'id' => $item->getId()]);
//break;
}
}

Expand Down
85 changes: 62 additions & 23 deletions cabinet/services/shop/OrderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use cabinet\cart\Cart;
use cabinet\cart\CartItem;
use cabinet\cart\cost\Discount;
use cabinet\entities\shop\Discount as DiscountEntity;
use cabinet\entities\shop\order\CustomerData;
use cabinet\entities\shop\order\DeliveryData;
use cabinet\entities\shop\order\Order;
Expand All @@ -16,6 +18,8 @@
use cabinet\repositories\UserRepository;
use cabinet\services\TransactionManager;
use phpDocumentor\Reflection\DocBlock\Tags\Throws;
use Yii;
use yii\helpers\Json;

class OrderService
{
Expand Down Expand Up @@ -57,21 +61,29 @@ public function checkout($raceId, $userId, OrderForm $form): Order
{
$user = $this->users->get($userId);
$session = \Yii::$app->session;

$products = [];
$cost = function() use ($session){
if(!$session->has('promo_code')) {
if ($this->cart->getItems() > 1) {
return (int) $this->cart->getCost()->getTotalDiscSizeProd($this->cart->getAmount());
} else {
return (int) $this->cart->getCost()->getOrigin();
}

if(!isset($session['promo_code'])) {
if($this->cart->getItems() > 1){
$cost = $this->cart->getCost()->getTotalDiscSizeProd($this->cart->getAmount());
}else{
$valuePromoCode = (int) $session->get('promo_code');
$discountValue = (int) $this->cart->getCost()->getTotalDiscSizeProd($this->cart->getAmount());
return $discountValue - $valuePromoCode;
$cost = $this->cart->getCost()->getOrigin();
}
};
}else{
$valuePromoCode = $session['promo_code']['value'];
if($session['promo_code']['type'] == DiscountEntity::TYPE_VALUE_NUMBER){
// Рассчет скидки при числовом коэффиценте значения промокода
$discountValue = $this->cart->getCost()->getTotalDiscSizeProd($this->cart->getAmount());
$cost = $discountValue - $valuePromoCode;
}elseif($session['promo_code']['type'] == DiscountEntity::TYPE_VALUE_PERCENT){
// Рассчет скидки при процентном коэффиценте значения промокода
$discountValue = $this->cart->getCost()->getTotalDiscSizeProd($this->cart->getAmount());
$cost = $discountValue - $discountValue * $valuePromoCode / 100;
}else{
$discountValue = $this->cart->getCost()->getTotalDiscSizeProd($this->cart->getAmount());
$cost = $discountValue - $valuePromoCode;
}
}

$items = array_map(function (CartItem $item){
$product = $item->getProduct();
Expand All @@ -90,9 +102,7 @@ public function checkout($raceId, $userId, OrderForm $form): Order
$form->customer->phone
),
$items,
($this->cart->getItems() > 1) ?
$this->cart->getCost()->getTotalDiscSizeProd($this->cart->getAmount()) :
$this->cart->getCost()->getOrigin() // $this->cart->getCost()->getTotal()
$cost
);

$order->setDeliveryInfo(
Expand All @@ -106,23 +116,52 @@ public function checkout($raceId, $userId, OrderForm $form): Order
$this->transaction->wrap(function() use ($order, $session){
$this->orders->save($order);
$this->cart->clear();
if($session->has('promo_code')){
$session->remove('promo_code');
if(isset($session['promo_code'])){
unset($session['promo_code']);
}
});

return $order;
}

// Рассчет при активации промокода
public function calcPromoCode($code, $size): float
public function calcPromoCode(string $code, $size)
{
$discount = $this->discounts->getByCode($code);
$session = \Yii::$app->session;
if(!$session->has('promo_code')) {
return $this->cart->getCost()->getTotalDiscCode($discount->code, $size);
return $this->cart->getCost()->getTotalDiscCode($code, $size);
}

// Проверка и обработка промокода
public function resultPromoCode(string $code)
{
$data = [];
$session = Yii::$app->session;
$discount = DiscountEntity::find()->active()->where(['type' => DiscountEntity::TYPE_PROMO_CODE])
->andWhere(['code' => $code])->one();

if(is_null($discount)){
$data['flag'] = false;
$data['text'] = 'Такой промокод не зарегистрирован.';
return Json::encode($data);
}else{
$code_session = $session['promo_code']['code'];
}

if($code != $code_session){
try {
$data['value'] = $this->calcPromoCode($code, $this->cart->getAmount());
$data['flag'] = true;
$data['text'] = 'Промокод активирован';
return Json::encode($data);
} catch (\DomainException $e) {
Yii::$app->errorHandler->logException($e);
$data['flag'] = false;
$data['text'] = 'Не удалось выполнить активацию.';
return Json::encode($data);
}
}else{
throw new \DomainException('Такой промокод уже активирован.');
$data['flag'] = false;
$data['text'] = 'Такой промокод уже активирован.';
return Json::encode($data);
}
}

Expand Down
3 changes: 1 addition & 2 deletions console/controllers/NotifyOrderController.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public function __construct($id, $module,
public function actionReminderPay(): bool
{
$orders = $this->repository->getNewAll();
$result = 'Not new orders';
$result = 'Не найдено новых заказов';

/** @var $order Order */
if($orders){
Expand All @@ -43,6 +43,5 @@ public function actionReminderPay(): bool

/** @var $result string */
$this->stdout($result . PHP_EOL);
return true;
}
}
Loading

0 comments on commit e71526d

Please sign in to comment.