Files
hedena_gold/apps/admin-panel/src/views/branch/order/create.vue
T

253 lines
8.4 KiB
Vue

<template>
<!--
Ported from legacy henza_admin/src/views/branch/order/create.vue — the
branch-mode order builder.
It differs from the admin builder (views/order/create.vue) in flow, not in
substance: the CUSTOMER is picked first and the product grid stays hidden
until one is chosen ("جهت ثبت سفارش مشتری را انتخاب نمایید"). Preserved.
It also drops the admin version's `$hasPermission('order.create')` wrapper —
branch mode gates the whole route instead. Preserved.
-->
<a-spin :spinning="loading">
<a-card title="ثبت سفارش">
<span>جهت ثبت سفارش مشتری را انتخاب نمایید</span>
<a-form layout="vertical" class="mt-4" @submit.prevent="submitOrder">
<a-form-item
label="مشتری"
class="customer-field"
:validate-status="err.customer_id ? 'error' : ''"
:help="err.customer_id"
>
<a-select
v-model:value="form.customer_id"
show-search
option-filter-prop="children"
:filter-option="filterOption"
>
<a-select-option v-for="item in customers" :key="item.id" :value="item.id">
{{ `${item.id}-${item.fname} ${item.lname}` }}
</a-select-option>
</a-select>
</a-form-item>
<!-- legacy: the grid appears only once a customer is chosen -->
<div v-if="form.customer_id != null">
<h6>تعداد {{ items.length }} محصول انتخاب شده است.</h6>
<XTable ref="tblProducts" :model="cols">
<template #image="{ record }">
<img
width="90px"
height="90px"
style="object-fit: scale-down"
:src="record.thumb && record.thumb.full ? record.thumb.full : noImage"
/>
</template>
<template #op="{ record }">
<a-dropdown>
<a-button style="margin-left: 8px">
افزودن
<DownOutlined />
</a-button>
<template #overlay>
<a-menu @click="onVariantPick(record, $event)">
<a-menu-item v-for="item in record.variants_all" :key="item.id">
افزودن تنوع {{ item.title }}
</a-menu-item>
</a-menu>
</template>
</a-dropdown>
</template>
</XTable>
<a-card v-if="items.length > 0" title="سبد سفارش" class="mt-4">
<a-table
:columns="columns"
:data-source="items"
bordered
:pagination="false"
row-key="vid"
>
<template #bodyCell="{ column, record, index }">
<template v-if="column.dataIndex === 'delete'">
<CloseOutlined class="cursor-pointer" @click="cart.remove(record)" />
</template>
<template v-else-if="column.dataIndex === 'product'">
<div class="flex items-center">
<img :src="getImage(record.product)" width="50px" />
{{ record.product.title }}
</div>
</template>
<template v-else-if="column.dataIndex === 'qty'">
<a-input-number
v-model:value="items[index].qty"
:min="1"
:max="maxQtyFor(index)"
@change="onQtyChange(index, $event)"
/>
</template>
<template v-else-if="column.dataIndex === 'weight'">
{{ getVariant(record).grams }}
</template>
<template v-else-if="column.dataIndex === 'total'">
{{ rowWeight(record) }} گرم
</template>
</template>
</a-table>
<div class="totals">
<a-tag color="blue">مجموع وزن: {{ totalWeight }} گرم</a-tag>
</div>
<a-form-item label="توضیحات">
<a-textarea v-model:value="form.note" :auto-size="{ minRows: 2, maxRows: 4 }" />
</a-form-item>
<a-button type="primary" :disabled="items.length < 1" @click="submitOrder">
ثبت سفارش
</a-button>
</a-card>
</div>
</a-form>
</a-card>
</a-spin>
</template>
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { CloseOutlined, DownOutlined } from '@ant-design/icons-vue';
import XTable from '../../../components/x-table/XTable.vue';
import { buildProductListModel } from '../../apps/product/productListModel';
import { useCartStore, type CartItem, type CartVariant } from '../../../stores/cart';
import api from '../../../api/client';
const router = useRouter();
const cart = useCartStore();
const noImage = '/img/no-items.png';
const cols = buildProductListModel();
const tblProducts = ref<{ fetch: () => Promise<void> } | null>(null);
const loading = ref(false);
const customers = ref<{ id: string; fname: string; lname: string }[]>([]);
const form = reactive<Record<string, any>>({ customer_id: undefined, note: '' });
const err = reactive<Record<string, string>>({});
const items = computed(() => cart.items);
const columns = [
{ title: 'حذف', dataIndex: 'delete', width: 60, align: 'center' },
{ title: 'محصول', dataIndex: 'product' },
{ title: 'تعداد', dataIndex: 'qty', align: 'center', width: 140 },
{ title: 'وزن', dataIndex: 'weight', align: 'center', width: 90 },
{ title: 'مجموع', dataIndex: 'total', align: 'center' },
];
function getVariant(item: CartItem): CartVariant & Record<string, any> {
return (item.product.variants_all.find((x) => x.id === item.vid) ?? {}) as CartVariant;
}
function getImage(product: Record<string, any>) {
return product?.thumb?.full ?? product?.ProductImage?.[0]?.image ?? noImage;
}
/** Same as the admin builder: 0 stock means uncapped, which keeps pre-orders orderable. */
function maxQtyFor(index: number): number {
const item = items.value[index];
if (!item) return Infinity;
const stock = Number(getVariant(item).qty ?? 0);
return stock > 0 ? stock : Infinity;
}
function onQtyChange(index: number, value: unknown) {
cart.updateItemQuantity({ index, quantity: Number(value) });
}
function onVariantPick(record: Record<string, any>, e: { key: string | number }) {
cart.add({
vid: String(e.key),
pid: record.id,
product: record as any,
qty: 1,
promotion_id: record.promotion && record.promotion.id ? record.promotion.id : null,
});
message.info('اضافه شد');
}
function rowWeight(record: CartItem) {
return Number(getVariant(record).grams ?? 0) * record.qty;
}
/** legacy sums the gram figures WITHOUT multiplying by qty — preserved. */
const totalWeight = computed(() => {
let total = 0;
for (const item of items.value) total += Number(getVariant(item).grams ?? 0);
return total;
});
function filterOption(input: string, option: any) {
return String(option?.children?.[0]?.children ?? '')
.toLowerCase()
.includes(input.toLowerCase());
}
async function submitOrder() {
Object.keys(err).forEach((k) => delete err[k]);
if (!form.customer_id) {
err.customer_id = 'مقدار را وارد نمایید';
return;
}
try {
loading.value = true;
const order_items = items.value.map((x) => {
const v = getVariant(x);
return { vid: x.vid, qty: x.qty, percent: v.percentage_pay };
});
await api.post('order', {
customer_id: form.customer_id,
note: form.note,
sts: 1,
order_items,
});
message.info('عملیات با موفقیت انجام شد');
cart.clear();
router.push('/order/list');
} catch (e: any) {
console.log(e);
message.error(e?.response?.data?.message ?? 'خطا در ثبت اطلاعات.');
} finally {
loading.value = false;
}
}
onMounted(async () => {
try {
const { data } = await api.post('single-customer', { page: 1, limit: 500 });
customers.value = data.rows ?? [];
} catch (e) {
console.log(e);
}
await cart.init();
});
</script>
<style scoped>
.customer-field {
max-width: 320px;
}
.mt-4 {
margin-top: 1rem;
}
.totals {
margin: 1rem 0;
}
</style>