wip: shopping cart

This commit is contained in:
Nikita Kiselev
2025-07-23 18:40:57 +03:00
parent bb2ee38118
commit 49d41747d3
22 changed files with 545 additions and 141 deletions

View File

@@ -20,7 +20,7 @@ if (is_readable($sysLibPath . '/oc_telegram_shop.phar')) {
class Controllerextensiontgshophandle extends Controller class Controllerextensiontgshophandle extends Controller
{ {
public function index() public function index(): void
{ {
$app = ApplicationFactory::create([ $app = ApplicationFactory::create([
'oc_config_tax' => $this->config->get('config_tax'), 'oc_config_tax' => $this->config->get('config_tax'),
@@ -79,4 +79,206 @@ class Controllerextensiontgshophandle extends Controller
$app->bootAndHandleRequest(); $app->bootAndHandleRequest();
} }
public function cart() {
$this->load->language('checkout/cart');
if ($this->cart->hasProducts()) {
if (!$this->cart->hasStock() && (!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning'))) {
$data['error_warning'] = $this->language->get('error_stock');
} elseif (isset($this->session->data['error'])) {
$data['error_warning'] = $this->session->data['error'];
unset($this->session->data['error']);
} else {
$data['error_warning'] = '';
}
if ($this->config->get('config_customer_price') && !$this->customer->isLogged()) {
$data['attention'] = sprintf($this->language->get('text_login'), $this->url->link('account/login'), $this->url->link('account/register'));
} else {
$data['attention'] = '';
}
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
if ($this->config->get('config_cart_weight')) {
$data['weight'] = $this->weight->format($this->cart->getWeight(), $this->config->get('config_weight_class_id'), $this->language->get('decimal_point'), $this->language->get('thousand_point'));
} else {
$data['weight'] = '';
}
$this->load->model('tool/image');
$this->load->model('tool/upload');
$data['products'] = array();
$products = $this->cart->getProducts();
foreach ($products as $product) {
$product_total = 0;
foreach ($products as $product_2) {
if ($product_2['product_id'] == $product['product_id']) {
$product_total += $product_2['quantity'];
}
}
if ($product['minimum'] > $product_total) {
$data['error_warning'] = sprintf($this->language->get('error_minimum'), $product['name'], $product['minimum']);
}
if ($product['image']) {
$image = $this->model_tool_image->resize($product['image'], $this->config->get('theme_' . $this->config->get('config_theme') . '_image_cart_width'), $this->config->get('theme_' . $this->config->get('config_theme') . '_image_cart_height'));
} else {
$image = '';
}
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['value'];
} else {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
} else {
$value = '';
}
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
);
}
// Display prices
if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
$unit_price = $this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'));
$price = $this->currency->format($unit_price, $this->session->data['currency']);
$total = $this->currency->format($unit_price * $product['quantity'], $this->session->data['currency']);
} else {
$price = false;
$total = false;
}
$recurring = '';
if ($product['recurring']) {
$frequencies = array(
'day' => $this->language->get('text_day'),
'week' => $this->language->get('text_week'),
'semi_month' => $this->language->get('text_semi_month'),
'month' => $this->language->get('text_month'),
'year' => $this->language->get('text_year')
);
if ($product['recurring']['trial']) {
$recurring = sprintf($this->language->get('text_trial_description'), $this->currency->format($this->tax->calculate($product['recurring']['trial_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']), $product['recurring']['trial_cycle'], $frequencies[$product['recurring']['trial_frequency']], $product['recurring']['trial_duration']) . ' ';
}
if ($product['recurring']['duration']) {
$recurring .= sprintf($this->language->get('text_payment_description'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
} else {
$recurring .= sprintf($this->language->get('text_payment_cancel'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
}
}
$data['products'][] = array(
'cart_id' => (int)$product['cart_id'],
'thumb' => $image,
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'recurring' => $recurring,
'quantity' => (int)$product['quantity'],
'stock' => $product['stock'] ? true : !(!$this->config->get('config_stock_checkout') || $this->config->get('config_stock_warning')),
'reward' => ($product['reward'] ? sprintf($this->language->get('text_points'), $product['reward']) : ''),
'price' => $price,
'total' => $total,
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id'])
);
}
// Totals
$this->load->model('setting/extension');
$totals = array();
$taxes = $this->cart->getTaxes();
$total = 0;
// Because __call can not keep var references so we put them into an array.
$total_data = array(
'totals' => &$totals,
'taxes' => &$taxes,
'total' => &$total
);
// Display prices
if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
$sort_order = array();
$results = $this->model_setting_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get('total_' . $value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get('total_' . $result['code'] . '_status')) {
$this->load->model('extension/total/' . $result['code']);
// We have to put the totals in an array so that they pass by reference.
$this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
}
}
$sort_order = array();
foreach ($totals as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $totals);
}
$data['totals'] = array();
foreach ($totals as $total) {
$data['totals'][] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $this->session->data['currency'])
);
}
$data['total_products_count'] = $this->cart->countProducts();
} else {
$data['text_error'] = $this->language->get('text_empty');
$data['totals'] = [];
$data['products'] = [];
$data['total_products_count'] = 0;
unset($this->session->data['success']);
}
http_response_code(200);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
echo json_encode($data);
die();
}
} }

View File

@@ -0,0 +1,8 @@
<?php
namespace Openguru\OpenCartFramework\Telegram;
class RequestValidator
{
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Openguru\OpenCartFramework\Telegram;
use Openguru\OpenCartFramework\Http\Request;
class ValidateInitDataMiddleware
{
public function handle(Request $request, callable $next): void
{
$next($request);
}
}

View File

@@ -19,17 +19,6 @@ class CartHandler
$this->imageTool = $imageTool; $this->imageTool = $imageTool;
} }
public function index(Request $request): JsonResponse
{
return new JsonResponse([
'data' => [
'products' => $this->getProducts(),
'count' => $this->cart->countProducts(),
'total' => $this->cart->getTotal(),
]
]);
}
public function checkout(Request $request): JsonResponse public function checkout(Request $request): JsonResponse
{ {
$items = $request->json(); $items = $request->json();

View File

@@ -10,6 +10,8 @@ use Openguru\OpenCartFramework\QueryBuilder\JoinClause;
class CategoriesHandler class CategoriesHandler
{ {
private const THUMB_SIZE = 150;
private Builder $queryBuilder; private Builder $queryBuilder;
private ImageToolInterface $ocImageTool; private ImageToolInterface $ocImageTool;
@@ -22,14 +24,11 @@ class CategoriesHandler
public function index(Request $request): JsonResponse public function index(Request $request): JsonResponse
{ {
$languageId = 1; $languageId = 1;
$perPage = $request->get('perPage', 10);
$imageWidth = 150; $categoriesFlat = $this->queryBuilder->newQuery()
$imageHeight = 150;
$categories = $this->queryBuilder->newQuery()
->select([ ->select([
'categories.category_id' => 'id', 'categories.category_id' => 'id',
'categories.parent_id' => 'parent_id',
'categories.image' => 'image', 'categories.image' => 'image',
'descriptions.name' => 'name', 'descriptions.name' => 'name',
'descriptions.description' => 'description', 'descriptions.description' => 'description',
@@ -42,23 +41,48 @@ class CategoriesHandler
->where('descriptions.language_id', '=', $languageId); ->where('descriptions.language_id', '=', $languageId);
} }
) )
->where('categories.parent_id', '=', 0)
->where('categories.status', '=', 1) ->where('categories.status', '=', 1)
->orderBy('parent_id')
->orderBy('sort_order') ->orderBy('sort_order')
->limit($perPage)
->get(); ->get();
return new JsonResponse([ $categories = $this->buildCategoryTree($categoriesFlat);
'data' => array_map(function ($category) use ($imageWidth, $imageHeight) {
$image = $this->ocImageTool->resize($category['image'], $imageWidth, $imageHeight, 'no_image.png');
return new JsonResponse([
'data' => array_map(static function ($category) {
return [ return [
'id' => (int)$category['id'], 'id' => (int)$category['id'],
'image' => $image, 'image' => $category['image'],
'name' => $category['name'], 'name' => $category['name'],
'description' => $category['description'], 'description' => $category['description'],
'children' => $category['children'],
]; ];
}, $categories), }, $categories),
]); ]);
} }
public function buildCategoryTree(array $flat, $parentId = 0): array {
$branch = [];
foreach ($flat as $category) {
if ((int)$category['parent_id'] === (int)$parentId) {
$children = $this->buildCategoryTree($flat, $category['id']);
if ($children) {
$category['children'] = $children;
}
$image = $this->ocImageTool->resize($category['image'], self::THUMB_SIZE, self::THUMB_SIZE, 'no_image.png');
$branch[] = [
'id' => (int)$category['id'],
'image' => $image,
'name' => $category['name'],
'description' => $category['description'],
'children' => $category['children'] ?? [],
];
}
}
return $branch;
}
} }

View File

@@ -44,7 +44,7 @@ class ProductsHandler
{ {
$languageId = 1; $languageId = 1;
$page = $request->get('page', 1); $page = $request->get('page', 1);
$perPage = 10; $perPage = 6;
$categoryId = (int) $request->get('categoryId', 0); $categoryId = (int) $request->get('categoryId', 0);
$categoryName = ''; $categoryName = '';
@@ -178,6 +178,8 @@ class ProductsHandler
'product_description.name' => 'product_name', 'product_description.name' => 'product_name',
'product_description.description' => 'product_description', 'product_description.description' => 'product_description',
'products.price' => 'price', 'products.price' => 'price',
'products.minimum' => 'minimum',
'products.quantity' => 'quantity',
'products.image' => 'product_image', 'products.image' => 'product_image',
'products.tax_class_id' => 'tax_class_id', 'products.tax_class_id' => 'tax_class_id',
'manufacturer.name' => 'product_manufacturer', 'manufacturer.name' => 'product_manufacturer',
@@ -247,6 +249,8 @@ class ProductsHandler
'description' => html_entity_decode($product['product_description']), 'description' => html_entity_decode($product['product_description']),
'manufacturer' => $product['product_manufacturer'], 'manufacturer' => $product['product_manufacturer'],
'price' => $price, 'price' => $price,
'minimum' => $product['minimum'],
'quantity' => $product['quantity'],
'images' => $images, 'images' => $images,
'options' => $this->loadProductOptions($product), 'options' => $this->loadProductOptions($product),
]; ];

View File

@@ -14,5 +14,4 @@ return [
'categoriesList' => [CategoriesHandler::class, 'index'], 'categoriesList' => [CategoriesHandler::class, 'index'],
'checkout' => [CartHandler::class, 'checkout'], 'checkout' => [CartHandler::class, 'checkout'],
'cart' => [CartHandler::class, 'index'],
]; ];

View File

@@ -1,13 +1,13 @@
<template> <template>
<div class="flex items-center justify-center p-5 gap-2 flex-wrap"> <div class="flex items-center justify-center p-5 gap-2 flex-wrap">
<RouterLink class="btn" to="/categories"> <RouterLink class="btn btn-sm" to="/categories">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-5">
<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z" /> <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z" />
</svg> </svg>
Каталог Каталог
</RouterLink> </RouterLink>
<RouterLink v-for="category in categoriesStore.topCategories" class="btn" :to="`/category/${category.id}`"> <RouterLink v-for="category in categoriesStore.topCategories" class="btn btn-sm" :to="{name: 'product.categories.show', params: {category_id: category.id}}">
{{ category.name }} {{ category.name }}
</RouterLink> </RouterLink>
</div> </div>

View File

@@ -0,0 +1,27 @@
<template>
<a
href="#"
:key="category.id"
class="py-2 px-4 flex items-center mb-3"
@click.prevent="$emit('onSelect', category)"
>
<div class="avatar">
<div class="w-8 h-8 rounded">
<img :src="category.image" :alt="category.name" loading="lazy" width="30" height="30" class="bg-base-400"/>
</div>
</div>
<h3 class="ml-5 text-lg">{{ category.name }}</h3>
</a>
</template>
<script setup>
const props = defineProps({
category: {
type: Object,
required: true,
}
});
const emit = defineEmits(["onSelect"]);
</script>

View File

@@ -1,16 +1,5 @@
<template> <template>
<div class="mx-auto max-w-2xl px-4 py-4 sm:px-6 sm:py-6 lg:max-w-7xl lg:px-8"> <div class="mx-auto max-w-2xl px-4 py-4 sm:px-6 sm:py-6 lg:max-w-7xl lg:px-8">
<div v-if="productsStore.isLoading"
class="grid grid-cols-2 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8">
<div v-for="n in 8" :key="n" class="animate-pulse space-y-2">
<div class="aspect-square bg-gray-200 rounded-md"></div>
<div class="h-4 bg-gray-200 rounded w-3/4"></div>
<div class="h-4 bg-gray-200 rounded w-1/2"></div>
</div>
</div>
<template v-else>
<h2 class="text-lg font-bold mb-5 text-center">{{ productsStore.products.meta.currentCategoryName }}</h2> <h2 class="text-lg font-bold mb-5 text-center">{{ productsStore.products.meta.currentCategoryName }}</h2>
<div v-if="productsStore.products.data.length > 0"> <div v-if="productsStore.products.data.length > 0">
@@ -30,6 +19,10 @@
</RouterLink> </RouterLink>
</div> </div>
<div v-if="productsStore.isLoading" class="text-center mt-5">
<span class="loading loading-spinner loading-md"></span> Загрузка...
</div>
<div <div
v-if="productsStore.hasMore === false" v-if="productsStore.hasMore === false"
class="text-gray-500 text-xs text-center mt-4 pt-4 mb-2 border-t" class="text-gray-500 text-xs text-center mt-4 pt-4 mb-2 border-t"
@@ -38,10 +31,16 @@
</div> </div>
</div> </div>
<NoProducts v-else/> <NoProducts v-else-if="productsStore.loadFinished"/>
<div v-else
</template> class="grid grid-cols-2 gap-x-6 gap-y-10 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8">
<div v-for="n in 8" :key="n" class="animate-pulse space-y-2">
<div class="aspect-square bg-gray-200 rounded-md"></div>
<div class="h-4 bg-gray-200 rounded w-3/4"></div>
<div class="h-4 bg-gray-200 rounded w-1/2"></div>
</div>
</div>
</div> </div>
</template> </template>
@@ -55,7 +54,7 @@ import {useSettingsStore} from "@/stores/SettingsStore.js";
import {nextTick, onMounted, ref, watch} from "vue"; import {nextTick, onMounted, ref, watch} from "vue";
const route = useRoute(); const route = useRoute();
const categoryId = route.params.id ?? null; const categoryId = route.params.category_id ?? null;
const productsStore = useProductsStore(); const productsStore = useProductsStore();
const settings = useSettingsStore(); const settings = useSettingsStore();
@@ -85,13 +84,14 @@ async function loadMore() {
console.error('Ошибка загрузки', e) console.error('Ошибка загрузки', e)
} finally { } finally {
productsStore.isLoading = false; productsStore.isLoading = false;
productsStore.loadFinished = true;
} }
} }
useInfiniteScroll( useInfiniteScroll(
window, window,
loadMore, loadMore,
{distance: 300} {distance: 500}
) )
watch(() => route.params.id, async newId => { watch(() => route.params.id, async newId => {
@@ -103,7 +103,6 @@ watch(() => route.params.id, async newId => {
}); });
onMounted(async () => { onMounted(async () => {
console.log("Mounted");
const saved = productsStore.savedCategoryId === categoryId; const saved = productsStore.savedCategoryId === categoryId;
console.log("Saved Category: ", saved); console.log("Saved Category: ", saved);

View File

@@ -17,6 +17,8 @@ app.mount('#app');
const settings = useSettingsStore(); const settings = useSettingsStore();
const categoriesStore = useCategoriesStore(); const categoriesStore = useCategoriesStore();
categoriesStore.fetchTopCategories(); categoriesStore.fetchTopCategories();
categoriesStore.fetchCategories();
import {useCategoriesStore} from "@/stores/CategoriesStore.js"; import {useCategoriesStore} from "@/stores/CategoriesStore.js";
import {useSettingsStore} from "@/stores/SettingsStore.js"; import {useSettingsStore} from "@/stores/SettingsStore.js";
@@ -30,4 +32,3 @@ if (settings.night_auto) {
} }
window.Telegram.WebApp.ready(); window.Telegram.WebApp.ready();

View File

@@ -4,23 +4,19 @@ import Product from './views/Product.vue';
import CategoriesList from "./views/CategoriesList.vue"; import CategoriesList from "./views/CategoriesList.vue";
import Cart from "./views/Cart.vue"; import Cart from "./views/Cart.vue";
import Products from "@/views/Products.vue"; import Products from "@/views/Products.vue";
import Checkout from "@/views/Checkout.vue";
const routes = [ const routes = [
{path: '/', name: 'home', component: Home}, {path: '/', name: 'home', component: Home},
{path: '/product/:id', name: 'product.show', component: Product}, {path: '/product/:id', name: 'product.show', component: Product},
{path: '/products/:category_id', name: 'product.categories.show', component: Products},
{path: '/categories', name: 'categories', component: CategoriesList}, {path: '/categories', name: 'categories', component: CategoriesList},
{path: '/category/:id', name: 'category.show', component: Products}, {path: '/category/:id', name: 'category.show', component: CategoriesList},
{path: '/cart', name: 'cart.show', component: Cart}, {path: '/cart', name: 'cart.show', component: Cart},
{path: '/checkout', name: 'checkout', component: Checkout},
]; ];
export const router = createRouter({ export const router = createRouter({
history: createMemoryHistory('/image/catalog/tgshopspa/'), history: createMemoryHistory('/image/catalog/tgshopspa/'),
routes, routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition; // Восстановить позицию прокрутки
} else {
return {top: 0}; // Или оставить на старте
}
}
}); });

View File

@@ -1,25 +1,38 @@
import {defineStore} from "pinia"; import {defineStore} from "pinia";
import ftch from "@/utils/ftch.js";
import {$fetch} from "ofetch";
import {isNotEmpty} from "@/helpers.js"; import {isNotEmpty} from "@/helpers.js";
import {apiFetch} from "@/utils/ftch.js";
export const useCartStore = defineStore('cart', { export const useCartStore = defineStore('cart', {
state: () => ({ state: () => ({
items: [], items: [],
products: [],
productsCount: 0, productsCount: 0,
total: 0, total: 0,
isLoading: false, isLoading: false,
reason: null,
error_warning: '',
attention: '',
success: '',
}), }),
getters: {
canCheckout: (state) => {
if (state.isLoading) {
return false;
}
},
},
actions: { actions: {
async getProducts() { async getProducts() {
try { try {
this.isLoading = true; this.isLoading = true;
const {data} = await ftch('cart'); const data = await apiFetch('/index.php?route=extension/tgshop/handle/cart');
this.products = data.products; this.items = data.products;
this.productsCount = data.count; this.productsCount = data.total_products_count;
this.total = data.total; this.totals = data.totals;
this.error_warning = data.error_warning;
this.attention = data.attention;
this.success = data.success;
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} finally { } finally {
@@ -49,7 +62,7 @@ export const useCartStore = defineStore('cart', {
} }
}) })
const response = await $fetch('/index.php?route=checkout/cart/add', { const response = await apiFetch('/index.php?route=checkout/cart/add', {
method: 'POST', method: 'POST',
body: formData, body: formData,
}); });
@@ -72,7 +85,7 @@ export const useCartStore = defineStore('cart', {
this.isLoading = true; this.isLoading = true;
const formData = new FormData(); const formData = new FormData();
formData.append('key', rowId); formData.append('key', rowId);
await $fetch('/index.php?route=checkout/cart/remove', { await apiFetch('/index.php?route=checkout/cart/remove', {
method: 'POST', method: 'POST',
body: formData, body: formData,
}); });
@@ -89,7 +102,7 @@ export const useCartStore = defineStore('cart', {
this.isLoading = true; this.isLoading = true;
const formData = new FormData(); const formData = new FormData();
formData.append(`quantity[${cartId}]`, quantity); formData.append(`quantity[${cartId}]`, quantity);
await $fetch('/index.php?route=checkout/cart/edit', { await apiFetch('/index.php?route=checkout/cart/edit', {
redirect: 'manual', redirect: 'manual',
method: 'POST', method: 'POST',
body: formData, body: formData,

View File

@@ -4,10 +4,25 @@ import ftch from "../utils/ftch.js";
export const useCategoriesStore = defineStore('categories', { export const useCategoriesStore = defineStore('categories', {
state: () => ({ state: () => ({
topCategories: [], topCategories: [],
categories: [],
isLoading: false, isLoading: false,
}), }),
actions: { actions: {
async fetchCategories() {
if (this.isLoading === false && this.categories.length === 0) {
try {
this.isLoading = true;
const {data} = await ftch('categoriesList');
this.categories = data;
} catch (error) {
console.error(error);
} finally {
this.isLoading = false;
}
}
},
async fetchTopCategories() { async fetchTopCategories() {
try { try {
this.isLoading = true; this.isLoading = true;

View File

@@ -9,6 +9,7 @@ export const useProductsStore = defineStore('products', {
}, },
page: 1, page: 1,
isLoading: false, isLoading: false,
loadFinished: false,
hasMore: true, hasMore: true,
savedCategoryId: null, savedCategoryId: null,
savedScrollY: 0, savedScrollY: 0,
@@ -32,6 +33,7 @@ export const useProductsStore = defineStore('products', {
reset() { reset() {
this.page = 1; this.page = 1;
this.hasMore = true; this.hasMore = true;
this.loadFinished = false;
this.products = { this.products = {
data: [], data: [],
meta: {}, meta: {},

View File

@@ -3,10 +3,7 @@
themes: all; themes: all;
} }
html, body {
overscroll-behavior-y: none;
-webkit-overflow-scrolling: auto;
}
#app { #app {
padding-top: var(--tg-content-safe-area-inset-top); padding-top: var(--tg-content-safe-area-inset-top);

View File

@@ -1,11 +1,26 @@
import {$fetch} from "ofetch"; import {ofetch} from "ofetch";
const BASE_URL = '/'; const BASE_URL = '/';
export default async function (action, query = null, json = null) { export const apiFetch = ofetch.create({
return await $fetch(`${BASE_URL}index.php?route=extension/tgshop/handle&api_action=${action}`, { onRequest({ request, options }) {
method: json ? 'POST' : 'GET', const initData = window.Telegram?.WebApp?.initData
query: query,
body: json, if (initData) {
options.headers = {
...options.headers,
'X-Telegram-InitData': initData,
}
}
},
}); });
export default async function (action, query = null, json = null) {
const options = {
method: json ? 'POST' : 'GET',
}
if (query) options.query = query;
if (json) options.body = json;
return await apiFetch(`${BASE_URL}index.php?route=extension/tgshop/handle&api_action=${action}`, options);
}; };

View File

@@ -5,9 +5,23 @@
<span v-if="cart.isLoading" class="loading loading-spinner loading-md"></span> <span v-if="cart.isLoading" class="loading loading-spinner loading-md"></span>
</h2> </h2>
<div v-if="cart.products.length > 0"> <div v-if="cart.attention" role="alert" class="alert alert-warning">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0 stroke-current" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<span>{{ cart.attention }}</span>
</div>
<div v-if="cart.error_warning" role="alert" class="alert alert-error">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0 stroke-current" fill="none" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>{{ cart.error_warning }}</span>
</div>
<div v-if="cart.items.length > 0">
<div <div
v-for="item in cart.products" v-for="item in cart.items"
:key="item.cart_id" :key="item.cart_id"
class="card card-border bg-base-100 card-sm mb-3" class="card card-border bg-base-100 card-sm mb-3"
:class="item.stock === false ? 'border-error' : ''" :class="item.stock === false ? 'border-error' : ''"
@@ -19,21 +33,20 @@
</div> </div>
</div> </div>
<p v-if="! item.stock" class="text-error font-bold">Товар отсутствует на складе в нужном количестве.</p> <h2 class="card-title">{{ item.name }} <span v-if="! item.stock" class="text-error font-bold">***</span></h2>
<p class="text-sm font-bold">{{ item.total }}</p>
<h2 class="card-title">{{ item.name }}</h2> <p>{{ item.price }}/ед</p>
<p class="text-sm font-bold">{{ formatPrice(item.total) }} </p>
<p>{{ formatPrice(item.price) }} /ед</p>
<div> <div>
<div v-for="option in item.option"> <div v-for="option in item.option">
<component <p><span class="font-bold">{{ option.name }}</span>: {{ option.value }}</p>
v-if="SUPPORTED_OPTION_TYPES.includes(option.type) && componentMap[option.type]" <!-- <component-->
:is="componentMap[option.type]" <!-- v-if="SUPPORTED_OPTION_TYPES.includes(option.type) && componentMap[option.type]"-->
:option="option" <!-- :is="componentMap[option.type]"-->
/> <!-- :option="option"-->
<div v-else class="text-sm text-error"> <!-- />-->
Тип опции "{{ option.type }}" не поддерживается. <!-- <div v-else class="text-sm text-error">-->
</div> <!-- Тип опции "{{ option.type }}" не поддерживается.-->
<!-- </div>-->
</div> </div>
</div> </div>
<div class="card-actions justify-between"> <div class="card-actions justify-between">
@@ -51,14 +64,29 @@
</div> </div>
</div> </div>
<div class="card card-border bg-base-100">
<div class="card-body">
<h2 class="card-title">Ваша корзина</h2>
<div v-for="total in cart.totals">
<div class="flex justify-between">
<span class="text-xs text-base-content mr-2">{{ total.title }}:</span>
<span v-if="cart.isLoading" class="loading loading-spinner loading-xs"></span>
<span v-else class="text-xs font-bold">{{ total.text }}</span>
</div>
</div>
</div>
</div>
<div class="fixed px-4 pb-10 pt-4 bottom-0 left-0 w-full bg-base-200 z-50 flex justify-between items-center gap-2 border-t-1 border-t-base-300"> <div class="fixed px-4 pb-10 pt-4 bottom-0 left-0 w-full bg-base-200 z-50 flex justify-between items-center gap-2 border-t-1 border-t-base-300">
<div> <div>
<div v-if="lastTotal">
<span class="text-xs text-base-content mr-2">Всего:</span> <span class="text-xs text-base-content mr-2">{{ lastTotal.title }}:</span><br>
<span v-if="cart.isLoading" class="loading loading-spinner loading-xs"></span> <span v-if="cart.isLoading" class="loading loading-spinner loading-xs"></span>
<span v-else class="text-accent font-bold">{{ formatPrice(cart.total) }} </span> <span v-else class="text-accent font-bold">{{ lastTotal.text }}</span>
</div> </div>
<button class="btn btn-primary" :disabled="cart.isLoading">Перейти к оформлению</button> </div>
<button class="btn btn-primary" :disabled="cart.canCheckout === false">Перейти к оформлению</button>
</div> </div>
</div> </div>
@@ -66,7 +94,8 @@
v-else v-else
class="text-center rounded-2xl" class="text-center rounded-2xl"
> >
<p class="text-lg">Ваша корзина пуста</p> <p class="text-lg mb-3">Ваша корзина пуста</p>
<RouterLink class="btn btn-primary" to="/">Начать покупки.</RouterLink>
</div> </div>
</div> </div>
</template> </template>
@@ -74,21 +103,25 @@
<script setup> <script setup>
import { useCartStore } from '../stores/CartStore.js' import { useCartStore } from '../stores/CartStore.js'
import Quantity from "@/components/Quantity.vue"; import Quantity from "@/components/Quantity.vue";
import {SUPPORTED_OPTION_TYPES} from "@/constants/options.js"; // import {SUPPORTED_OPTION_TYPES} from "@/constants/options.js";
import OptionRadio from "@/components/ProductOptions/Cart/OptionRadio.vue"; import OptionRadio from "@/components/ProductOptions/Cart/OptionRadio.vue";
import OptionCheckbox from "@/components/ProductOptions/Cart/OptionCheckbox.vue"; import OptionCheckbox from "@/components/ProductOptions/Cart/OptionCheckbox.vue";
import OptionText from "@/components/ProductOptions/Cart/OptionText.vue"; import OptionText from "@/components/ProductOptions/Cart/OptionText.vue";
import {formatPrice} from "../helpers.js"; import {computed} from "vue";
const cart = useCartStore(); const cart = useCartStore();
const componentMap = { // const componentMap = {
radio: OptionRadio, // radio: OptionRadio,
select: OptionRadio, // select: OptionRadio,
checkbox: OptionCheckbox, // checkbox: OptionCheckbox,
text: OptionText, // text: OptionText,
textarea: OptionText, // textarea: OptionText,
}; // };
const lastTotal = computed(() => {
return cart.totals.at(-1) ?? null;
});
function removeItem(cartId) { function removeItem(cartId) {
cart.removeItem(cartId); cart.removeItem(cartId);

View File

@@ -2,29 +2,81 @@
<div class="mx-auto max-w-2xl px-4 py-4 sm:px-6 sm:py-24 lg:max-w-7xl lg:px-8 mb-5"> <div class="mx-auto max-w-2xl px-4 py-4 sm:px-6 sm:py-24 lg:max-w-7xl lg:px-8 mb-5">
<h2 class="text-3xl mb-5">Категории</h2> <h2 class="text-3xl mb-5">Категории</h2>
<div class="grid grid-cols-2 gap-x-6 gap-y-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 xl:gap-x-8"> <button v-if="parentId" class="py-2 px-4 flex items-center mb-3 cursor-pointer" @click="goBack">
<RouterLink <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
v-for="category in categories" <path stroke-linecap="round" stroke-linejoin="round" d="M10.5 19.5 3 12m0 0 7.5-7.5M3 12h18" />
:key="category.id" </svg>
:to="`/category/${category.id}`"
class="group border border-gray-200 rounded-lg py-2 px-4 flex flex-col justify-center items-center" <span class="ml-2">Назад к "{{ parentCategory.name }}"</span>
</button>
<button
v-if="parentId"
class="py-2 px-4 flex items-center mb-3 cursor-pointer"
@click.prevent="showProductsInParentCategory"
> >
<img :src="category.image" :alt="category.name" loading="lazy"/> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">
<h3 class="mt-4 text-lg">{{ category.name }}</h3> <path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 0 1 6 3.75h2.25A2.25 2.25 0 0 1 10.5 6v2.25a2.25 2.25 0 0 1-2.25 2.25H6a2.25 2.25 0 0 1-2.25-2.25V6ZM3.75 15.75A2.25 2.25 0 0 1 6 13.5h2.25a2.25 2.25 0 0 1 2.25 2.25V18a2.25 2.25 0 0 1-2.25 2.25H6A2.25 2.25 0 0 1 3.75 18v-2.25ZM13.5 6a2.25 2.25 0 0 1 2.25-2.25H18A2.25 2.25 0 0 1 20.25 6v2.25A2.25 2.25 0 0 1 18 10.5h-2.25a2.25 2.25 0 0 1-2.25-2.25V6ZM13.5 15.75a2.25 2.25 0 0 1 2.25-2.25H18a2.25 2.25 0 0 1 2.25 2.25V18A2.25 2.25 0 0 1 18 20.25h-2.25A2.25 2.25 0 0 1 13.5 18v-2.25Z" />
</RouterLink> </svg>
<span class="ml-2">Показать все товары</span>
</button>
<div v-for="category in categories" :key="category.id">
<CategoryItem
:category="category"
@onSelect="onSelect"
/>
</div> </div>
</div> </div>
</template> </template>
<script setup> <script setup>
import {onMounted, ref} from "vue"; import {computed, onMounted} from "vue";
import ftch from "../utils/ftch.js"; import {router} from "@/router.js";
import {useCategoriesStore} from "@/stores/CategoriesStore.js";
import {useRoute} from "vue-router";
import CategoryItem from "@/components/CategoriesList/CategoryItem.vue";
const categories = ref([]); const route = useRoute();
const parentId = computed(() => route.params.id ? Number(route.params.id) : null);
const parentCategory = computed(() => findCategoryById(parentId.value));
const categoriesStore = useCategoriesStore();
function findCategoryById(id) {
for (const category of categoriesStore.categories) {
if (category.id === id) {
return category;
}
}
return []
}
const categories = computed(() => {
if (! parentId.value) {
return categoriesStore.categories;
}
return findCategoryById(parentId.value).children;
});
function onSelect(category) {
if (category.children.length === 0) {
router.push({ name: "product.categories.show", params: { category_id: category.id } });
} else {
router.push({ name: "category.show", params: { id: category.id } });
}
}
function goBack() {
router.back();
}
function showProductsInParentCategory() {
router.push({ name: "product.categories.show", params: { category_id: parentId.value } });
}
onMounted(async () => { onMounted(async () => {
const {data} = await ftch('categoriesList'); categoriesStore.fetchCategories();
console.log(data);
categories.value = data;
}); });
</script> </script>

View File

@@ -0,0 +1,13 @@
<template>
<div class="max-w-3xl mx-auto p-4 space-y-6 pb-30">
<h2 class="text-2xl">
Корзина
<span class="loading loading-spinner loading-md"></span>
</h2>
</div>
</template>
<script setup>
</script>

View File

@@ -15,6 +15,8 @@
<div class="mt-4 lg:row-span-3 lg:mt-0"> <div class="mt-4 lg:row-span-3 lg:mt-0">
<p class="text-3xl tracking-tight">{{ product.price }}</p> <p class="text-3xl tracking-tight">{{ product.price }}</p>
<p v-if="false" class="text-xs">Кол-во на складе: {{ product.quantity }} шт.</p>
<p v-if="product.minimum && product.minimum > 1">Минимальное кол-ва для заказа: {{ product.minimum }}</p>
</div> </div>
<div v-if="product.options && product.options.length" class="mt-4"> <div v-if="product.options && product.options.length" class="mt-4">
@@ -67,13 +69,13 @@
<script setup> <script setup>
import {computed, onMounted, ref} from "vue"; import {computed, onMounted, ref} from "vue";
import {$fetch} from "ofetch";
import {useRoute} from 'vue-router' import {useRoute} from 'vue-router'
import ProductOptions from "../components/ProductOptions/ProductOptions.vue"; import ProductOptions from "../components/ProductOptions/ProductOptions.vue";
import {useCartStore} from "../stores/CartStore.js"; import {useCartStore} from "../stores/CartStore.js";
import ProductImageSwiper from "../components/ProductImageSwiper.vue"; import ProductImageSwiper from "../components/ProductImageSwiper.vue";
import Quantity from "../components/Quantity.vue"; import Quantity from "../components/Quantity.vue";
import {SUPPORTED_OPTION_TYPES} from "@/constants/options.js"; import {SUPPORTED_OPTION_TYPES} from "@/constants/options.js";
import {apiFetch} from "@/utils/ftch.js";
const route = useRoute(); const route = useRoute();
const productId = computed(() => route.params.id); const productId = computed(() => route.params.id);
@@ -117,7 +119,7 @@ function setQuantity(newQuantity) {
} }
onMounted(async () => { onMounted(async () => {
const {data} = await $fetch(`/index.php?route=extension/tgshop/handle&api_action=product_show&id=${productId.value}`); const {data} = await apiFetch(`/index.php?route=extension/tgshop/handle&api_action=product_show&id=${productId.value}`);
product.value = data; product.value = data;
}); });
</script> </script>