Commit 6bda769d authored by Batyr Mackenov's avatar Batyr Mackenov

#33

parent 600adae4
<?php
//##copyright##
$iaCart = $iaCore->factoryModule('cart', IA_CURRENT_MODULE);
$iaProduct = $iaCore->factoryModule('product', IA_CURRENT_MODULE);
if (iaView::REQUEST_JSON == $iaView->getRequestType()) {
$data = $_POST;
$output = ['message' => iaLanguage::get('something_went_wrong'), 'result' => iaView::ERROR];
switch ($pageAction) {
case iaCore::ACTION_ADD:
$productId = (int)$data['product'];
$qty = empty($data['quantity']) ? 1 : (int)$data['quantity'];
if ($productId) {
if ($iaCart->addItem($productId, $qty)) {
$output['message'] = (1 == $qty)
? iaLanguage::get('product_added_to_cart')
: iaLanguage::getf('num_items_added_to_cart', ['num' => $qty]);
$output['result'] = true;
$output['count'] = '(+' . $qty . ')';
if (1 === $qty) {
$product = $iaProduct->getById($productId);
$output['product'] = $product['title'];
}
$iaCart->recount();
}
}
break;
case iaCore::ACTION_DELETE:
$productId = (int)$data['product'];
$itemId = (int)$data['item_id'];
if ($productId) {
$output['result'] = $iaCart->deleteItem($productId, $itemId);
empty($output['result']) || $output['message'] = iaLanguage::get('product_removed');
$iaCart->recount();
}
}
$cart = $iaCart->get();
$iaView->loadSmarty(true);
$iaSmarty = &$iaView->iaSmarty;
$iaPage = $iaCore->factory('page', iaCore::FRONT);
$iaSmarty->assign('commerce', [
'cart' => (array)$cart,
'itemName' => $iaProduct->getItemName(),
'url' => ['cart' => $iaPage->getUrlByName('cart'), 'checkout' => $iaPage->getUrlByName('checkout')]
]);
$iaSmarty->assign('core', [
'config' => ['currency' => $iaCore->get('currency')]
]);
$output['count'] = $cart->count;
$output['total'] = (float)$cart->total . ' ' . $iaCore->get('currency');
$output['html'] = $iaSmarty->fetch('extra:commerce/widget.cart');
$iaView->assign($output);
}
if (iaView::REQUEST_HTML == $iaView->getRequestType()) {
$iaPage = $iaCore->factory('page');
if (isset($_POST['data-cart'])) {
foreach ($_POST['quantity'] as $itemId => $quantity) {
if (isset($_POST['q'][$itemId]) && $_POST['q'][$itemId] != $quantity) {
$iaCart->editItemQuantity($itemId, $quantity);
}
}
$iaCart->recount();
}
$checkoutUrl = $iaPage->getUrlByName('checkout');
$cart = $iaCart->get();
$items = $cart->items;
$total = $cart->total;
$iaView->assign('checkoutUrl', $checkoutUrl);
$iaView->assign('items', $items);
$iaView->assign('total', $total);
$iaView->display('cart');
}
\ No newline at end of file
<?php
//##copyright##
if (iaView::REQUEST_HTML == $iaView->getRequestType()) {
$iaView->display('checkout');
$iaField = $iaCore->factory('field');
$iaPage = $iaCore->factory('page', iaCore::FRONT);
$iaCart = $iaCore->factoryModule('cart', IA_CURRENT_MODULE);
$iaProduct = $iaCore->factoryModule('product', IA_CURRENT_MODULE);
$iaOrder = $iaCore->factoryModule('order', IA_CURRENT_MODULE);
$cart = $iaCart->get();
if (!$cart->count) {
iaUtil::go_to($iaPage->getUrlByName('cart'));
}
$iaOrder->save(['total' => $cart->total]);
$order = (array)$iaOrder->get();
if (isset($_POST['data-checkout'])) {
$messages = [];
$orderData = [];
list($orderData, , $messages, ) = $iaField->parsePost($iaOrder->getItemName(), $order);
$requiredFields = ['buyer_name', 'phone'];
foreach ($_POST['buyer'] as $key => $value) {
$orderData['buyer_' . $key] = $value;
if (empty($value) && in_array($key, $requiredFields))
{
$messages[] = iaLanguage::getf('field_is_empty', ['field' => iaLanguage::get($key)]);
}
}
$orderData['comment'] = iaSanitize::tags(trim($_POST['comment']));
$result = $iaOrder->save($orderData);
$order = $iaOrder->get();
if (empty($messages) && $result) {
$orderData = ['status' => iaOrder::PENDING];
if (isset($_POST['createaccount'])) {
$member = [
'email' => $order->buyer_email,
'fullname' => $order->buyer_first_name . ($order->buyer_last_name ? ' ' . $order->buyer_last_name : ''),
//'password' => $_POST['password']
'disable_fields' => true
];
$orderData['member_id'] = $iaCore->factory('users')->register($member);
}
$iaOrder->copyProductsFromCart();
$iaOrder->save($orderData);
iaHelper::sendEmail('order_placed', (array)$order);
$iaCart->cleanup();
$iaOrder->cleanup();
$iaCore->startHook('phpCommerceOrderPlaced', (array)$order);
$iaView->assign('itemName', $iaProduct->getItemName());
$iaView->assign('order', (array)$order);
$iaView->assign('products', $iaOrder->getItemsByOrderId($order->id));
$iaView->display('checkout.complete');
iaBreadcrumb::toEnd('Завершено');
return;
} else {
$iaView->setMessages($messages);
}
}
$iaView->assign('cartUrl', $iaPage->getUrlByName('cart'));
$iaView->assign('itemName', $iaProduct->getItemName());
$iaView->assign('order', (array)$order);
$iaView->assign('products', $cart->items);
}
\ No newline at end of file
<?php
//##copyright##
class iaHelper extends abstractCore
{
public static function sendEmail($event, array $data, $data2 = null)
{
iaCore::instance()->loadClass('common', 'mailer', 'commerce');
return iaEmailHelper::send($event, $data, $data2);
}
}
\ No newline at end of file
<?php
//##copyright##
class iaEmailHelper
{
protected static $_moduleName = 'commerce';
public static function send($eventType, $data, $data2 = null)
{
$emailsOptions = [
'order_placed' => true
];
$iaCore = iaCore::instance();
$params = [];
$addressee = [];
$result = true;
if (!$iaCore->get(self::$_moduleName . '_' . $eventType))
{
return $result;
}
$iaMailer = $iaCore->factory('mailer');
switch ($eventType)
{
case 'order_placed':
$addressee[$data['buyer_email']] = $data['buyer_name'];
$params['order'] = $data;
$params['items'] = $iaCore->factoryModule('order', self::$_moduleName)->getItemsByOrderId($data['id']);
}
if ($emailsOptions[$eventType]) {
$iaMailer->loadTemplate(self::$_moduleName . '_' . $eventType . '_admin');
$iaMailer->Body = self::_fetchEmailTemplate($eventType, $params, true);
$result = $iaMailer->sendToAdministrators(true);
}
if (!$addressee) {
return $result;
}
foreach ($addressee as $emailAddress => $title) {
$iaMailer->addAddress($emailAddress, $title);
}
$iaMailer->loadTemplate(self::$_moduleName . '_' . $eventType);
$iaMailer->Body = self::_fetchEmailTemplate($eventType, $params);
return ($result && $iaMailer->send());
}
private static function _fetchEmailTemplate($templateName, array $params, $useBackendTemplate = false)
{
static $iaSmarty;
if (is_null($iaSmarty)) {
$iaCore = iaCore::instance();
$iaSmarty = $iaCore->iaView->iaSmarty;
$iaSmarty->assign('nonProtocolUrl', $iaCore->iaView->assetsUrl);
$iaSmarty->assign('img', IA_TPL_URL . 'img/');
$iaSmarty->assign('core', [
'config' => $iaCore->getConfig()
]);
}
foreach ($params as $key => $value) {
$iaSmarty->assign($key, $value);
}
$templateName = 'email.' . ($useBackendTemplate ? 'admin.' : '') . $templateName;
return self::_compileLayout($iaSmarty, $iaSmarty->fetch('extra:' . self::$_moduleName . '/' . $templateName), $useBackendTemplate);
}
private static function _compileLayout(&$smarty, $content, $useBackendTemplate)
{
$iaCore = iaCore::instance();
$smarty->assign('_content_', $content);
$smarty->assign('defaultEmailSignature', str_replace(['{%SITE_URL%}', '{%SITE_NAME%}'],
[IA_URL, $iaCore->get('site')], $iaCore->get('default_email_signature')));
$layoutFile = 'extra:' . self::$_moduleName . '/email'. ($useBackendTemplate ? '.admin' : '') . '.layout';
//header('Content-type: text/html; charset=utf8');die($smarty->fetch($layoutFile));
return $smarty->fetch($layoutFile);
}
}
\ No newline at end of file
<?php
//##copyright##
class iaCart extends abstractModuleFront
{
const COOKIE_NAME = 'cart-id';
const EMULATED_CART_ID = 0;
protected static $_table = 'cart';
protected $_tableItems = 'cart_items';
protected $_moduleName = 'commerce';
protected $_itemName = 'products';
private static $_cart;
public function init()
{
parent::init();
$this->iaCore->factory('util');
}
public function getTableItems()
{
return $this->_tableItems;
}
public function get($forcedCreation = false)
{
if (is_null(self::$_cart)) {
$cartId = empty($_COOKIE[self::COOKIE_NAME]) ? null : (int)$_COOKIE[self::COOKIE_NAME];
if (!$cartId && !$forcedCreation) {
$cart = ['id' => self::EMULATED_CART_ID];
} else {
if (!$cartId && iaUsers::hasIdentity()) {
$cart = $this->_fetchByMemberId(iaUsers::getIdentity()->id);
}
elseif ($cartId) {
$cart = $this->getById($cartId);
}
if (empty($cart)) {
$cart = $this->_create();
}
$this->_setCookie($cart['id']);
}
self::$_cart = $this->_summarize($cart['id']);
}
return self::$_cart;
}
public function reload() // called when user signed in, makes possible to load cart contents populated earlier on other PC
{
if (self::EMULATED_CART_ID == $this->get()->id) {
self::$_cart = null;
$this->get(true);
}
}
public function recount()
{
if (self::$_cart) {
self::$_cart = $this->_summarize(self::$_cart->id);
}
}
public function cleanup()
{
$cart = $this->get();
// first, drop the variables
self::$_cart = null;
unset($_COOKIE[self::COOKIE_NAME]);
// ...then delete DB entries
$this->iaDb->delete(iaDb::convertIds($cart->id), self::getTable());
$this->iaDb->delete(iaDb::convertIds($cart->id, 'cart_id'), $this->getTableItems());
}
public function addItem($productId, $quantity)
{
$cart = $this->get(true);
$this->iaDb->setTable($this->getTableItems());
$iaProduct = $this->iaCore->factoryModule('product', $this->getModuleName());
$product = $iaProduct->getById($productId);
if (!$product) {
return false;
}
$stmt = '`cart_id` = :cart AND `product_id` = :product AND `price` = :price';
$this->iaDb->bind($stmt, ['cart' => $cart->id, 'product' => $productId, 'price' => $product['price']]);
if ($this->iaDb->exists($stmt)) {
$result = (bool)$this->iaDb->update(null, $stmt, ['qty' => '`qty` + ' . (int)$quantity]);
} else {
if ($product && iaCore::STATUS_ACTIVE == $product['status']) {
$item = [
'cart_id' => $cart->id,
'product_id' => (int)$productId,
'qty' => (int)$quantity,
'price' => $product['price']
];
$result = (bool)$this->iaDb->insert($item, null, $this->getTableItems());
} else {
$result = false;
}
}
$this->iaDb->resetTable();
return $result;
}
public function deleteItem($productId, $itemId)
{
$cart = $this->get();
return (bool)$this->iaDb->delete('`cart_id` = :cart AND `product_id` = :product AND `id` = :item_id',
$this->getTableItems(),
['cart' => $cart->id, 'product' => $productId, 'item_id' => $itemId]);
}
public function editItemQuantity($itemId, $quantity)
{
return (bool)$this->iaDb->update(['qty' => (int)$quantity], iaDb::convertIds($itemId),
null, $this->getTableItems());
}
protected function _getItems($cartId)
{
if (self::EMULATED_CART_ID == $cartId) {
return [];
}
$iaCategory = $this->iaCore->factoryModule('category', $this->getModuleName(), 'common');
$iaProduct = $this->iaCore->factoryModule('product', $this->getModuleName());
$sql = 'SELECT '
. 'p.*, '
. 'i.`id` `item_id`, i.`qty`, i.`price`, '
. 'c.`slug` `category_slug` '
. 'FROM `:prefix:table_items` i '
. 'LEFT JOIN `:prefix:table_products` p ON (p.`id` = i.`product_id`) '
. 'LEFT JOIN `:prefix:table_categories` c ON (c.`id` = p.`category_id`) '
. 'WHERE i.`cart_id` = :cart '
. 'ORDER BY i.`id` DESC';
$sql = iaDb::printf($sql, [
'prefix' => $this->iaDb->prefix,
'table_items' => $this->getTableItems(),
'table_products' => $iaProduct::getTable(),
'table_categories' => $iaCategory::getTable(),
'cart' => (int)$cartId
]);
$rows = $this->iaDb->getAll($sql);
$this->_processValues($rows);
return $rows;
}
protected function _summarize($cartId)
{
$items = $this->_getItems($cartId);
$count = $total = 0;
foreach ($items as $item) {
$count += $item['qty'];
$total += $item['price'] * $item['qty'];
}
$cartData = (object)[
'id' => $cartId,
'count' => $count,
'items' => $items,
'total' => $total
];
return $cartData;
}
protected function _fetchByMemberId($memberId)
{
return $this->iaDb->row(iaDb::ALL_COLUMNS_SELECTION, iaDb::convertIds($memberId, 'member_id'), self::getTable());
}
protected function _create()
{
$cart = [
'ip' => iaUtil::getIp(),
'member_id' => iaUsers::hasIdentity() ? iaUsers::getIdentity()->id : 0,
'date_created' => date(iaDb::DATETIME_FORMAT)
];
return ($cart['id'] = $this->iaDb->insert($cart, null, self::getTable()))
? $cart
: false;
}
protected function _setCookie($cartId)
{
$expireDate = time() + 60 * 60 * 24 * 60; // 60 days
setcookie(self::COOKIE_NAME, $cartId, $expireDate, '/');
}
public function fetch($where, $order, $limit = null)
{
$where.= ' ORDER BY ' . $order;
if ($result = $this->iaDb->all(iaDb::ALL_COLUMNS_SELECTION, $where, 0, $limit, self::getTable())) {
foreach ($result as &$entry) {
$memberId = $entry['member_id'];
$entry = $this->_summarize($entry['id']);
$entry->member_id = $memberId;
}
}
return $result;
}
}
\ No newline at end of file
<?php
//##copyright##
class iaOrder extends abstractModuleFront
{
const COOKIE_NAME = 'order-id';
const INCOMPLETE = 'incomplete';
const PENDING = 'pending';
const CANCELED = 'canceled';
const COMPLETED = 'completed';
protected static $_table = 'orders';
protected $_tableItems = 'orders_items';
protected $_itemName = 'orders';
protected $_moduleName = 'commerce';
protected $_statuses = [self::INCOMPLETE, self::PENDING, self::CANCELED, self::COMPLETED];
protected static $_order;
public function get()
{
if (is_null(self::$_order)) {
$orderId = $this->getCurrentOrderId();
if ($orderId) {
$order = $this->_fetch($orderId);
}
if (empty($order)) {
$order = $this->_create();
$this->_setCookie($order['id']);
}
self::$_order = (object)$order;
}
return self::$_order;
}
public function getCurrentOrderId()
{
return empty($_COOKIE[self::COOKIE_NAME]) ? null : $_COOKIE[self::COOKIE_NAME];
}
public function save(array $orderData)
{
if ($order = $this->get()) {
$this->iaDb->update($orderData, iaDb::convertIds($order->id), null, self::getTable());
if (0 == $this->iaDb->getErrorNumber()) {
$this->refresh();
return true;
}
}
return false;
}
public function refresh()
{
self::$_order = null;
}
public function getStatuses()
{
return $this->_statuses;
}
public function getTableItems()
{
return $this->_tableItems;
}
public function cleanup()
{
self::$_order = null;
$this->_setCookie(null);
unset($_COOKIE[self::COOKIE_NAME]);
}
public function copyProductsFromCart()
{
$iaCart = $this->iaCore->factoryModule('cart', $this->getModuleName());
$order = $this->get();
$cartItems = $iaCart->get()->items;
$iaDb = &$this->iaDb;
$iaDb->setTable($this->getTableItems());
foreach ($cartItems as $entry) {
$finalPrice = $entry['price'] * $entry['qty'];
$item = [
'order_id' => $order->id,
'product_id' => $entry['id'],
'category_id' => $entry['category_id'],
'title' => $entry['title'],
'price' => $entry['price'],
'discount' => 0,
'quantity' => $entry['qty'],
'price_total' => $finalPrice
];
$iaDb->insert($item);
}
$iaDb->resetTable();
}
public function getItemsByOrderId($orderId)
{
$iaProduct = $this->iaCore->factoryModule('product', $this->getModuleName());
$iaCategory = $this->iaCore->factoryModule('category', $this->getModuleName());
$sql =
'SELECT '
. 'i.*, '
. 'p.`alias`, p.`pictures`, '
. 'c.`url` `category_slug` '
. 'FROM `:prefix:table_items` i '
. 'LEFT JOIN `:prefix:table_products` p ON (p.`id` = i.`product_id`) '
. 'LEFT JOIN `:prefix:table_categories` c ON (c.`id` = i.`category_id`) '
. 'WHERE i.`order_id` = :order';
$sql = iaDb::printf($sql, [
'prefix' => $this->iaDb->prefix,
'table_items' => $this->getTableItems(),
'table_products' => $iaProduct::getTable(),
'table_categories' => $iaCategory::getTable(),
'order' => $orderId
]);
return $this->iaDb->getAll($sql);
}