ADD: Warehouse inventory management dashboard

- Add WarehouseItemService.js — API client for all warehouse item endpoints (items CRUD, transactions, stock queries)
- Add WarehouseService.js — API client for warehouse location management
- Add ListWarehouseItems.vue — item catalogue table with inline create/edit dialog and bilingual unit picker
- Add WarehouseItemStockView.vue — per-item stock dashboard showing total + per-warehouse breakdown, IN/OUT transaction dialog with reason presets, inline transaction history with delete
- Add ListWarehouseItemTransactions.vue — full transaction history with filter panel (item, warehouse, type, date range)
- Add ListWarehouses.vue — warehouse location management with create/edit dialogs
- Update AppMenu.vue — add 'مدیریت انبار' menu group with 3 items
- Update router/index.js — register 4 new warehouse management routes
This commit is contained in:
2026-08-11 20:09:31 +03:30
parent 7421896805
commit 703df418ce
8 changed files with 2033 additions and 8 deletions
+12 -5
View File
@@ -9,19 +9,26 @@ const model = ref([
items: [{ label: 'داشبورد', icon: 'pi pi-fw pi-home', to: '/' }]
},
{
label: 'مدیریت اموال',
label: 'مدیریت املاک',
items: [
{ label: 'ایجاد اموال', icon: 'pi pi-fw pi-file-plus', to: '/belonging/create-belonging' },
{ label: 'لیست اموال', icon: 'pi pi-fw pi-file', to: '/belonging/list-belongings' },
{ label: 'لیست تراکنش اموال', icon: 'pi pi-list-check', to: '/transactions/list-transactions' }
{ label: 'ایجاد ملک', icon: 'pi pi-fw pi-file-plus', to: '/property/create-property' },
{ label: 'لیست املاک', icon: 'pi pi-fw pi-file', to: '/property/list-properties' }
]
},
{
label: 'دسته بندی اموال',
label: 'دسته بندی املاک',
items: [
{ label: 'لیست دسته بندی ها', icon: 'pi pi-fw pi-th-large', to: '/categories/list-categories' },
{ label: 'ویژگی دسته بندی ها', icon: 'pi pi-fw pi-sitemap', to: '/features/list-features' }
]
},
{
label: 'مدیریت انبار',
items: [
{ label: 'اقلام انبار', icon: 'pi pi-fw pi-box', to: '/warehouse-items/list' },
{ label: 'تراکنش‌های انبار', icon: 'pi pi-fw pi-history', to: '/warehouse-items/transactions' },
{ label: 'مکان‌های انبار', icon: 'pi pi-fw pi-map', to: '/warehouse-items/warehouses' }
]
}
]);
</script>
+45 -3
View File
@@ -38,20 +38,41 @@ const router = createRouter({
name: 'dashboard',
component: () => import('@/views/Dashboard.vue')
},
{
path: '/property/create-property',
name: 'create-property',
component: () => import('@/views/pages/Property/CreateProperty.vue')
},
{
path: '/property/edit-property/:propertyId',
name: 'edit-property',
component: () => import('@/views/pages/Property/CreateProperty.vue')
},
{
path: '/property/list-properties',
name: 'list-properties',
component: () => import('@/views/pages/Property/CreateProperty.vue')
},
// Aliases for backward compatibility
{
path: '/belonging/create-belonging',
name: 'create-belonging',
component: () => import('@/views/pages/Belonging/CreateBelonging.vue')
component: () => import('@/views/pages/Property/CreateProperty.vue')
},
{
path: '/belonging/edit-belonging/:belongingId',
name: 'edit-belonging',
component: () => import('@/views/pages/Belonging/CreateBelonging.vue')
component: () => import('@/views/pages/Property/CreateProperty.vue')
},
{
path: '/belonging/list-belongings',
name: 'list-belongings',
component: () => import('@/views/pages/Belonging/ListBelongings.vue')
component: () => import('@/views/pages/Property/ListProperties.vue')
},
{
path: '/property/list-properties',
name: 'list-properties-main',
component: () => import('@/views/pages/Property/ListProperties.vue')
},
{
path: '/categories/list-categories',
@@ -68,6 +89,27 @@ const router = createRouter({
name: 'list-transactions',
component: () => import('@/views/pages/Transaction/ListTransactions.vue')
},
// ─── Warehouse Items ──────────────────────────────────────────
{
path: '/warehouse-items/list',
name: 'list-warehouse-items',
component: () => import('@/views/pages/WarehouseItems/ListWarehouseItems.vue')
},
{
path: '/warehouse-items/stock/:itemId',
name: 'warehouse-item-stock',
component: () => import('@/views/pages/WarehouseItems/WarehouseItemStockView.vue')
},
{
path: '/warehouse-items/transactions',
name: 'warehouse-item-transactions',
component: () => import('@/views/pages/WarehouseItems/ListWarehouseItemTransactions.vue')
},
{
path: '/warehouse-items/warehouses',
name: 'list-warehouses',
component: () => import('@/views/pages/WarehouseItems/ListWarehouses.vue')
},
{
path: '/uikit/formlayout',
name: 'formlayout',
+102
View File
@@ -0,0 +1,102 @@
import axios from 'axios';
const getAuthHeader = () => {
const bmToken = document.cookie
.split('; ')
.find((row) => row.startsWith('bm-token='))
?.split('=')[1];
return { Authorization: `Bearer ${bmToken}` };
};
export const WarehouseItemService = {
// ─── Items ────────────────────────────────────────────────────────────────
listItems: async (params = {}) => {
const response = await axios.get('/api/warehouse-items/admin/items', {
params,
withCredentials: true,
headers: getAuthHeader()
});
return response.data;
},
createItem: async (data) => {
const response = await axios.post('/api/warehouse-items/admin/items', data, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
getItem: async (itemId) => {
const response = await axios.get(`/api/warehouse-items/admin/items/${itemId}`, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
updateItem: async (itemId, data) => {
const response = await axios.patch(`/api/warehouse-items/admin/items/${itemId}`, data, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
deleteItem: async (itemId) => {
await axios.delete(`/api/warehouse-items/admin/items/${itemId}`, {
withCredentials: true,
headers: getAuthHeader()
});
},
// ─── Transactions ─────────────────────────────────────────────────────────
listTransactions: async (params = {}) => {
const response = await axios.get('/api/warehouse-items/admin/transactions', {
params,
withCredentials: true,
headers: getAuthHeader()
});
return response.data;
},
createTransaction: async (data) => {
const response = await axios.post('/api/warehouse-items/admin/transactions', data, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
deleteTransaction: async (transactionId) => {
await axios.delete(`/api/warehouse-items/admin/transactions/${transactionId}`, {
withCredentials: true,
headers: getAuthHeader()
});
},
// ─── Stock ────────────────────────────────────────────────────────────────
getTotalStock: async () => {
const response = await axios.get('/api/warehouse-items/admin/stock/total', {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
getStockByItem: async (itemId) => {
const response = await axios.get(`/api/warehouse-items/admin/stock/by-item/${itemId}`, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
getStockByWarehouse: async (warehouseId) => {
const response = await axios.get(`/api/warehouse-items/admin/stock/by-warehouse/${warehouseId}`, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
}
};
+51
View File
@@ -0,0 +1,51 @@
import axios from 'axios';
const getAuthHeader = () => {
const bmToken = document.cookie
.split('; ')
.find((row) => row.startsWith('bm-token='))
?.split('=')[1];
return { Authorization: `Bearer ${bmToken}` };
};
export const WarehouseService = {
listWarehouses: async (params = {}) => {
const response = await axios.get('/api/warehouses/admin/get-all', {
params,
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
createWarehouse: async (data) => {
const response = await axios.post('/api/warehouses/admin/create', data, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
getWarehouse: async (warehouseId) => {
const response = await axios.get(`/api/warehouses/admin/get-one/${warehouseId}`, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
updateWarehouse: async (warehouseId, data) => {
const response = await axios.patch(`/api/warehouses/admin/update/${warehouseId}`, data, {
withCredentials: true,
headers: getAuthHeader()
});
return response.data.data;
},
deleteWarehouse: async (warehouseId) => {
await axios.delete(`/api/warehouses/admin/delete/${warehouseId}`, {
withCredentials: true,
headers: getAuthHeader()
});
}
};
@@ -0,0 +1,353 @@
<script setup>
import { onMounted, ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import { WarehouseItemService } from '@/service/WarehouseItemService';
import { WarehouseService } from '@/service/WarehouseService';
const router = useRouter();
const route = useRoute();
const toast = useToast();
const transactions = ref([]);
const totalCount = ref(0);
const loading = ref(false);
const page = ref(1);
const perPage = ref(30);
// Filters
const filters = ref({
itemId: '',
warehouseId: '',
type: '',
dateFrom: '',
dateTo: '',
});
const items = ref([]);
const warehouses = ref([]);
const typeOptions = [
{ label: 'ورود', value: 'IN' },
{ label: 'خروج', value: 'OUT' },
];
onMounted(async () => {
await Promise.all([loadLookups(), loadData()]);
});
const loadLookups = async () => {
try {
const [wi, wh] = await Promise.all([
WarehouseItemService.listItems({ limit: 200 }),
WarehouseService.listWarehouses(),
]);
items.value = wi.items || [];
warehouses.value = wh;
} catch (e) {
console.error(e);
}
};
const loadData = async () => {
loading.value = true;
try {
const params = {
page: page.value,
limit: perPage.value,
};
if (filters.value.itemId) params.itemId = filters.value.itemId;
if (filters.value.warehouseId) params.warehouseId = filters.value.warehouseId;
if (filters.value.type) params.type = filters.value.type;
if (filters.value.dateFrom) params.dateFrom = filters.value.dateFrom;
if (filters.value.dateTo) params.dateTo = filters.value.dateTo;
const result = await WarehouseItemService.listTransactions(params);
transactions.value = result.transactions || [];
totalCount.value = result.total || 0;
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: 'خطا در بارگذاری تراکنش‌ها', life: 3000 });
} finally {
loading.value = false;
}
};
const applyFilters = () => {
page.value = 1;
loadData();
};
const clearFilters = () => {
filters.value = { itemId: '', warehouseId: '', type: '', dateFrom: '', dateTo: '' };
page.value = 1;
loadData();
};
const onPageChange = (event) => {
page.value = event.page + 1;
perPage.value = event.rows;
loadData();
};
const formatDate = (d) => {
if (!d) return '—';
return new Intl.DateTimeFormat('fa-IR', {
year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit'
}).format(new Date(d));
};
</script>
<template>
<div class="transactions-page">
<!-- Header -->
<div class="page-header">
<div class="header-content">
<div class="header-icon">
<i class="pi pi-history"></i>
</div>
<div>
<h1 class="page-title">تراکنش‌های انبار</h1>
<p class="page-subtitle">تاریخچه کامل ورود و خروج اقلام</p>
</div>
</div>
</div>
<!-- Filters -->
<div class="card filters-card">
<div class="filters-header">
<span class="filters-title"><i class="pi pi-filter"></i> فیلترها</span>
<Button label="پاک‌کردن فیلترها" icon="pi pi-times" text size="small" @click="clearFilters" />
</div>
<div class="filters-grid">
<div class="filter-field">
<label>قلم انبار</label>
<Select
v-model="filters.itemId"
:options="items"
optionLabel="nameFa"
optionValue="_id"
placeholder="همه اقلام"
showClear
class="w-full"
/>
</div>
<div class="filter-field">
<label>انبار</label>
<Select
v-model="filters.warehouseId"
:options="warehouses"
optionLabel="name"
optionValue="_id"
placeholder="همه انبارها"
showClear
class="w-full"
/>
</div>
<div class="filter-field">
<label>نوع تراکنش</label>
<Select
v-model="filters.type"
:options="typeOptions"
optionLabel="label"
optionValue="value"
placeholder="همه"
showClear
class="w-full"
/>
</div>
<div class="filter-field">
<label>از تاریخ</label>
<InputText v-model="filters.dateFrom" type="date" class="w-full" dir="ltr" />
</div>
<div class="filter-field">
<label>تا تاریخ</label>
<InputText v-model="filters.dateTo" type="date" class="w-full" dir="ltr" />
</div>
<div class="filter-field filter-action">
<Button label="اعمال فیلتر" icon="pi pi-search" class="apply-btn" @click="applyFilters" />
</div>
</div>
</div>
<!-- Table -->
<div class="card main-card">
<DataTable
:value="transactions"
:loading="loading"
dataKey="_id"
:paginator="true"
:rows="perPage"
:total-records="totalCount"
lazy
@page="onPageChange($event)"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
:rowsPerPageOptions="[20, 30, 50]"
currentPageReportTemplate="نمایش {first} تا {last} از {totalRecords} تراکنش"
stripedRows
responsiveLayout="scroll"
>
<template #header>
<div class="flex justify-between items-center">
<span class="table-title">
لیست تراکنش‌ها
<Tag severity="secondary" :value="`${totalCount.toLocaleString('fa-IR')} تراکنش`" />
</span>
</div>
</template>
<template #empty>
<div class="empty-state">
<i class="pi pi-inbox"></i>
<p>هیچ تراکنشی یافت نشد</p>
</div>
</template>
<Column header="نوع" style="width:7%">
<template #body="{ data }">
<Tag
:severity="data.type === 'IN' ? 'success' : 'danger'"
:value="data.type === 'IN' ? 'ورود' : 'خروج'"
class="type-tag"
/>
</template>
</Column>
<Column header="قلم انبار" style="width:16%">
<template #body="{ data }">
<div class="item-cell">
<span class="item-name-fa">{{ data.item?.nameFa || '—' }}</span>
<span class="item-name-en">{{ data.item?.nameEn }}</span>
</div>
</template>
</Column>
<Column header="مقدار" style="width:12%">
<template #body="{ data }">
<span class="qty-display" :class="data.type === 'IN' ? 'qty-in' : 'qty-out'">
{{ data.type === 'OUT' ? '−' : '+' }}{{ data.quantity.toLocaleString('fa-IR') }}
<small>{{ data.unit }}</small>
</span>
</template>
</Column>
<Column header="انبار" style="width:13%">
<template #body="{ data }">
<div class="warehouse-cell">
<i class="pi pi-map-marker" style="font-size:0.75rem; opacity:0.5;"></i>
{{ data.warehouse?.name || '—' }}
</div>
</template>
</Column>
<Column header="دلیل" style="width:18%">
<template #body="{ data }">
<div>
<span class="reason-text">{{ data.reason }}</span>
<div class="note-text" v-if="data.note">{{ data.note }}</div>
</div>
</template>
</Column>
<Column header="کاربر" style="width:12%">
<template #body="{ data }">
<div class="actor-cell">
<i class="pi pi-user" style="font-size:0.75rem; opacity:0.5;"></i>
{{ data.actorName || data.actor?.name || '—' }}
</div>
</template>
</Column>
<Column header="تاریخ" style="width:14%">
<template #body="{ data }">
<span class="date-text">{{ formatDate(data.date || data.createdAt) }}</span>
</template>
</Column>
<Column style="width:8%">
<template #body="{ data }">
<Button
icon="pi pi-eye"
text
rounded
severity="secondary"
size="small"
v-tooltip.top="'مشاهده موجودی قلم'"
@click="router.push(`/warehouse-items/stock/${data.item?._id}`)"
/>
</template>
</Column>
</DataTable>
</div>
</div>
</template>
<style scoped>
.transactions-page { padding: 1.5rem; direction: rtl; }
/* Header */
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem; }
.header-content { display: flex; align-items: center; gap: 1rem; }
.header-icon {
width: 52px; height: 52px;
border-radius: 14px;
background: linear-gradient(135deg, #0ea5e9, #6366f1);
display: flex; align-items: center; justify-content: center;
font-size: 1.5rem; color: #fff;
box-shadow: 0 4px 15px rgba(14,165,233,0.35);
}
.page-title { margin: 0; font-size: 1.5rem; font-weight: 700; }
.page-subtitle { margin: 0; color: var(--text-color-secondary); font-size: 0.875rem; }
/* Filters */
.filters-card { border-radius: 16px; margin-bottom: 1.25rem; }
.filters-header {
display: flex; justify-content: space-between; align-items: center;
margin-bottom: 1rem;
}
.filters-title { font-weight: 600; display: flex; align-items: center; gap: 0.5rem; }
.filters-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
gap: 1rem;
align-items: end;
}
.filter-field { display: flex; flex-direction: column; gap: 0.4rem; }
.filter-field label { font-size: 0.85rem; font-weight: 600; color: var(--text-color-secondary); }
.filter-action { display: flex; align-items: flex-end; }
.apply-btn {
background: linear-gradient(135deg, #6366f1, #8b5cf6) !important;
border: none !important;
width: 100%;
}
/* Table */
.main-card { border-radius: 16px; }
.table-title { display: flex; align-items: center; gap: 0.75rem; font-weight: 600; }
.empty-state {
text-align: center; padding: 3rem;
color: var(--text-color-secondary);
}
.empty-state i { font-size: 2.5rem; display: block; margin-bottom: 0.75rem; opacity: 0.3; }
/* Cells */
.type-tag { font-weight: 700; }
.item-cell { display: flex; flex-direction: column; }
.item-name-fa { font-weight: 600; font-size: 0.9rem; }
.item-name-en { font-size: 0.75rem; color: var(--text-color-secondary); direction: ltr; display: inline-block; }
.qty-display { font-weight: 700; font-size: 1rem; }
.qty-in { color: #16a34a; }
.qty-out { color: #dc2626; }
.qty-display small { font-size: 0.75rem; font-weight: 400; margin-right: 0.25rem; color: var(--text-color-secondary); }
.warehouse-cell { display: flex; align-items: center; gap: 0.35rem; font-size: 0.875rem; }
.actor-cell { display: flex; align-items: center; gap: 0.35rem; font-size: 0.875rem; }
.reason-text { font-size: 0.875rem; }
.note-text { font-size: 0.775rem; color: var(--text-color-secondary); margin-top: 2px; }
.date-text { font-size: 0.8rem; color: var(--text-color-secondary); }
</style>
@@ -0,0 +1,537 @@
<script setup>
import { onMounted, ref, watch } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useRouter, useRoute } from 'vue-router';
import { useConfirm } from 'primevue/useconfirm';
import ConfirmPopup from 'primevue/confirmpopup';
import { WarehouseItemService } from '@/service/WarehouseItemService';
const toast = useToast();
const router = useRouter();
const route = useRoute();
const confirm = useConfirm();
const items = ref([]);
const totalCount = ref(0);
const page = ref(Number(route.query.page) || 1);
const perPage = ref(Number(route.query.per_page) || 20);
const searchPhrase = ref(route.query.search || '');
const loading = ref(false);
// Create/Edit dialog
const showDialog = ref(false);
const editMode = ref(false);
const submitting = ref(false);
const selectedItem = ref(null);
const form = ref({
nameFa: '',
nameEn: '',
code: '',
unitFa: '',
unitEn: '',
category: '',
description: ''
});
// ─── Common units ─────────────────────────────────────────────────────────────
const UNITS = [
{ fa: 'عدد', en: 'Piece' },
{ fa: 'تن', en: 'Ton' },
{ fa: 'کیلوگرم', en: 'Kilogram' },
{ fa: 'متر', en: 'Meter' },
{ fa: 'متر مربع', en: 'Square Meter' },
{ fa: 'متر مکعب', en: 'Cubic Meter' },
{ fa: 'لیتر', en: 'Liter' },
{ fa: 'بسته', en: 'Package' },
{ fa: 'رول', en: 'Roll' },
{ fa: 'جعبه', en: 'Box' },
{ fa: 'کیسه', en: 'Bag' },
{ fa: 'پالت', en: 'Pallet' },
];
let searchTimeout = null;
onMounted(() => {
loadData();
});
watch(searchPhrase, (val) => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
router.push({ query: { ...route.query, search: val || undefined, page: 1 } });
}, 400);
});
watch(() => route.query, () => {
page.value = Number(route.query.page) || 1;
perPage.value = Number(route.query.per_page) || 20;
searchPhrase.value = route.query.search || '';
loadData();
}, { deep: true });
const loadData = async () => {
loading.value = true;
try {
const result = await WarehouseItemService.listItems({
page: page.value,
limit: perPage.value,
search: searchPhrase.value || undefined
});
items.value = result.items || [];
totalCount.value = result.total || 0;
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: 'خطا در بارگذاری اطلاعات', life: 3000 });
} finally {
loading.value = false;
}
};
const onPageChange = (event) => {
router.push({ query: { ...route.query, page: event.page + 1, per_page: event.rows } });
};
const openCreateDialog = () => {
editMode.value = false;
selectedItem.value = null;
form.value = { nameFa: '', nameEn: '', code: '', unitFa: '', unitEn: '', category: '', description: '' };
showDialog.value = true;
};
const openEditDialog = (item) => {
editMode.value = true;
selectedItem.value = item;
form.value = {
nameFa: item.nameFa,
nameEn: item.nameEn,
code: item.code || '',
unitFa: item.unitFa,
unitEn: item.unitEn,
category: item.category || '',
description: item.description || ''
};
showDialog.value = true;
};
const onUnitSelect = (unit) => {
form.value.unitFa = unit.fa;
form.value.unitEn = unit.en;
};
const submitForm = async () => {
if (!form.value.nameFa || !form.value.nameEn || !form.value.unitFa || !form.value.unitEn) {
toast.add({ severity: 'warn', summary: 'توجه', detail: 'لطفاً تمام فیلدهای ضروری را پر کنید', life: 3000 });
return;
}
submitting.value = true;
try {
if (editMode.value) {
await WarehouseItemService.updateItem(selectedItem.value._id, form.value);
toast.add({ severity: 'success', summary: 'موفق', detail: 'آیتم با موفقیت ویرایش شد', life: 3000 });
} else {
await WarehouseItemService.createItem(form.value);
toast.add({ severity: 'success', summary: 'موفق', detail: 'آیتم با موفقیت ایجاد شد', life: 3000 });
}
showDialog.value = false;
loadData();
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: e.response?.data?.message || 'عملیات ناموفق بود', life: 4000 });
} finally {
submitting.value = false;
}
};
const confirmDelete = (item, event) => {
confirm.require({
target: event.currentTarget,
message: `آیا از غیرفعال‌سازی "${item.nameFa}" اطمینان دارید؟`,
icon: 'pi pi-exclamation-triangle',
rejectProps: { label: 'خیر', severity: 'secondary', outlined: true },
acceptProps: { label: 'بله', severity: 'danger' },
accept: async () => {
try {
await WarehouseItemService.deleteItem(item._id);
toast.add({ severity: 'success', summary: 'موفق', detail: 'آیتم غیرفعال شد', life: 3000 });
loadData();
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: 'عملیات ناموفق بود', life: 3000 });
}
}
});
};
const viewStock = (itemId) => {
router.push(`/warehouse-items/stock/${itemId}`);
};
</script>
<template>
<ConfirmPopup />
<div class="warehouse-items-page">
<!-- ─── Header ─────────────────────────────────────────────────── -->
<div class="page-header">
<div class="header-content">
<div class="header-icon">
<i class="pi pi-box"></i>
</div>
<div>
<h1 class="page-title">اقلام انبار</h1>
<p class="page-subtitle">مدیریت محصولات و مصالح انبار</p>
</div>
</div>
<div class="header-actions">
<Button
label="افزودن قلم جدید"
icon="pi pi-plus"
class="create-btn"
@click="openCreateDialog"
/>
</div>
</div>
<!-- ─── Main card ───────────────────────────────────────────────── -->
<div class="card main-card">
<DataTable
:value="items"
:loading="loading"
dataKey="_id"
:paginator="true"
:rows="perPage"
:total-records="totalCount"
lazy
@page="onPageChange($event)"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
:rowsPerPageOptions="[20, 40, 80]"
currentPageReportTemplate="نمایش {first} تا {last} از {totalRecords} قلم"
stripedRows
responsiveLayout="scroll"
>
<template #header>
<div class="table-header">
<span class="table-title">لیست اقلام</span>
<IconField>
<InputIcon><i class="pi pi-search" /></InputIcon>
<InputText v-model="searchPhrase" placeholder="جستجو..." class="search-input" />
</IconField>
</div>
</template>
<template #empty>
<div class="empty-state">
<i class="pi pi-inbox empty-icon"></i>
<p>هیچ قلمی یافت نشد</p>
<Button label="افزودن اولین قلم" icon="pi pi-plus" @click="openCreateDialog" />
</div>
</template>
<Column field="code" header="کد" style="width:8%">
<template #body="{ data }">
<span class="code-badge" v-if="data.code">{{ data.code }}</span>
<span class="text-muted" v-else>—</span>
</template>
</Column>
<Column field="nameFa" header="نام فارسی" sortable style="width:18%">
<template #body="{ data }">
<div class="item-name">
<span class="name-fa">{{ data.nameFa }}</span>
</div>
</template>
</Column>
<Column field="nameEn" header="نام انگلیسی" sortable style="width:18%">
<template #body="{ data }">
<span class="name-en">{{ data.nameEn }}</span>
</template>
</Column>
<Column header="واحد" style="width:12%">
<template #body="{ data }">
<span class="unit-badge">{{ data.unitFa }} / {{ data.unitEn }}</span>
</template>
</Column>
<Column field="category" header="دسته‌بندی" style="width:14%">
<template #body="{ data }">
<span v-if="data.category" class="category-chip">{{ data.category }}</span>
<span v-else class="text-muted">—</span>
</template>
</Column>
<Column field="isActive" header="وضعیت" style="width:9%">
<template #body="{ data }">
<Tag :severity="data.isActive ? 'success' : 'danger'"
:value="data.isActive ? 'فعال' : 'غیرفعال'" />
</template>
</Column>
<Column header="عملیات" style="width:21%">
<template #body="{ data }">
<div class="action-buttons">
<Button
icon="pi pi-chart-bar"
outlined
rounded
severity="info"
v-tooltip.top="'مشاهده موجودی'"
@click="viewStock(data._id)"
/>
<Button
icon="pi pi-pencil"
outlined
rounded
v-tooltip.top="'ویرایش'"
@click="openEditDialog(data)"
/>
<Button
icon="pi pi-ban"
outlined
rounded
severity="danger"
v-tooltip.top="'غیرفعال‌سازی'"
@click="confirmDelete(data, $event)"
/>
</div>
</template>
</Column>
</DataTable>
</div>
<!-- ─── Create/Edit Dialog ──────────────────────────────────────── -->
<Dialog
v-model:visible="showDialog"
:header="editMode ? 'ویرایش قلم انبار' : 'افزودن قلم جدید'"
:style="{ width: '580px' }"
modal
:dir="'rtl'"
>
<div class="form-grid">
<div class="form-row">
<div class="form-field">
<label>نام فارسی <span class="required">*</span></label>
<InputText v-model="form.nameFa" placeholder="مثال: سیمان" class="w-full" />
</div>
<div class="form-field">
<label>نام انگلیسی <span class="required">*</span></label>
<InputText v-model="form.nameEn" placeholder="e.g. Cement" class="w-full" dir="ltr" />
</div>
</div>
<div class="form-row">
<div class="form-field">
<label>کد (اختیاری)</label>
<InputText v-model="form.code" placeholder="مثال: CEM" class="w-full" dir="ltr" />
</div>
<div class="form-field">
<label>دسته‌بندی</label>
<InputText v-model="form.category" placeholder="مثال: مصالح ساختمانی" class="w-full" />
</div>
</div>
<!-- Unit picker -->
<div class="form-field full-width">
<label>واحد شمارش <span class="required">*</span></label>
<div class="unit-picker">
<button
v-for="u in UNITS"
:key="u.en"
class="unit-chip"
:class="{ active: form.unitFa === u.fa }"
type="button"
@click="onUnitSelect(u)"
>
{{ u.fa }}
<span class="unit-en">{{ u.en }}</span>
</button>
</div>
<div class="unit-custom-row">
<InputText v-model="form.unitFa" placeholder="واحد فارسی سفارشی" class="w-1/2" />
<InputText v-model="form.unitEn" placeholder="Custom unit (EN)" class="w-1/2" dir="ltr" />
</div>
</div>
<div class="form-field full-width">
<label>توضیحات</label>
<Textarea v-model="form.description" rows="2" class="w-full" placeholder="توضیحات اختیاری..." autoResize />
</div>
</div>
<template #footer>
<Button label="انصراف" icon="pi pi-times" text @click="showDialog = false" />
<Button
:label="editMode ? 'ذخیره تغییرات' : 'ایجاد قلم'"
icon="pi pi-check"
:loading="submitting"
@click="submitForm"
/>
</template>
</Dialog>
</div>
</template>
<style scoped>
.warehouse-items-page {
padding: 1.5rem;
direction: rtl;
}
/* Header */
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1.5rem;
}
.header-content {
display: flex;
align-items: center;
gap: 1rem;
}
.header-icon {
width: 52px;
height: 52px;
border-radius: 14px;
background: linear-gradient(135deg, #6366f1, #8b5cf6);
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
color: #fff;
box-shadow: 0 4px 15px rgba(99, 102, 241, 0.35);
}
.page-title {
margin: 0;
font-size: 1.5rem;
font-weight: 700;
}
.page-subtitle {
margin: 0;
color: var(--text-color-secondary);
font-size: 0.875rem;
}
.create-btn {
background: linear-gradient(135deg, #6366f1, #8b5cf6) !important;
border: none !important;
padding: 0.65rem 1.5rem !important;
font-weight: 600 !important;
}
/* Card */
.main-card {
border-radius: 16px;
overflow: hidden;
}
/* Table header */
.table-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.25rem 0;
}
.table-title {
font-size: 1rem;
font-weight: 600;
}
.search-input { width: 260px; }
/* Empty state */
.empty-state {
text-align: center;
padding: 3rem;
color: var(--text-color-secondary);
}
.empty-icon {
font-size: 3rem;
display: block;
margin-bottom: 1rem;
opacity: 0.4;
}
/* Badges / chips */
.code-badge {
font-family: monospace;
background: var(--surface-100);
padding: 2px 8px;
border-radius: 6px;
font-size: 0.8rem;
font-weight: 600;
}
.name-fa { font-weight: 600; }
.name-en {
color: var(--text-color-secondary);
font-size: 0.875rem;
direction: ltr;
display: inline-block;
}
.unit-badge {
background: linear-gradient(135deg, rgba(99,102,241,0.1), rgba(139,92,246,0.1));
color: #6366f1;
padding: 3px 10px;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 600;
}
.category-chip {
background: var(--surface-200);
padding: 3px 10px;
border-radius: 20px;
font-size: 0.8rem;
}
.text-muted { color: var(--text-color-secondary); opacity: 0.5; }
/* Actions */
.action-buttons {
display: flex;
gap: 0.4rem;
align-items: center;
}
/* Form */
.form-grid { display: flex; flex-direction: column; gap: 1rem; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.form-field { display: flex; flex-direction: column; gap: 0.4rem; }
.form-field.full-width { grid-column: span 2; }
.form-field label { font-weight: 600; font-size: 0.9rem; }
.required { color: #ef4444; }
/* Unit picker */
.unit-picker {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-bottom: 0.75rem;
}
.unit-chip {
border: 1.5px solid var(--surface-border);
background: var(--surface-50);
border-radius: 20px;
padding: 5px 14px;
cursor: pointer;
font-size: 0.85rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.4rem;
transition: all 0.2s;
color: var(--text-color);
}
.unit-chip:hover { border-color: #6366f1; color: #6366f1; background: rgba(99,102,241,0.06); }
.unit-chip.active {
border-color: #6366f1;
background: linear-gradient(135deg, rgba(99,102,241,0.15), rgba(139,92,246,0.15));
color: #6366f1;
}
.unit-en {
font-size: 0.75rem;
opacity: 0.7;
direction: ltr;
display: inline-block;
}
.unit-custom-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.5rem;
}
</style>
@@ -0,0 +1,295 @@
<script setup>
import { onMounted, ref } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import ConfirmPopup from 'primevue/confirmpopup';
import { WarehouseService } from '@/service/WarehouseService';
const toast = useToast();
const confirm = useConfirm();
const warehouses = ref([]);
const loading = ref(false);
const showDialog = ref(false);
const editMode = ref(false);
const submitting = ref(false);
const selectedWarehouse = ref(null);
const searchPhrase = ref('');
const form = ref({
name: '',
code: '',
description: '',
location: { address: '' },
});
onMounted(() => loadData());
const loadData = async () => {
loading.value = true;
try {
warehouses.value = await WarehouseService.listWarehouses({
search: searchPhrase.value || undefined
});
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: 'خطا در بارگذاری انبارها', life: 3000 });
} finally {
loading.value = false;
}
};
const openCreate = () => {
editMode.value = false;
selectedWarehouse.value = null;
form.value = { name: '', code: '', description: '', location: { address: '' } };
showDialog.value = true;
};
const openEdit = (wh) => {
editMode.value = true;
selectedWarehouse.value = wh;
form.value = {
name: wh.name,
code: wh.code || '',
description: wh.description || '',
location: { address: wh.location?.address || '' },
};
showDialog.value = true;
};
const submitForm = async () => {
if (!form.value.name) {
toast.add({ severity: 'warn', summary: 'توجه', detail: 'نام انبار ضروری است', life: 3000 });
return;
}
submitting.value = true;
try {
if (editMode.value) {
await WarehouseService.updateWarehouse(selectedWarehouse.value._id, form.value);
toast.add({ severity: 'success', summary: 'موفق', detail: 'انبار با موفقیت ویرایش شد', life: 3000 });
} else {
await WarehouseService.createWarehouse(form.value);
toast.add({ severity: 'success', summary: 'موفق', detail: 'انبار با موفقیت ایجاد شد', life: 3000 });
}
showDialog.value = false;
loadData();
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: e.response?.data?.message || 'عملیات ناموفق', life: 4000 });
} finally {
submitting.value = false;
}
};
const confirmDelete = (wh, event) => {
confirm.require({
target: event.currentTarget,
message: `آیا از غیرفعال‌سازی انبار "${wh.name}" اطمینان دارید؟`,
icon: 'pi pi-exclamation-triangle',
rejectProps: { label: 'خیر', severity: 'secondary', outlined: true },
acceptProps: { label: 'بله', severity: 'danger' },
accept: async () => {
try {
await WarehouseService.deleteWarehouse(wh._id);
toast.add({ severity: 'success', summary: 'موفق', detail: 'انبار غیرفعال شد', life: 3000 });
loadData();
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: 'عملیات ناموفق', life: 3000 });
}
}
});
};
let searchTimeout;
const onSearch = () => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(loadData, 400);
};
</script>
<template>
<ConfirmPopup />
<div class="warehouses-page">
<!-- Header -->
<div class="page-header">
<div class="header-content">
<div class="header-icon">
<i class="pi pi-map"></i>
</div>
<div>
<h1 class="page-title">مدیریت انبارها</h1>
<p class="page-subtitle">مکان‌های نگهداری اقلام</p>
</div>
</div>
<Button label="افزودن انبار جدید" icon="pi pi-plus" class="create-btn" @click="openCreate" />
</div>
<!-- Table -->
<div class="card main-card">
<DataTable
:value="warehouses"
:loading="loading"
dataKey="_id"
stripedRows
responsiveLayout="scroll"
>
<template #header>
<div class="table-header">
<span class="table-title">لیست انبارها ({{ warehouses.length }})</span>
<IconField>
<InputIcon><i class="pi pi-search" /></InputIcon>
<InputText v-model="searchPhrase" placeholder="جستجو..." class="search-input" @input="onSearch" />
</IconField>
</div>
</template>
<template #empty>
<div class="empty-state">
<i class="pi pi-map empty-icon"></i>
<p>هیچ انباری تعریف نشده است</p>
<Button label="افزودن اولین انبار" icon="pi pi-plus" @click="openCreate" />
</div>
</template>
<Column field="code" header="کد" style="width:8%">
<template #body="{ data }">
<span v-if="data.code" class="code-badge">{{ data.code }}</span>
<span v-else class="text-muted">—</span>
</template>
</Column>
<Column field="name" header="نام انبار" sortable style="width:20%">
<template #body="{ data }">
<span class="warehouse-name">{{ data.name }}</span>
</template>
</Column>
<Column header="آدرس" style="width:28%">
<template #body="{ data }">
<span class="address-text">{{ data.location?.address || '—' }}</span>
</template>
</Column>
<Column header="مدیر انبار" style="width:16%">
<template #body="{ data }">
{{ data.manager?.name || '—' }}
</template>
</Column>
<Column field="isActive" header="وضعیت" style="width:9%">
<template #body="{ data }">
<Tag :severity="data.isActive ? 'success' : 'danger'"
:value="data.isActive ? 'فعال' : 'غیرفعال'" />
</template>
</Column>
<Column header="توضیحات" style="width:12%">
<template #body="{ data }">
<span class="desc-text">{{ data.description || '—' }}</span>
</template>
</Column>
<Column header="عملیات" style="width:7%">
<template #body="{ data }">
<div class="action-buttons">
<Button icon="pi pi-pencil" outlined rounded size="small" v-tooltip.top="'ویرایش'" @click="openEdit(data)" />
<Button icon="pi pi-ban" outlined rounded severity="danger" size="small" v-tooltip.top="'غیرفعال‌سازی'" @click="confirmDelete(data, $event)" />
</div>
</template>
</Column>
</DataTable>
</div>
<!-- Dialog -->
<Dialog
v-model:visible="showDialog"
:header="editMode ? 'ویرایش انبار' : 'افزودن انبار جدید'"
:style="{ width: '480px' }"
modal
dir="rtl"
>
<div class="form-grid">
<div class="form-row">
<div class="form-field">
<label>نام انبار <span class="required">*</span></label>
<InputText v-model="form.name" placeholder="مثال: انبار تهران" class="w-full" />
</div>
<div class="form-field">
<label>کد (اختیاری)</label>
<InputText v-model="form.code" placeholder="مثال: WHT" class="w-full" dir="ltr" />
</div>
</div>
<div class="form-field full-width">
<label>آدرس</label>
<InputText v-model="form.location.address" placeholder="آدرس کامل انبار" class="w-full" />
</div>
<div class="form-field full-width">
<label>توضیحات</label>
<Textarea v-model="form.description" rows="2" class="w-full" autoResize placeholder="توضیحات اختیاری..." />
</div>
</div>
<template #footer>
<Button label="انصراف" icon="pi pi-times" text @click="showDialog = false" />
<Button
:label="editMode ? 'ذخیره تغییرات' : 'ایجاد انبار'"
icon="pi pi-check"
:loading="submitting"
@click="submitForm"
/>
</template>
</Dialog>
</div>
</template>
<style scoped>
.warehouses-page { padding: 1.5rem; direction: rtl; }
.page-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem; }
.header-content { display: flex; align-items: center; gap: 1rem; }
.header-icon {
width: 52px; height: 52px;
border-radius: 14px;
background: linear-gradient(135deg, #0891b2, #0ea5e9);
display: flex; align-items: center; justify-content: center;
font-size: 1.5rem; color: #fff;
box-shadow: 0 4px 15px rgba(8,145,178,0.35);
}
.page-title { margin: 0; font-size: 1.5rem; font-weight: 700; }
.page-subtitle { margin: 0; color: var(--text-color-secondary); font-size: 0.875rem; }
.create-btn {
background: linear-gradient(135deg, #0891b2, #0ea5e9) !important;
border: none !important;
padding: 0.65rem 1.5rem !important;
font-weight: 600 !important;
}
.main-card { border-radius: 16px; }
.table-header { display: flex; align-items: center; justify-content: space-between; padding: 0.25rem 0; }
.table-title { font-size: 1rem; font-weight: 600; }
.search-input { width: 240px; }
.empty-state { text-align: center; padding: 3rem; color: var(--text-color-secondary); }
.empty-icon { font-size: 3rem; display: block; margin-bottom: 1rem; opacity: 0.35; }
.code-badge {
font-family: monospace;
background: var(--surface-100);
padding: 2px 8px;
border-radius: 6px;
font-size: 0.8rem;
font-weight: 600;
}
.warehouse-name { font-weight: 600; }
.address-text { font-size: 0.875rem; color: var(--text-color-secondary); }
.desc-text { font-size: 0.8rem; color: var(--text-color-secondary); }
.text-muted { opacity: 0.4; }
.action-buttons { display: flex; gap: 0.4rem; }
.form-grid { display: flex; flex-direction: column; gap: 1rem; }
.form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }
.form-field { display: flex; flex-direction: column; gap: 0.4rem; }
.form-field.full-width { }
.form-field label { font-weight: 600; font-size: 0.9rem; }
.required { color: #ef4444; }
</style>
@@ -0,0 +1,638 @@
<script setup>
import { onMounted, ref, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useToast } from 'primevue/usetoast';
import { useConfirm } from 'primevue/useconfirm';
import ConfirmPopup from 'primevue/confirmpopup';
import { WarehouseItemService } from '@/service/WarehouseItemService';
import { WarehouseService } from '@/service/WarehouseService';
const route = useRoute();
const router = useRouter();
const toast = useToast();
const confirm = useConfirm();
const itemId = computed(() => route.params.itemId);
const stockData = ref(null);
const warehouses = ref([]);
const loading = ref(false);
const showTransactionDialog = ref(false);
const showTransactionHistory = ref(false);
const submitting = ref(false);
const transactions = ref([]);
const transactionsLoading = ref(false);
const totalTransactions = ref(0);
const txForm = ref({
type: 'IN',
warehouseId: '',
quantity: null,
reason: '',
note: '',
});
const IN_REASONS = [
'خرید از تامین‌کننده',
'برگشت از کارگاه',
'انتقال از انبار دیگر',
'اهدا / دریافت رایگان',
'موجودی اولیه',
'سایر',
];
const OUT_REASONS = [
'مصرف در پروژه',
'انتقال به انبار دیگر',
'فروش / واگذاری',
'ضایعات',
'مفقودی',
'سایر',
];
const reasons = computed(() => txForm.value.type === 'IN' ? IN_REASONS : OUT_REASONS);
onMounted(async () => {
await Promise.all([loadStock(), loadWarehouses()]);
});
const loadStock = async () => {
loading.value = true;
try {
stockData.value = await WarehouseItemService.getStockByItem(itemId.value);
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: 'خطا در بارگذاری موجودی', life: 3000 });
} finally {
loading.value = false;
}
};
const loadWarehouses = async () => {
try {
warehouses.value = await WarehouseService.listWarehouses({ isActive: 'true' });
} catch (e) {
console.error('Failed to load warehouses', e);
}
};
const loadTransactions = async () => {
transactionsLoading.value = true;
try {
const result = await WarehouseItemService.listTransactions({ itemId: itemId.value, limit: 50 });
transactions.value = result.transactions || [];
totalTransactions.value = result.total || 0;
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: 'خطا در بارگذاری تراکنش‌ها', life: 3000 });
} finally {
transactionsLoading.value = false;
}
};
const openTransactionDialog = (type = 'IN') => {
txForm.value = { type, warehouseId: '', quantity: null, reason: '', note: '' };
showTransactionDialog.value = true;
};
const submitTransaction = async () => {
if (!txForm.value.warehouseId || !txForm.value.quantity || !txForm.value.reason) {
toast.add({ severity: 'warn', summary: 'توجه', detail: 'لطفاً تمام فیلدهای ضروری را پر کنید', life: 3000 });
return;
}
submitting.value = true;
try {
await WarehouseItemService.createTransaction({
itemId: itemId.value,
warehouseId: txForm.value.warehouseId,
type: txForm.value.type,
quantity: txForm.value.quantity,
reason: txForm.value.reason,
note: txForm.value.note,
});
toast.add({
severity: 'success',
summary: 'موفق',
detail: txForm.value.type === 'IN' ? 'موجودی با موفقیت افزوده شد' : 'موجودی با موفقیت کسر شد',
life: 3000
});
showTransactionDialog.value = false;
await loadStock();
if (showTransactionHistory.value) await loadTransactions();
} catch (e) {
toast.add({
severity: 'error',
summary: 'خطا',
detail: e.response?.data?.message || 'عملیات ناموفق بود',
life: 5000
});
} finally {
submitting.value = false;
}
};
const toggleHistory = async () => {
showTransactionHistory.value = !showTransactionHistory.value;
if (showTransactionHistory.value && transactions.value.length === 0) {
await loadTransactions();
}
};
const confirmDeleteTransaction = (tx, event) => {
confirm.require({
target: event.currentTarget,
message: 'حذف این تراکنش موجودی انبار را برگشت می‌دهد. مطمئنید؟',
icon: 'pi pi-exclamation-triangle',
rejectProps: { label: 'خیر', severity: 'secondary', outlined: true },
acceptProps: { label: 'بله، حذف شود', severity: 'danger' },
accept: async () => {
try {
await WarehouseItemService.deleteTransaction(tx._id);
toast.add({ severity: 'success', summary: 'موفق', detail: 'تراکنش حذف شد', life: 3000 });
await Promise.all([loadStock(), loadTransactions()]);
} catch (e) {
toast.add({ severity: 'error', summary: 'خطا', detail: e.response?.data?.message || 'خطا در حذف', life: 4000 });
}
}
});
};
const formatDate = (d) => {
if (!d) return '—';
return new Intl.DateTimeFormat('fa-IR', {
year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit'
}).format(new Date(d));
};
const getWarehouseName = (id) => {
const w = warehouses.value.find(w => w._id === id);
return w ? w.name : id;
};
</script>
<template>
<ConfirmPopup />
<div class="stock-view-page">
<!-- ─── Back + Title ──────────────────────────────────────────── -->
<div class="page-header">
<Button icon="pi pi-arrow-right" text rounded @click="router.back()" />
<div class="header-text" v-if="stockData">
<h1 class="page-title">
<span class="item-name-fa">{{ stockData.item.nameFa }}</span>
<span class="item-name-en">{{ stockData.item.nameEn }}</span>
</h1>
<p class="page-subtitle">مدیریت موجودی انبار</p>
</div>
<div class="header-actions" v-if="stockData">
<Button
icon="pi pi-plus"
label="افزودن موجودی"
severity="success"
@click="openTransactionDialog('IN')"
/>
<Button
icon="pi pi-minus"
label="کسر موجودی"
severity="danger"
outlined
@click="openTransactionDialog('OUT')"
/>
<Button
:icon="showTransactionHistory ? 'pi pi-times' : 'pi pi-history'"
:label="showTransactionHistory ? 'بستن تاریخچه' : 'تاریخچه تراکنش‌ها'"
severity="secondary"
outlined
@click="toggleHistory"
/>
</div>
</div>
<div v-if="loading" class="loading-container">
<ProgressSpinner />
</div>
<div v-else-if="stockData" class="content-grid">
<!-- ─── Total Summary Card ────────────────────────────────── -->
<div class="summary-card">
<div class="summary-icon">
<i class="pi pi-database"></i>
</div>
<div class="summary-details">
<span class="summary-label">موجودی کل (تمام انبارها)</span>
<div class="summary-value">
<span class="qty">{{ stockData.totalQuantity.toLocaleString('fa-IR') }}</span>
<span class="unit">{{ stockData.unit }}</span>
</div>
<span class="unit-en-label">{{ stockData.unitEn }}</span>
</div>
<div class="summary-locations">
<i class="pi pi-map-marker"></i>
{{ stockData.stocks.length }} انبار فعال
</div>
</div>
<!-- ─── Per-warehouse stock table ─────────────────────────── -->
<div class="card stock-table-card">
<h3 class="card-title">
<i class="pi pi-warehouse me-2"></i>
موجودی به تفکیک انبار
</h3>
<DataTable :value="stockData.stocks" stripedRows responsiveLayout="scroll">
<template #empty>
<div class="empty-state">
<i class="pi pi-inbox"></i>
<p>هنوز هیچ موجودی ثبت نشده است</p>
</div>
</template>
<Column header="انبار">
<template #body="{ data }">
<div class="warehouse-info">
<div class="warehouse-name">{{ data.warehouse?.name || '—' }}</div>
<div class="warehouse-code" v-if="data.warehouse?.code">{{ data.warehouse.code }}</div>
</div>
</template>
</Column>
<Column header="آدرس">
<template #body="{ data }">
<span class="warehouse-address">{{ data.warehouse?.location?.address || '—' }}</span>
</template>
</Column>
<Column header="موجودی فعلی">
<template #body="{ data }">
<div class="stock-quantity" :class="{ 'zero-stock': data.quantity <= 0, 'low-stock': data.quantity > 0 && data.quantity < 5 }">
<span class="qty-value">{{ data.quantity.toLocaleString('fa-IR') }}</span>
<span class="qty-unit">{{ data.unit }}</span>
</div>
</template>
</Column>
<Column header="عملیات" style="width: 12rem">
<template #body="{ data }">
<div class="row-actions">
<Button
icon="pi pi-plus"
size="small"
severity="success"
text
rounded
v-tooltip.top="'افزودن موجودی'"
@click="() => { txForm.warehouseId = data.warehouse?._id; openTransactionDialog('IN'); txForm.warehouseId = data.warehouse?._id; }"
/>
<Button
icon="pi pi-minus"
size="small"
severity="danger"
text
rounded
v-tooltip.top="'کسر موجودی'"
@click="() => { txForm.warehouseId = data.warehouse?._id; openTransactionDialog('OUT'); txForm.warehouseId = data.warehouse?._id; }"
/>
</div>
</template>
</Column>
</DataTable>
</div>
<!-- ─── Transaction History ────────────────────────────────── -->
<Transition name="slide-fade">
<div class="card history-card" v-if="showTransactionHistory">
<h3 class="card-title">
<i class="pi pi-history me-2"></i>
تاریخچه تراکنش‌ها
<span class="history-count">({{ totalTransactions }} تراکنش)</span>
</h3>
<DataTable
:value="transactions"
:loading="transactionsLoading"
stripedRows
responsiveLayout="scroll"
>
<template #empty>
<div class="empty-state"><p>هیچ تراکنشی یافت نشد</p></div>
</template>
<Column header="نوع" style="width:8%">
<template #body="{ data }">
<Tag
:severity="data.type === 'IN' ? 'success' : 'danger'"
:value="data.type === 'IN' ? 'ورود' : 'خروج'"
/>
</template>
</Column>
<Column header="مقدار">
<template #body="{ data }">
<span class="qty-value" :class="data.type === 'IN' ? 'in-qty' : 'out-qty'">
{{ data.type === 'OUT' ? '-' : '+' }}{{ data.quantity.toLocaleString('fa-IR') }} {{ data.unit }}
</span>
</template>
</Column>
<Column header="انبار">
<template #body="{ data }">{{ data.warehouse?.name || '—' }}</template>
</Column>
<Column header="دلیل">
<template #body="{ data }">
<span class="reason-text">{{ data.reason }}</span>
<small class="note-text" v-if="data.note"> — {{ data.note }}</small>
</template>
</Column>
<Column header="کاربر">
<template #body="{ data }">{{ data.actorName || data.actor?.name || '—' }}</template>
</Column>
<Column header="تاریخ">
<template #body="{ data }">{{ formatDate(data.date) }}</template>
</Column>
<Column style="width:5%">
<template #body="{ data }">
<Button
icon="pi pi-trash"
text
rounded
severity="danger"
size="small"
v-tooltip.top="'حذف تراکنش'"
@click="confirmDeleteTransaction(data, $event)"
/>
</template>
</Column>
</DataTable>
</div>
</Transition>
</div>
<!-- ─── Transaction Dialog ────────────────────────────────────── -->
<Dialog
v-model:visible="showTransactionDialog"
:header="txForm.type === 'IN' ? 'افزودن موجودی' : 'کسر موجودی'"
:style="{ width: '500px' }"
modal
dir="rtl"
>
<div class="tx-form">
<!-- Type toggle -->
<div class="type-toggle">
<button
class="type-btn"
:class="{ active: txForm.type === 'IN', 'in-type': true }"
@click="txForm.type = 'IN'"
type="button"
>
<i class="pi pi-arrow-down"></i> ورود به انبار
</button>
<button
class="type-btn"
:class="{ active: txForm.type === 'OUT', 'out-type': true }"
@click="txForm.type = 'OUT'"
type="button"
>
<i class="pi pi-arrow-up"></i> خروج از انبار
</button>
</div>
<div class="form-field">
<label>انبار <span class="required">*</span></label>
<Select
v-model="txForm.warehouseId"
:options="warehouses"
optionLabel="name"
optionValue="_id"
placeholder="انتخاب انبار..."
class="w-full"
/>
</div>
<div class="form-field">
<label>مقدار ({{ stockData?.unit }}) <span class="required">*</span></label>
<InputNumber
v-model="txForm.quantity"
:min="0.001"
:minFractionDigits="0"
:maxFractionDigits="3"
class="w-full"
placeholder="مقدار را وارد کنید"
:pt="{ input: { dir: 'ltr' } }"
/>
</div>
<div class="form-field">
<label>دلیل <span class="required">*</span></label>
<div class="reason-chips">
<button
v-for="r in reasons"
:key="r"
class="reason-chip"
:class="{ active: txForm.reason === r }"
type="button"
@click="txForm.reason = r"
>{{ r }}</button>
</div>
<InputText v-model="txForm.reason" placeholder="یا دلیل سفارشی وارد کنید..." class="w-full mt-2" />
</div>
<div class="form-field">
<label>یادداشت (اختیاری)</label>
<Textarea v-model="txForm.note" rows="2" class="w-full" autoResize placeholder="توضیحات تکمیلی..." />
</div>
<!-- Stock preview for OUT -->
<div class="stock-warning" v-if="txForm.type === 'OUT' && txForm.warehouseId">
<i class="pi pi-info-circle"></i>
<span>
موجودی فعلی در این انبار:
<strong>
{{
(stockData.stocks.find(s => s.warehouse?._id === txForm.warehouseId)?.quantity || 0).toLocaleString('fa-IR')
}} {{ stockData?.unit }}
</strong>
</span>
</div>
</div>
<template #footer>
<Button label="انصراف" icon="pi pi-times" text @click="showTransactionDialog = false" />
<Button
:label="txForm.type === 'IN' ? 'افزودن موجودی' : 'کسر موجودی'"
:icon="txForm.type === 'IN' ? 'pi pi-plus' : 'pi pi-minus'"
:severity="txForm.type === 'IN' ? 'success' : 'danger'"
:loading="submitting"
@click="submitTransaction"
/>
</template>
</Dialog>
</div>
</template>
<style scoped>
.stock-view-page { padding: 1.5rem; direction: rtl; }
/* Header */
.page-header {
display: flex;
align-items: center;
gap: 1rem;
margin-bottom: 1.5rem;
flex-wrap: wrap;
}
.header-text { flex: 1; }
.page-title {
margin: 0;
font-size: 1.4rem;
font-weight: 700;
display: flex;
align-items: center;
gap: 0.75rem;
}
.item-name-fa { color: var(--text-color); }
.item-name-en {
font-size: 0.95rem;
color: var(--text-color-secondary);
direction: ltr;
display: inline-block;
font-weight: 400;
}
.page-subtitle { margin: 0; color: var(--text-color-secondary); font-size: 0.875rem; }
.header-actions { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.loading-container { display: flex; justify-content: center; padding: 4rem; }
/* Content grid */
.content-grid { display: flex; flex-direction: column; gap: 1.5rem; }
/* Summary card */
.summary-card {
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
border-radius: 16px;
padding: 1.75rem 2rem;
color: #fff;
display: flex;
align-items: center;
gap: 1.5rem;
box-shadow: 0 8px 30px rgba(99,102,241,0.35);
}
.summary-icon {
width: 64px; height: 64px;
background: rgba(255,255,255,0.2);
border-radius: 16px;
display: flex; align-items: center; justify-content: center;
font-size: 1.8rem;
flex-shrink: 0;
}
.summary-details { flex: 1; }
.summary-label { font-size: 0.875rem; opacity: 0.85; display: block; margin-bottom: 0.3rem; }
.summary-value { display: flex; align-items: baseline; gap: 0.5rem; }
.summary-value .qty { font-size: 2.5rem; font-weight: 700; line-height: 1; }
.summary-value .unit { font-size: 1.1rem; opacity: 0.9; }
.unit-en-label { font-size: 0.8rem; opacity: 0.7; }
.summary-locations {
font-size: 0.875rem;
opacity: 0.85;
display: flex;
align-items: center;
gap: 0.4rem;
}
/* Table card */
.stock-table-card, .history-card { border-radius: 16px; }
.card-title {
font-size: 1rem;
font-weight: 600;
margin-bottom: 1.25rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.history-count { font-size: 0.8rem; color: var(--text-color-secondary); font-weight: 400; }
/* Warehouse cells */
.warehouse-name { font-weight: 600; }
.warehouse-code { font-size: 0.75rem; color: var(--text-color-secondary); font-family: monospace; }
.warehouse-address { font-size: 0.85rem; color: var(--text-color-secondary); }
/* Stock quantity */
.stock-quantity { display: flex; align-items: baseline; gap: 0.4rem; }
.qty-value { font-size: 1.2rem; font-weight: 700; }
.qty-unit { font-size: 0.8rem; color: var(--text-color-secondary); }
.zero-stock .qty-value { color: #ef4444; }
.low-stock .qty-value { color: #f59e0b; }
.in-qty { color: #22c55e; font-weight: 700; }
.out-qty { color: #ef4444; font-weight: 700; }
.row-actions { display: flex; gap: 0.25rem; }
.reason-text { font-size: 0.875rem; }
.note-text { font-size: 0.8rem; color: var(--text-color-secondary); }
.empty-state { text-align: center; padding: 2rem; color: var(--text-color-secondary); }
/* Slide animation */
.slide-fade-enter-active, .slide-fade-leave-active { transition: all 0.3s ease; }
.slide-fade-enter-from { opacity: 0; transform: translateY(-12px); }
.slide-fade-leave-to { opacity: 0; transform: translateY(-12px); }
/* TX form */
.tx-form { display: flex; flex-direction: column; gap: 1rem; }
.form-field { display: flex; flex-direction: column; gap: 0.4rem; }
.form-field label { font-weight: 600; font-size: 0.9rem; }
.required { color: #ef4444; }
.type-toggle {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.5rem;
border-radius: 12px;
overflow: hidden;
}
.type-btn {
padding: 0.75rem;
border: 2px solid var(--surface-border);
background: var(--surface-50);
border-radius: 10px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
transition: all 0.2s;
color: var(--text-color);
}
.type-btn.in-type.active { background: #dcfce7; border-color: #22c55e; color: #16a34a; }
.type-btn.out-type.active { background: #fee2e2; border-color: #ef4444; color: #dc2626; }
.type-btn:hover { border-color: var(--primary-color); }
.reason-chips { display: flex; flex-wrap: wrap; gap: 0.4rem; }
.reason-chip {
border: 1.5px solid var(--surface-border);
background: var(--surface-50);
border-radius: 20px;
padding: 4px 12px;
font-size: 0.8rem;
cursor: pointer;
transition: all 0.2s;
color: var(--text-color);
}
.reason-chip:hover { border-color: var(--primary-color); color: var(--primary-color); }
.reason-chip.active { background: var(--primary-50); border-color: var(--primary-color); color: var(--primary-color); font-weight: 600; }
.stock-warning {
background: #fef3c7;
border: 1px solid #f59e0b;
border-radius: 8px;
padding: 0.75rem 1rem;
font-size: 0.875rem;
display: flex;
align-items: center;
gap: 0.5rem;
color: #92400e;
}
</style>