shoppingmallv2/app/Controllers/Front/Order/CartController.php
최준흠git config git config --helpgit config --global user.name 최준흠 3e55c62922 shoppingmallv2 init...
2023-08-13 17:54:44 +09:00

182 lines
7.6 KiB
PHP

<?php
namespace App\Controllers\Front\Order;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\ProductModel;
class CartController extends OrderController
{
private $_productModel = null;
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->_viewDatas['className'] = 'Cart';
$this->_viewPath .= '/' . strtolower($this->_viewDatas['className']);
$this->_viewDatas['title'] = lang($this->_viewDatas['className'] . '.title');
$this->_viewDatas['class_icon'] = CLASS_ICONS[strtoupper($this->_viewDatas['className'])];
helper($this->_viewDatas['className']);
}
final protected function getProductModel()
{
return $this->_productModel = $this->_productModel ?: new ProductModel();
}
public function getFields(string $action = ""): array
{
switch ($action) {
case 'insert':
return ["product_uid", "quantity", "price"];
break;
default:
return [];
break;
}
}
protected function getFieldRule(string $field, array $rules, string $action = ""): array
{
switch ($field) {
case 'product_uid':
$rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";
break;
case 'quantity':
case 'price':
$rules[$field] = "required|numeric";
break;
default:
$rules = parent::getFieldRule($field, $rules, $action);
break;
}
return $rules;
}
public function getFieldFilters(): array
{
return [];
}
public function getFieldBatchFilters(): array
{
return parent::getFieldBatchFilters();
}
protected function insert_process()
{
//addCart용 데이터 재처리 작업
$orderFormDatas = [];
$orderFormDatas[$this->_model->getTitleField()] = $this->_viewDatas['fieldDatas'][$this->_model->getTitleField()];
$orderFormDatas['product_uid'] = $this->_viewDatas['fieldDatas']['product_uid'];
$orderFormDatas['cost'] = $this->_viewDatas['fieldDatas']['price'];
$orderFormDatas['sale'] = 0;
$orderFormDatas['quantity'] = $this->_viewDatas['fieldDatas']['quantity'];
$orderFormDatas['price'] = $orderFormDatas['cost'] * $orderFormDatas['quantity'];
$this->_viewDatas['fieldDatas'] = $orderFormDatas;
// echo var_export($this->_viewDatas['fieldDatas']);
// exit;
return parent::insert_process();
}
//주문(uid->product_uid)
public function insert()
{
$msg = "";
try {
$this->_viewDatas = $this->init(__FUNCTION__);
//장바구니정보 검증
$this->insert_validate();
//상품정보 가져오기
$product = $this->getProductModel()->getEntity([$this->getProductModel()->getPrimaryKey() => $this->_viewDatas['fieldDatas']['product_uid']]);
//재고수 비교
if ($product->stock < $this->_viewDatas['fieldDatas']['quantity']) {
throw new \Exception("구매수량이 너무 많습니다.\n구매수량:{$this->_viewDatas['fieldDatas']['quantity']}개, 남은 재고수량:{$product->stock}");
}
//구매 금액 비교
$price = $product->price * $this->_viewDatas['fieldDatas']['quantity'];
if ($price != $this->_viewDatas['fieldDatas']['price']) {
throw new \Exception("실 상품금액{$price} 와 구매금액{$this->_viewDatas['fieldDatas']['price']}이 서로 다릅니다.");
}
//상품명을 복사해서 구매한 상품명에 넣기
$this->_viewDatas['fieldDatas'][$this->_model->getTitleField()] = $product->getTitle();
//Transaction 시작
$this->_model->transStart();
//주문추가
$entity = $this->insert_process();
//상품재고감소
$product = $this->getProductModel()->addCart($product, $this->_viewDatas['fieldDatas']['quantity']);
//주문정보 세션에 넣기
$order_uids = $this->_session->get(SESSION_NAMES['CART']) ?: array();
$this->_session->set(SESSION_NAMES['CART'], [...$order_uids, $entity->getPrimaryKey()]);
//Transaction Commit
$this->_model->transComplete();
$msg = sprintf(
"%s\n 상품명:%s\n 상품갯수:%s개, 구매금액:%s원\n 장바구니에 담았습니다.",
$this->_viewDatas['title'],
$entity->getTitle(),
$entity->quantity,
number_format($entity->price)
);
//Return URL clear -> 장바구니로 바로 이동
$this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']);
return redirect()->to(URLS['Order']);
} catch (\Exception $e) {
//Transaction Rollback
$this->_model->transRollback();
log_message("error", $e->getMessage());
$msg = sprintf(
"%s에서 다음 오류로 인해 장바구니에 담기를 실패하였습니다.\n%s",
$this->_viewDatas['title'],
$e->getMessage()
);
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} finally {
$this->_session->setFlashdata("return_message", $msg);
}
}
//주문취소(uid -> order_uid)
public function delete($uid)
{
$msg = "";
try {
//주문정보 가져오기
$entity = $this->_model->getEntity([$this->_model->getPrimaryKey() => $uid]);
//상품정보 가져오기
$product = $this->getProductModel()->getEntity([$this->getProductModel()->getPrimaryKey() => $entity->product_uid]);
//Transaction 시작
$this->_model->transStart();
//주문취소
$entity = $this->_model->modify($entity, ['status' => 'unuse']);
//상품반환
$product = $this->getProductModel()->cancelCart($product, $entity->quantity);
//주문정보 세션에서 빼기
$order_uids = $this->_session->get(SESSION_NAMES['CART']) ?: array();
$temps = array();
foreach ($order_uids as $order_uid) {
if ($order_uid != $entity->getPrimaryKey()) {
array_push($temps, $order_uid);
}
}
$this->_session->set(SESSION_NAMES['CART'], $temps);
//Transaction Commit
$this->_model->transComplete();
$msg = "{$this->_viewDatas['title']}에서 {$entity->getTitle()} {$entity->quantity}개의 주문을 취소하였습니다.";
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} catch (\Exception $e) {
//Transaction Rollback
$this->_model->transRollback();
$msg = sprintf(
"%s에서 다음 오류로 인해 주문취소를 실패하였습니다.\n%s",
$this->_viewDatas['title'],
$e->getMessage()
);
log_message("error", $e->getMessage());
return redirect()->to($this->_session->getFlashdata(SESSION_NAMES['RETURN_URL']));
} finally {
$this->_session->setFlashdata("return_message", $msg);
}
}
}