REFACTOR: Belonging → Property system migration + dashboard + map improvements

Property system:
- Add PropertyService.js and PropertyStatusService.js
- Add Property pages: CreateProperty.vue, ListProperties.vue, TransactionDialog.vue
- Remove legacy BelongingService.js and Belonging pages (CreateBelonging, ListBelongings, TransactionDialog)

Dashboard:
- Update RecentSalesWidget.vue
- Update RevenueStreamWidget.vue
- Update StatsWidget.vue

UI & config:
- Major MapComponent.vue improvements (extended functionality)
- Update ListCategories.vue
- Update ListTransactions.vue
- Update vite.config.mjs
This commit is contained in:
2026-08-11 20:36:02 +03:30
parent c01fed2622
commit 79da0d24ab
13 changed files with 1522 additions and 742 deletions
+11 -16
View File
@@ -1,43 +1,38 @@
<script setup>
import { ProductService } from '@/service/ProductService';
import { onMounted, ref } from 'vue';
import { BelongingService } from '@/service/BelongingService';
import { PropertyService } from '@/service/PropertyService';
import { useRouter } from 'vue-router';
const products = ref(null);
function formatCurrency(value) {
return value.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
}
const properties = ref(null);
onMounted(() => {
BelongingService.getAllBelongings().then((data) => (products.value = data));
PropertyService.getAllProperties().then((data) => (properties.value = data));
});
const router = useRouter();
function editBelonging(belongingId) {
router.push('/belonging/edit-belonging/' + belongingId);
function editProperty(propertyId) {
router.push('/property/edit-property/' + propertyId);
}
</script>
<template>
<div class="card">
<div class="font-semibold text-xl mb-4">آخرین دارایی های افزوده شده</div>
<DataTable :value="products" :rows="5" :paginator="true" responsiveLayout="scroll">
<Column style="min-width: 15%" header="Image">
<div class="font-semibold text-xl mb-4">آخرین املاک افزوده شده</div>
<DataTable :value="properties" :rows="5" :paginator="true" responsiveLayout="scroll">
<Column style="min-width: 15%" header="تصویر">
<template #body="slotProps">
<img :src="`${slotProps.data.mainImageUrl}`" :alt="slotProps.data.name" width="50" class="shadow" />
<img :src="`${slotProps.data.mainImageUrl || slotProps.data.mainImageUrls?.[0]}`" :alt="slotProps.data.name" width="50" class="shadow" />
</template>
</Column>
<Column field="name" header="نام" :sortable="true" style="min-width: 35%"></Column>
<Column field="price" header="دسته بندی" :sortable="true" style="min-width: 30%">
<Column field="category" header="دسته بندی" :sortable="true" style="min-width: 30%">
<template #body="slotProps">
{{ slotProps.data.category?.nativeName }}
</template>
</Column>
<Column style="min-width: 15%" header="نمایش">
<template #body="slotProps">
<Button icon="pi pi-search" type="button" class="p-button-text" @click="editBelonging(slotProps.data._id)"></Button>
<Button icon="pi pi-search" type="button" class="p-button-text" @click="editProperty(slotProps.data._id)"></Button>
</template>
</Column>
</DataTable>
@@ -11,17 +11,17 @@ function setChartData() {
const documentStyle = getComputedStyle(document.documentElement);
return {
labels: ['زمین', 'ساختمان', 'خودرو', 'ارز'],
labels: ['زمین', 'ساختمان'],
datasets: [
{
type: 'bar',
label: 'تعداد دارایی ها',
label: 'تعداد املاک',
backgroundColor: documentStyle.getPropertyValue('--p-primary-400'),
font: {
family: 'Estedad', // Set custom font for y-axis labels
size: 14 // Set font size
family: 'Estedad',
size: 14
},
data: [18, 13, 5, 11],
data: [18, 13],
barThickness: 32
}
]
@@ -42,8 +42,8 @@ function setChartOptions() {
ticks: {
color: textMutedColor,
font: {
family: 'Estedad', // Set custom font for y-axis labels
size: 14 // Set font size
family: 'Estedad',
size: 14
}
},
grid: {
@@ -56,8 +56,8 @@ function setChartOptions() {
ticks: {
color: textMutedColor,
font: {
family: 'Estedad', // Set custom font for y-axis labels
size: 14 // Set font size
family: 'Estedad',
size: 14
}
},
grid: {
@@ -83,7 +83,7 @@ onMounted(() => {
<template>
<div class="card">
<div class="font-semibold text-xl mb-4">تقسیم بندی دارایی ها</div>
<div class="font-semibold text-xl mb-4">تقسیم بندی املاک</div>
<Chart type="bar" :data="chartData" :options="chartOptions" class="h-80" />
</div>
</template>
+1 -1
View File
@@ -3,7 +3,7 @@
<div class="card mb-0">
<div class="flex justify-between mb-4">
<div>
<span class="block text-muted-color font-medium mb-4">تعداد دارایی ها</span>
<span class="block text-muted-color font-medium mb-4">تعداد املاک</span>
<div class="text-surface-900 dark:text-surface-0 font-medium text-xl">100</div>
</div>
<div class="flex items-center justify-center bg-blue-100 dark:bg-blue-400/10 rounded-border" style="width: 2.5rem; height: 2.5rem">
@@ -1,7 +1,6 @@
import axios from 'axios';
export const BelongingService = {
// Helper function to get token from cookies
export const PropertyService = {
_getAuthHeader: () => {
const bmToken = document.cookie
.split('; ')
@@ -13,12 +12,12 @@ export const BelongingService = {
};
},
getBelonging: async (belongingId) => {
getProperty: async (propertyId) => {
const config = {
method: 'get',
url: '/api/belongings/admin/get-one/' + belongingId,
url: '/api/properties/admin/get-one/' + propertyId,
withCredentials: true,
headers: BelongingService._getAuthHeader()
headers: PropertyService._getAuthHeader()
};
try {
const response = await axios(config);
@@ -28,12 +27,12 @@ export const BelongingService = {
}
},
getAllBelongings: async () => {
getAllProperties: async () => {
const config = {
method: 'get',
url: '/api/belongings/admin/get-all',
url: '/api/properties/admin/get-all',
withCredentials: true,
headers: BelongingService._getAuthHeader()
headers: PropertyService._getAuthHeader()
};
try {
const response = await axios(config);
@@ -43,13 +42,13 @@ export const BelongingService = {
}
},
searchBelongings: async (query) => {
searchProperties: async (query) => {
const config = {
method: 'get',
url: '/api/belongings/admin/search',
url: '/api/properties/admin/search',
withCredentials: true,
params: query,
headers: BelongingService._getAuthHeader()
headers: PropertyService._getAuthHeader()
};
try {
const response = await axios(config);
@@ -59,12 +58,12 @@ export const BelongingService = {
}
},
indexBelongings: async () => {
indexProperties: async () => {
const config = {
method: 'post',
url: '/api/belongings/admin/index-all',
url: '/api/properties/admin/index-all',
withCredentials: true,
headers: BelongingService._getAuthHeader()
headers: PropertyService._getAuthHeader()
};
try {
const response = await axios(config);
@@ -74,13 +73,13 @@ export const BelongingService = {
}
},
createBelonging: async (data) => {
createProperty: async (data) => {
const config = {
method: 'post',
url: '/api/belongings/admin/create',
url: '/api/properties/admin/create',
withCredentials: true,
data,
headers: BelongingService._getAuthHeader()
headers: PropertyService._getAuthHeader()
};
try {
const response = await axios(config);
@@ -91,13 +90,13 @@ export const BelongingService = {
}
},
updateBelonging: async (belongingId, data) => {
updateProperty: async (propertyId, data) => {
const config = {
method: 'put',
url: '/api/belongings/admin/update/' + belongingId,
url: '/api/properties/admin/update/' + propertyId,
withCredentials: true,
data,
headers: BelongingService._getAuthHeader()
headers: PropertyService._getAuthHeader()
};
try {
const response = await axios(config);
@@ -106,5 +105,15 @@ export const BelongingService = {
console.log(err);
return err.response.data.message;
}
}
},
// Backward compatibility aliases
getBelonging: (id) => PropertyService.getProperty(id),
getAllBelongings: () => PropertyService.getAllProperties(),
searchBelongings: (q) => PropertyService.searchProperties(q),
indexBelongings: () => PropertyService.indexProperties(),
createBelonging: (data) => PropertyService.createProperty(data),
updateBelonging: (id, data) => PropertyService.updateProperty(id, data)
};
export const BelongingService = PropertyService;
+22
View File
@@ -0,0 +1,22 @@
import axios from 'axios';
import { PropertyService } from './PropertyService';
export const PropertyStatusService = {
getAllStatuses: async () => {
const config = {
method: 'get',
url: '/api/property-statuses/admin/get-all',
withCredentials: true,
headers: PropertyService._getAuthHeader()
};
try {
const response = await axios(config);
return response.data.data;
} catch (err) {
console.error('Error fetching property statuses:', err);
return [];
}
}
};
export const BelongingStatusService = PropertyStatusService;
@@ -1,546 +0,0 @@
<script setup>
import { Listbox, InputText } from 'primevue';
import { onBeforeMount, ref, watch } from 'vue';
import { CategoryService } from '@/service/CategoryService';
import ImageUploader from '@/views/uikit/ImageUploader.vue';
import ImageGallery from '@/views/uikit/ImageGallery.vue';
import KiwiChips from '@/views/uikit/KiwiChips.vue';
import { useToast } from 'primevue/usetoast';
import { BelongingService } from '@/service/BelongingService';
import { useRoute, useRouter } from 'vue-router';
import MapComponent from '@/views/uikit/MapComponent.vue';
import TransactionDialog from './TransactionDialog.vue';
import { TransactionService } from '@/service/TransactionService';
import { FilterMatchMode, FilterOperator } from '@primevue/core/api';
import Popover from 'primevue/popover';
// For the single popover approach
const op = ref();
const activeDescription = ref('');
const toggle = (event, data) => {
activeDescription.value = data;
op.value.toggle(event);
};
const toast = useToast();
const categories = ref([]);
const selectedCategory = ref();
const features = ref([]);
const featuresValues = ref({});
const documentData = ref([]);
const mainImageUrlsWithData = ref([]);
const uploadedMainImageUrls = ref([]);
const documentUrlsWithData = ref([]);
const uploadedDocumentUrls = ref([]);
const editMode = ref(false);
const belonging = ref({
documentUrls: [],
mainImageUrls: [],
location: {
type: 'Point',
coordinates: [0, 0]
}
});
const tags = ref([]);
const signedImageUrls = ref([]);
const signedDocumentsUrls = ref([]);
const route = useRoute();
const router = useRouter();
const mapKey = 'web.79abbab4970e401781f434da3e41cfa6';
const serviceKey = 'service.11d860f52c434bd29e5f84d0a0a41108';
const transactions = ref([]);
const stockData = ref({});
const handleDocumentUpload = (newDocumentUrls) => {
uploadedDocumentUrls.value = newDocumentUrls.value;
const tempConcatImages = [...belonging.value?.documentUrls, ...newDocumentUrls.value];
documentUrlsWithData.value = fillImagesArray(tempConcatImages);
};
const handleDocumentDelete = (newDocumentUrls) => {
uploadedDocumentUrls.value = newDocumentUrls;
const tempConcatImages = [...belonging.value?.documentUrls, ...newDocumentUrls.value];
documentUrlsWithData.value = fillImagesArray(tempConcatImages);
};
const handleDocumentGalleryDelete = (deletedDocumentUrl, index) => {
console.log('deletedImageUrl', deletedDocumentUrl, 'at index', index);
// Find which array contains the image to delete
if (index < belonging.value.documentUrls.length) {
// Remove only at specific index from belonging.value.mainImageNames
belonging.value.documentUrls.splice(index, 1);
} else {
// Adjust index for uploadedMainImageNames array
const adjustedIndex = index - belonging.value?.documentUrls.length;
uploadedDocumentUrls.value.splice(adjustedIndex, 1);
}
// Recombine arrays
const tempConcatImages = [...belonging.value?.documentUrls, ...uploadedDocumentUrls.value];
documentUrlsWithData.value = fillImagesArray(tempConcatImages);
};
const handleImageUpload = (newImageUrls) => {
uploadedMainImageUrls.value = newImageUrls.value;
// const tempConcatImages = [...belonging.value?.mainImageUrls, ...newImageUrls.value];
// mainImageUrlsWithData.value = fillImagesArray(tempConcatImages);
};
const handleImageDelete = (newImageUrls) => {
uploadedMainImageUrls.value = newImageUrls;
// const tempConcatImages = [...belonging.value?.mainImageUrls.value, ...newImageUrls.value];
// mainImageUrlsWithData.value = fillImagesArray(tempConcatImages);
};
const handleImageGalleryDelete = (deletedImageUrl, index) => {
console.log('deletedImageUrl', deletedImageUrl, 'at index', index);
// Find which array contains the image to delete
if (index < belonging.value?.mainImageUrls.length) {
// Remove only at specific index from belonging.value.mainImageNames
belonging.value?.mainImageUrls.splice(index, 1);
} else {
// Adjust index for uploadedMainImageNames array
const adjustedIndex = index - belonging.value?.mainImageUrls.length;
uploadedMainImageUrls.value?.splice(adjustedIndex, 1);
}
// Recombine arrays
const tempConcatImages = [...belonging.value?.mainImageUrls, ...uploadedMainImageUrls.value];
mainImageUrlsWithData.value = fillImagesArray(tempConcatImages);
};
onBeforeMount(async () => {
categories.value = await CategoryService.getAllCategories();
console.log(route.name);
if (route.name === 'edit-belonging') {
editMode.value = true;
belonging.value = await BelongingService.getBelonging(route.params.belongingId);
featuresValues.value = extractFeaturesValues(belonging.value.features);
transactions.value = await TransactionService.getTransactionsByBelongingId(route.params.belongingId);
stockData.value = await TransactionService.getStockByBelongingId(route.params.belongingId);
mainImageUrlsWithData.value = fillImagesArray(belonging.value?.mainImageUrls || []);
documentUrlsWithData.value = fillImagesArray(belonging.value?.documentUrls || []);
}
});
const showTransactionDialog = ref(false);
import { UTMtoLatLon, LatLontoUTM } from '@/utm';
const easting = ref();
const northing = ref();
const zone = ref();
const lat = ref();
const long = ref();
const convertUTMtoLatLng = () => {
if (easting.value && northing.value && zone.value) {
try {
const result = UTMtoLatLon(
Number(easting.value),
Number(northing.value),
Number(zone.value),
'N' // Change to 'S' if in Southern Hemisphere
);
lat.value = result.latitude;
long.value = result.longitude;
console.log(lat.value, long.value);
searchLocation(lat.value, long.value);
} catch (error) {
console.error('Error converting UTM to Lat/Lng:', error);
}
}
};
// Watch nationalGeoCode to split and convert to Lat/Lng
watch(
() => belonging.value.nationalGeoCode,
(newCode) => {
if (newCode && newCode.length === 15) {
easting.value = newCode.substring(0, 6); // First 6 digits for easting
northing.value = newCode.substring(6, 13); // Next 6 digits for northing
zone.value = newCode.substring(13, 15); // Last 2 digits for zone
// Convert to Lat/Lng after splitting
convertUTMtoLatLng();
}
}
);
const mapRef = ref();
const searchLocation = (lat, lon) => {
if (mapRef.value) {
mapRef.value.searchByCoordinates(lat, lon);
}
};
watch(
() => belonging.value.category,
(newCategory) => {
if (editMode.value && newCategory) {
selectedCategory.value = categories.value.find((x) => x._id === newCategory);
if (selectedCategory.value) {
features.value = selectedCategory.value.features;
}
}
}
);
const fillImagesArray = (imageUrls) => {
const images = [];
for (let url of imageUrls) {
images.push({ url: url });
}
return images;
};
const openTransactionDialog = () => {
showTransactionDialog.value = true;
};
const onTransactionSaved = async () => {
if (editMode.value && belonging.value?._id) {
belonging.value = await BelongingService.getBelonging(belonging.value._id);
}
// toast.add({ severity: 'success', summary: 'موفق', detail: 'تراکنش با موفقیت ثبت شد', life: 3000 });
};
const handleSelectCategory = ($event) => {
if ($event.value) {
belonging.value.category = $event.value;
selectedCategory.value = categories.value.find((x) => x._id === $event.value);
features.value = selectedCategory.value.features;
} else {
belonging.value = {
location: {
type: 'Point',
coordinates: [0, 0]
}
};
selectedCategory.value = {};
}
};
const extractFeatures = (featuresValues) => {
const features = [];
for (const [key, value] of Object.entries(featuresValues)) {
features.push({
definition: key,
value: value
});
}
return features;
};
const extractFeaturesValues = (features) => {
const featuresValues = {};
for (let feature of features) {
featuresValues[feature.definition] = feature.value;
}
return featuresValues;
};
const saveBelonging = async () => {
let status = 'failed';
console.log(belonging);
if (belonging?.value._id?.trim()) {
belonging.value.mainImageUrls = mainImageUrlsWithData.value.map((x) => x.url);
belonging.value.documentUrls = documentUrlsWithData.value.map((x) => x.url);
belonging.value.features = extractFeatures(featuresValues.value);
status = await BelongingService.updateBelonging(belonging.value._id, belonging.value);
} else {
belonging.value.mainImageUrls = mainImageUrlsWithData.value.map((x) => x.url);
belonging.value.documentUrls = documentUrlsWithData.value.map((x) => x.url);
belonging.value.features = extractFeatures(featuresValues.value);
status = await BelongingService.createBelonging(belonging.value);
}
if (status === 'success') {
toast.add({ severity: 'success', summary: 'موفق', detail: 'ویژگی جدید ساخته شد.', life: 3000 });
} else {
toast.add({ severity: 'error', summary: 'ناموفق', detail: status, life: 3000 });
}
setTimeout(async () => {
await router.push('/belonging/list-belongings');
}, 1000);
};
const filters = ref({
global: { value: null, matchMode: FilterMatchMode.CONTAINS },
type: { value: null, matchMode: FilterMatchMode.EQUALS },
status: { value: null, matchMode: FilterMatchMode.EQUALS },
value: { value: null, matchMode: FilterMatchMode.BETWEEN },
date: { value: null, matchMode: FilterMatchMode.DATE_IS }
});
// Options for filters
const typeOptions = [
{ label: 'واریز', value: 'deposit' },
{ label: 'برداشت', value: 'withdraw' }
];
const statusOptions = [
{ label: 'ناموفق', value: 'failed' },
{ label: 'در انتظار', value: 'pending' },
{ label: 'تکمیل شده', value: 'finished' }
];
// Helper functions for translations and formatting
const getTypeTranslation = (type) => {
switch (type) {
case 'deposit':
return 'واریز';
case 'withdraw':
return 'برداشت';
default:
return type;
}
};
const getTypeSeverity = (type) => {
switch (type) {
case 'deposit':
return 'success';
case 'withdraw':
return 'danger';
default:
return null;
}
};
const getStatusTranslation = (status) => {
switch (status) {
case 'failed':
return 'ناموفق';
case 'pending':
return 'در انتظار';
case 'finished':
return 'تکمیل شده';
default:
return status;
}
};
const getStatusSeverity = (status) => {
switch (status) {
case 'failed':
return 'danger';
case 'pending':
return 'warn';
case 'finished':
return 'success';
default:
return null;
}
};
const formatCurrency = (value) => {
return new Intl.NumberFormat('fa-IR', {
style: 'currency',
currency: 'IRR',
minimumFractionDigits: 0
}).format(Math.abs(value));
};
const formatDate = (dateString) => {
const date = new Date(dateString);
return new Intl.DateTimeFormat('fa-IR', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
}).format(date);
};
</script>
<template>
<TransactionDialog v-model:visible="showTransactionDialog" :belongingId="belonging._id" @saved="onTransactionSaved" />
<div className="card lg:p-5 px-3">
<div class="mb-4" v-if="editMode === true">
<Button @click="openTransactionDialog">افزایش یا کاهش موجودی</Button>
</div>
<div class="font-semibold text-xl mb-4" v-if="editMode === false">ایجاد اموال</div>
<p v-if="editMode === false">از طریق این صفحه می توانید اموال جدید را به سوابق اضافه کنید.</p>
<div class="font-semibold text-xl mb-4" v-if="editMode === true">
در حال ویرایش
<span class="text-primary">{{ belonging.name }}</span>
</div>
<div class="lg:flex my-6">
<div class="lg:w-3/4 w-full ml-3">
<div class="">
<label class="text-lg"> نام دارایی </label>
<InputText v-model="belonging.name" class="w-full my-2" placeholder="مثلا: 100 عدد کولر گازی" />
</div>
<div class="my-6">
<label class="text-lg"> توضیحات </label>
<Textarea v-model="belonging.description" class="w-full my-2" placeholder="مثلا: در تاریخ 1403/09/11 خریداری شد." rows="6" />
</div>
<div class="my-6">
<label class="text-lg"> تصاویر، فایل ها و مدارک </label>
<ImageUploader
v-model="uploadedDocumentUrls"
:max-files="50"
mode="private"
delete-endpoint="/api/files/bucket/delete-file/belonging-documents"
upload-endpoint="/api/files/bucket/upload-multi-filepond/belonging-documents"
@upload="handleDocumentUpload"
@delete="handleDocumentDelete"
/>
<div v-if="documentUrlsWithData.length > 0">
<ImageGallery v-model="documentUrlsWithData" gallery-id="documents" @delete-image="handleDocumentGalleryDelete" />
</div>
</div>
<div class="my-6" v-if="signedDocumentsUrls.length > 0">
<label class="text-lg"> فایل ها و مدارک </label>
</div>
<div class="my-6 max-h-96 overflow-y-auto" v-if="features.length > 0">
<label class="text-lg"> اطلاعات دارایی </label>
<div class="my-6 mr-10" v-for="feature of features">
<label>{{ feature.nativeName }}</label>
<InputText v-model="featuresValues[feature._id]" class="w-1/3 my-2 block" placeholder="" />
</div>
</div>
<div class="my-10">
<label class="text-lg"> موقعیت دارایی </label>
<MapComponent ref="mapRef" v-model="belonging.location.coordinates" />
<!-- <MapIrComponent />-->
</div>
<div class="my-10" v-if="editMode">
<label class="text-lg"> موجودی </label>
<p class="mx-3 text-blue-400">موجودی فعلی : {{ stockData.finishedInventory }}</p>
<p class="mx-3 text-green-400">موجودی در حال اضافه شدن : {{ stockData.pendingDepositsInventory }}</p>
<p class="mx-3 text-red-400">
موجودی در حال کم شدن : <span dir="ltr">{{ stockData.pendingWithdrawsInventory }}</span>
</p>
<div class="mx-6 py-4">
<label> تراکنش ها </label>
<div class="card lg:p-5 px-3">
<DataTable
:value="transactions"
paginator
:rows="20"
:rowsPerPageOptions="[20, 50, 100]"
tableStyle="min-width: 50rem"
stripedRows
v-model:filters="filters"
filterDisplay="menu"
:globalFilterFields="['type', 'status', 'value', 'date', 'description']"
>
<template #header>
<div class="lg:flex lg:justify-content-between">
<span class="p-input-icon-left">
<!-- <i class="pi pi-search" />-->
<InputText v-model="filters['global'].value" placeholder="جستجو..." class="w-full" />
</span>
</div>
</template>
<Column field="id" header="شناسه" sortable style="width: 25%"></Column>
<Column field="type" header="نوع" sortable style="width: 15%">
<template #body="{ data }">
<Tag :severity="getTypeSeverity(data.type)" :value="getTypeTranslation(data.type)" />
</template>
<template #filter="{ filterModel, filterCallback }">
<Dropdown v-model="filterModel.value" @change="filterCallback()" :options="typeOptions" optionLabel="label" optionValue="value" placeholder="انتخاب نوع" class="p-column-filter" showClear />
</template>
</Column>
<Column field="status" header="وضعیت" sortable style="width: 15%">
<template #body="{ data }">
<Tag :severity="getStatusSeverity(data.status)" :value="getStatusTranslation(data.status)" />
</template>
<template #filter="{ filterModel, filterCallback }">
<Dropdown v-model="filterModel.value" @change="filterCallback()" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="انتخاب وضعیت" class="p-column-filter" showClear />
</template>
</Column>
<Column field="value" header="تعداد" sortable style="width: 15%">
<template #body="{ data }">
<span :class="data.value >= 0 ? 'text-green-500' : 'text-red-500'" dir="ltr"> {{ data.value }} </span>
</template>
</Column>
<Column field="date" header="تاریخ" sortable style="width: 20%">
<template #body="{ data }">
{{ formatDate(data.date) }}
</template>
</Column>
<Column field="description" header="توضیحات" style="width: 10%">
<template #body="{ data }">
<Button v-if="data.description" icon="pi pi-info-circle" text rounded aria-label="توضیحات" @click="toggle($event, data.description)" />
</template>
</Column>
<Popover ref="op" :showCloseIcon="true" :autoHide="false">
<div class="p-2">{{ activeDescription }}</div>
</Popover>
</DataTable>
</div>
</div>
</div>
</div>
<div class="lg:w-1/4 w-full">
<div>
<label class="text-lg"> دسته بندی </label>
<Listbox @change="handleSelectCategory($event)" v-model="belonging.category" :options="categories" optionLabel="nativeName" optionValue="_id" checkmark :highlightOnSelect="false" class="w-full my-2" />
</div>
<div class="my-6">
<label class="text-lg"> تصویر اصلی </label>
<ImageUploader
v-model="uploadedMainImageUrls"
accepted-files="image/*"
:max-files="1"
mode="private"
delete-endpoint="/api/files/bucket/delete/belonging-images"
upload-endpoint="/api/files/bucket/upload-multi-filepond/belonging-images"
@upload="handleImageUpload"
@delete="handleImageDelete"
/>
<div class="my-10 border rounded-lg p-3 border-surface-700" v-if="mainImageUrlsWithData.length > 0">
<label for="ImageGallery">گالری تصاویر</label>
<div class="">
<ImageGallery v-model="mainImageUrlsWithData" gallery-id="productImages" @delete-image="handleImageGalleryDelete" />
</div>
</div>
</div>
<div class="my-8">
<label class="text-lg"> واحد </label>
<InputText v-model="belonging.unit" class="w-full" placeholder="مثلا: عدد، متر، و..." />
</div>
<div class="my-8">
<label class="text-lg"> برچسب ها </label>
<KiwiChips v-model="belonging.tags" class="w-full" placeholder="مثلا: زمین، ملک، کیانپارس..." />
</div>
<div class="my-8">
<label class="text-lg"> شناسه ملی جغرافیایی </label>
<InputText v-model="belonging.nationalGeoCode" class="w-full" placeholder="شناسه 14 رقمی سند" />
</div>
</div>
</div>
<div class="flex justify-center">
<Button @click="saveBelonging">ذخیره</Button>
</div>
</div>
</template>
<style>
@import url('leaflet/dist/leaflet.css');
</style>
<style scoped>
label {
@apply text-primary;
}
</style>
+1 -1
View File
@@ -121,7 +121,7 @@ function deleteSelectedCategories() {
:filters="filters"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
:rowsPerPageOptions="[20, 40, 80]"
currentPageReportTemplate="نمایش {first} تا {last} از {totalRecords} دارایی"
currentPageReportTemplate="نمایش {first} تا {last} از {totalRecords} دسته‌بندی"
>
<template #header>
<div class="flex flex-wrap gap-2 items-center justify-between">
+909
View File
@@ -0,0 +1,909 @@
<script setup>
import { onBeforeMount, ref, watch, computed } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useRoute, useRouter } from 'vue-router';
import { CategoryService } from '@/service/CategoryService';
import { PropertyService } from '@/service/PropertyService';
import { PropertyStatusService } from '@/service/PropertyStatusService';
import ImageUploader from '@/views/uikit/ImageUploader.vue';
import KiwiChips from '@/views/uikit/KiwiChips.vue';
import MapComponent from '@/views/uikit/MapComponent.vue';
import { UTMtoLatLon } from '@/utm';
// PrimeVue Components
import Dropdown from 'primevue/dropdown';
import MultiSelect from 'primevue/multiselect';
import InputText from 'primevue/inputtext';
import InputNumber from 'primevue/inputnumber';
import Textarea from 'primevue/textarea';
import ToggleSwitch from 'primevue/toggleswitch';
import Button from 'primevue/button';
import Tag from 'primevue/tag';
import SelectButton from 'primevue/selectbutton';
const toast = useToast();
const route = useRoute();
const router = useRouter();
// State
const categories = ref([]);
const statuses = ref([]);
const selectedCategory = ref(null);
const features = ref([]);
const featuresValues = ref({});
const mainImageUrlsWithData = ref([]);
const documentUrlsWithData = ref([]);
const editMode = ref(false);
const isSaving = ref(false);
const propertyTypes = ref([
{ label: 'زمین', value: 'Land' },
{ label: 'ساختمان', value: 'Building' }
]);
const documentTypeOptions = ref(['سند تک‌برگ', 'منگوله‌دار', 'وقفی', 'مشاع', 'بنچاق', 'قولنامه‌ای']);
const specialStatusOptions = ref(['عادی', 'توقیف', 'رهن', 'وراثتی', 'اوقافی', 'دولتی', 'در دست ساخت', 'مسدود']);
const zoningOptions = ref(['مسکونی', 'تجاری', 'کشاورزی', 'صنعتی', 'ویلایی', 'باغی', 'آموزشی', 'اداری']);
const structureTypeOptions = ref(['اسکلت بتنی', 'اسکلت فلزی', 'دیوار باربر', 'سازه پیش‌ساخته']);
const flooringTypeOptions = ref(['سرامیک', 'سنگ', 'پارکت', 'لمینت', 'موزاییک']);
const sideDirectionOptions = ref(['شمالی', 'جنوبی', 'شرقی', 'غربی', 'شمال شرقی', 'شمال غربی', 'جنوب شرقی', 'جنوب غربی']);
const property = ref({
name: '',
propertyType: 'Land',
category: null,
status: null,
description: '',
tags: [],
nationalGeoCode: '',
uniqueId: '',
serialNumber: '',
provinceRegistry: '',
localRegistryOffice: '',
registrationDate: '',
documentUrls: [],
mainImageUrls: [],
location: {
type: 'Point',
coordinates: [0, 0]
},
// 1. مشخصات مالک
ownerName: '',
fatherName: '',
idCardNumber: '',
nationalId: '',
issuePlace: '',
birthDate: '',
nationality: 'ایران',
dong: 6,
ownershipDocs: '',
// 2. مشخصات ملک
subNumber: '',
mainNumber: '',
separatedFrom: '',
plotNumber: '',
registrationSection: '',
district: '',
area: null,
blockNumber: '',
sideDirection: '',
floor: '',
specialStatus: 'عادی',
zoningType: 'مسکونی',
documentType: 'سند تک‌برگ',
address: '',
postalCode: '',
propertyBoundaries: '',
restrictions: '',
// Technical Features
landArea: null,
streetWidth: null,
facadeCount: null,
landLength: null,
landWidth: null,
builtArea: null,
floorsCount: null,
unitsCount: null,
constructionYear: null,
elevator: false,
parking: false,
warehouse: false,
heatingSystem: '',
coolingSystem: '',
structureType: '',
flooringType: ''
});
// Map state
const mapRef = ref(null);
const easting = ref();
const northing = ref();
const zone = ref();
const lat = ref();
const long = ref();
// Auto-generated property name: ownerName + شماره اصلی/شماره فرعی
const computedPropertyName = computed(() => {
const owner = property.value.ownerName?.trim() || '';
const main = property.value.mainNumber?.trim() || '';
const sub = property.value.subNumber?.trim() || '';
const regNum = main && sub ? `${main}/${sub}` : (main || sub || '');
if (owner && regNum) return `${owner} - ${regNum}`;
if (owner) return owner;
if (regNum) return regNum;
return '';
});
// Dong options with fractional description
const dongOptions = [
{ value: 1, label: '۱ دانگ', fraction: '۱⁏۶' },
{ value: 2, label: '۲ دانگ', fraction: '۱⁏۳ (یک سوم)' },
{ value: 3, label: '۳ دانگ', fraction: '۱⁏۲ (نیم)' },
{ value: 4, label: '۴ دانگ', fraction: '۲⁏۳ (دو سوم)' },
{ value: 5, label: '۵ دانگ', fraction: '۵⁏۶' },
{ value: 6, label: '۶ دانگ', fraction: 'تمام (مالکیت کامل)' },
];
const convertUTMtoLatLng = () => {
if (easting.value && northing.value && zone.value) {
try {
const result = UTMtoLatLon(
Number(easting.value),
Number(northing.value),
Number(zone.value),
'N'
);
lat.value = result.latitude;
long.value = result.longitude;
searchLocation(lat.value, long.value);
} catch (error) {
console.error('Error converting UTM to Lat/Lng:', error);
}
}
};
const handleMarkerUpdated = (coords) => {
if (coords && Array.isArray(coords)) {
property.value.location = {
type: 'Point',
coordinates: [coords[1], coords[0]]
};
lat.value = coords[0];
long.value = coords[1];
}
};
const searchLocation = (latitude, longitude) => {
if (mapRef.value && latitude && longitude) {
mapRef.value.setCenterAndMarker(Number(latitude), Number(longitude));
}
};
let geoCodeDebounceTimeout = null;
/**
* Parse Iran's شناسه ملی جغرافیایی (JAM code) which is a concatenated UTM string:
* - First 6 digits → Easting (e.g. 538136)
* - Next 7 digits → Northing (e.g. 3950135)
* - Last 2 digits → UTM Zone (e.g. 39 for most of Iran)
* If the code doesn't match the 15-digit pattern, falls back to zone 39.
*/
const parseNationalGeoCode = (code) => {
const digits = code.replace(/\D/g, ''); // strip non-digits
if (digits.length === 15) {
// Standard JAM: 6 easting + 7 northing + 2 zone
const e = parseInt(digits.slice(0, 6), 10);
const n = parseInt(digits.slice(6, 13), 10);
const z = parseInt(digits.slice(13, 15), 10);
return { easting: e, northing: n, zone: z };
}
if (digits.length === 13) {
// Some codes omit the zone (older format) — assume zone 39 for Iran
const e = parseInt(digits.slice(0, 6), 10);
const n = parseInt(digits.slice(6, 13), 10);
return { easting: e, northing: n, zone: 39 };
}
return null;
};
const applyNationalGeoCode = (val) => {
// 1. Try parsing as a JAM UTM code (15-digit or 13-digit)
const parsed = parseNationalGeoCode(val);
if (parsed) {
try {
const result = UTMtoLatLon(parsed.easting, parsed.northing, parsed.zone, 'N');
lat.value = result.latitude;
long.value = result.longitude;
easting.value = parsed.easting;
northing.value = parsed.northing;
zone.value = parsed.zone;
searchLocation(result.latitude, result.longitude);
return;
} catch (err) {
console.error('UTM conversion failed:', err);
}
}
// 2. Fallback: treat as lat,lon text or geocode search via map
if (mapRef.value && typeof mapRef.value.searchLocation === 'function') {
mapRef.value.searchLocation(val);
}
};
const handleNationalGeoCodeChange = () => {
const val = property.value.nationalGeoCode?.trim();
if (!val) return;
const digits = val.replace(/\D/g, '');
// Fire immediately once a full 15-digit JAM code is complete — no waiting
if (digits.length === 15) {
if (geoCodeDebounceTimeout) clearTimeout(geoCodeDebounceTimeout);
applyNationalGeoCode(val);
return;
}
// For partial / non-standard input, debounce to avoid firing on every keystroke
if (geoCodeDebounceTimeout) clearTimeout(geoCodeDebounceTimeout);
geoCodeDebounceTimeout = setTimeout(() => applyNationalGeoCode(val), 600);
};
// Auto sync category when propertyType changes
watch(() => property.value.propertyType, (newType) => {
if (!categories.value || categories.value.length === 0) return;
let targetCatName = newType === 'Land' ? 'Lot' : 'Building';
let matchedCategory = categories.value.find(c => c.englishName === targetCatName || c.nativeName === (newType === 'Land' ? 'زمین' : 'ساختمان'));
if (matchedCategory) {
property.value.category = matchedCategory._id;
handleSelectCategory(matchedCategory._id);
}
});
const initializeFeatureDefaultValues = () => {
featuresValues.value = {};
if (features.value && Array.isArray(features.value)) {
features.value.forEach((feat) => {
const definition = feat.definition || feat;
if (definition && definition._id) {
if (definition.type === 'boolean') {
featuresValues.value[definition._id] = false;
} else if (definition.type === 'multiselect') {
featuresValues.value[definition._id] = [];
} else {
featuresValues.value[definition._id] = null;
}
}
});
}
};
const extractFeaturesValues = (featuresArray) => {
const values = {};
if (Array.isArray(featuresArray)) {
featuresArray.forEach((item) => {
const defId = item.definition?._id || item.definition;
if (defId) {
values[defId] = item.value;
}
});
}
return values;
};
const serializeFeaturesPayload = (valuesObject) => {
const result = [];
if (valuesObject && typeof valuesObject === 'object') {
Object.entries(valuesObject).forEach(([definitionId, val]) => {
if (val !== null && val !== undefined && val !== '') {
result.push({
definition: definitionId,
value: val
});
}
});
}
return result;
};
const groupedFeatures = computed(() => {
if (!features.value || !Array.isArray(features.value)) return {};
const groups = {};
features.value.forEach((feat) => {
const def = feat.definition || feat;
const tag = def.tag || 'سایر ویژگی‌ها';
if (!groups[tag]) groups[tag] = [];
groups[tag].push(def);
});
return groups;
});
const fillImagesArray = (urlsArray) => {
if (!Array.isArray(urlsArray)) return [];
return urlsArray.map((url) => ({
name: url.split('/').pop() || 'file',
url: url,
progress: 100
}));
};
const handleSelectCategory = (catId) => {
selectedCategory.value = categories.value.find((c) => c._id === catId);
if (selectedCategory.value) {
features.value = selectedCategory.value.features || [];
initializeFeatureDefaultValues();
} else {
features.value = [];
featuresValues.value = {};
}
};
const onMainImageUploaded = (res) => {
if (res && res.url) {
mainImageUrlsWithData.value.push({
name: res.originalName || 'image',
url: res.url,
progress: 100
});
}
};
const onDocumentUploaded = (res) => {
if (res && res.url) {
documentUrlsWithData.value.push({
name: res.originalName || 'document',
url: res.url,
progress: 100
});
}
};
const getStatusSeverity = (st) => {
if (!st) return 'secondary';
// Use the color field from the API; fall back to secondary
const valid = ['success', 'info', 'warn', 'danger', 'secondary', 'contrast'];
return valid.includes(st.color) ? st.color : 'secondary';
};
onBeforeMount(async () => {
try {
const [fetchedCategories, fetchedStatuses] = await Promise.all([
CategoryService.getAllCategories(),
PropertyStatusService.getAllStatuses()
]);
categories.value = fetchedCategories || [];
statuses.value = fetchedStatuses || [];
const propId = route.params.propertyId || route.params.belongingId;
if (propId) {
editMode.value = true;
const data = await PropertyService.getProperty(propId);
if (data) {
property.value = { ...property.value, ...data };
featuresValues.value = extractFeaturesValues(data.features);
mainImageUrlsWithData.value = fillImagesArray(data.mainImageUrls || []);
documentUrlsWithData.value = fillImagesArray(data.documentUrls || []);
if (data.category) {
const catId = typeof data.category === 'object' ? data.category._id : data.category;
selectedCategory.value = categories.value.find((x) => x._id === catId);
if (selectedCategory.value) {
features.value = selectedCategory.value.features || [];
}
}
}
} else {
let matchedCat = categories.value.find(c => c.englishName === 'Lot' || c.nativeName === 'زمین');
if (matchedCat) {
property.value.category = matchedCat._id;
handleSelectCategory(matchedCat._id);
}
}
} catch (err) {
console.error('Initialization error:', err);
}
});
const saveProperty = async () => {
// Auto-set name from ownerName + mainNumber/subNumber
property.value.name = computedPropertyName.value || 'ملک جدید';
if (!property.value.nationalGeoCode?.trim()) {
toast.add({ severity: 'warn', summary: 'هشدار', detail: 'شناسه ملی جغرافیایی الزامی است.', life: 3000 });
return;
}
isSaving.value = true;
try {
property.value.mainImageUrls = mainImageUrlsWithData.value.map((x) => x.url);
property.value.documentUrls = documentUrlsWithData.value.map((x) => x.url);
property.value.features = serializeFeaturesPayload(featuresValues.value);
let status = 'failed';
if (property.value._id?.trim()) {
status = await PropertyService.updateProperty(property.value._id, property.value);
} else {
status = await PropertyService.createProperty(property.value);
}
if (status === 'success') {
toast.add({
severity: 'success',
summary: 'موفقیت‌آمیز',
detail: editMode.value ? 'اطلاعات ملک با موفقیت بروزرسانی شد.' : 'ملک جدید با موفقیت ایجاد شد.',
life: 3000
});
setTimeout(async () => {
await router.push('/property/list-properties');
}, 800);
} else {
toast.add({ severity: 'error', summary: 'خطا در ثبت', detail: status, life: 4000 });
}
} catch (error) {
console.error('Save error:', error);
toast.add({ severity: 'error', summary: 'خطا', detail: 'خطایی در ارتباط با سرور رخ داد.', life: 4000 });
} finally {
isSaving.value = false;
}
};
</script>
<template>
<div class="space-y-6 dir-rtl" style="direction: rtl;">
<!-- Header Bar -->
<div class="card p-4 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
<div class="flex items-center gap-3">
<div class="p-3 bg-primary-50 dark:bg-primary-950/50 rounded-xl text-primary">
<i class="pi pi-building text-2xl"></i>
</div>
<div>
<div class="flex items-center gap-2 flex-wrap">
<h1 class="text-xl font-bold text-surface-900 dark:text-surface-0">
{{ editMode ? 'ویرایش ملک' : 'ایجاد ملک جدید' }}
</h1>
<Tag :value="editMode ? 'حالت ویرایش' : 'حالت ایجاد'" :severity="editMode ? 'warn' : 'success'" rounded class="px-2.5 text-xs font-semibold" />
</div>
<p class="text-xs text-surface-500 dark:text-surface-400 mt-0.5">
{{ editMode ? property.name || 'در حال بروزرسانی اطلاعات ملک' : 'مشخصات ملک (زمین یا ساختمان)، ویژگی‌ها و شناسه ملی جغرافیایی را ثبت نمایید' }}
</p>
</div>
</div>
<div class="flex items-center gap-2 flex-wrap justify-end">
<Button label="بازگشت" icon="pi pi-arrow-right" severity="secondary" text rounded @click="router.push('/property/list-properties')" />
<Button
:label="editMode ? 'بروزرسانی ملک' : 'ذخیره ملک'"
icon="pi pi-check"
severity="primary"
rounded
:loading="isSaving"
@click="saveProperty"
class="px-5 font-semibold"
/>
</div>
</div>
<!-- Main Layout Grid -->
<div class="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
<!-- Main Content Area -->
<div class="lg:col-span-8 space-y-6 w-full">
<!-- 1. General Identification & Registry Card (شناسه و اداره ثبت) -->
<div class="card p-4 sm:p-6 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl space-y-5">
<div class="flex items-center gap-2 text-primary font-bold text-lg border-b border-surface-100 dark:border-surface-800 pb-3">
<i class="pi pi-file-edit text-xl"></i>
<span>شناسه و اداره ثبت اسناد</span>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<!-- 1. شناسه یکتا -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">
شناسه یکتا ثبت ملک (۱۸ رقم)
</label>
<InputText
v-model="property.uniqueId"
placeholder="مثلاً: ۱۳۹۹۲۱۵۸۰۳۰۱۰۰۰۱۲۳"
class="w-full !rounded-xl"
fluid
/>
</div>
<!-- شناسه ملی جغرافیایی (جام) -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">
شناسه ملی جغرافیایی (جام) <span class="text-red-500">*</span>
</label>
<div class="flex gap-2">
<InputText
v-model="property.nationalGeoCode"
placeholder="کد ۱۵ رقمی جام (UTM)"
class="w-full !rounded-xl"
fluid
@input="handleNationalGeoCodeChange"
@change="handleNationalGeoCodeChange"
@keyup.enter="handleNationalGeoCodeChange"
/>
<Button
icon="pi pi-map-marker"
severity="secondary"
outlined
rounded
title="یافتن نقطه روی نقشه"
@click="handleNationalGeoCodeChange"
/>
</div>
</div>
<!-- 2. شماره سریال -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">شماره سریال سند</label>
<InputText v-model="property.serialNumber" placeholder="مثلاً: الف/۹۹ ۱۲۳۴۵۶" class="w-full !rounded-xl" fluid />
</div>
<!-- 3. اداره کل استان -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">اداره کل استان</label>
<InputText v-model="property.provinceRegistry" placeholder="مثلاً: خوزستان" class="w-full !rounded-xl" fluid />
</div>
<!-- 4. اداره ثبت اسناد و املاک -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">اداره ثبت اسناد و املاک</label>
<InputText v-model="property.localRegistryOffice" placeholder="مثلاً: کرج - ناحیه ۱" class="w-full !rounded-xl" fluid />
</div>
<!-- 5. تاریخ ثبت -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">تاریخ ثبت</label>
<InputText v-model="property.registrationDate" placeholder="مثلاً: ۱۳۹۹/۰۴/۱۵" class="w-full !rounded-xl" fluid />
</div>
<!-- Auto Name Preview -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">
نام ملک
<span class="text-xs text-surface-400 font-normal mr-1">(خودکار تولید می‌شود)</span>
</label>
<div class="flex items-center gap-2 px-3 py-2.5 rounded-xl bg-surface-100 dark:bg-surface-800 border border-surface-200 dark:border-surface-700 min-h-[42px]">
<i class="pi pi-tag text-primary text-sm"></i>
<span v-if="computedPropertyName" class="text-sm font-semibold text-surface-800 dark:text-surface-100">
{{ computedPropertyName }}
</span>
<span v-else class="text-sm text-surface-400 italic">
پس از وارد کردن نام مالک و شماره ثبتی نمایش داده می‌شود
</span>
</div>
</div>
<!-- Category Selector & Status -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">دسته‌بندی اصلی</label>
<Dropdown
v-model="property.category"
:options="categories"
optionLabel="nativeName"
optionValue="_id"
placeholder="انتخاب دسته‌بندی"
class="w-full !rounded-xl"
@change="handleSelectCategory($event.value)"
showClear
fluid
/>
</div>
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">وضعیت ملک</label>
<Dropdown
v-model="property.status"
:options="statuses"
optionLabel="nativeName"
optionValue="_id"
placeholder="انتخاب وضعیت"
class="w-full !rounded-xl"
showClear
fluid
>
<template #option="slotProps">
<div class="flex items-center gap-2">
<Tag :value="slotProps.option.nativeName" :severity="getStatusSeverity(slotProps.option)" rounded class="text-xs" />
</div>
</template>
</Dropdown>
</div>
</div>
</div>
<!-- 2. Owner Specifications Card (مشخصات مالک) -->
<div class="card p-4 sm:p-6 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl space-y-5">
<div class="flex items-center gap-2 text-primary font-bold text-lg border-b border-surface-100 dark:border-surface-800 pb-3">
<i class="pi pi-user text-xl"></i>
<span>مشخصات مالک</span>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<!-- 1. نام و نام خانوادگی مالک -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">نام و نام خانوادگی مالک</label>
<InputText v-model="property.ownerName" placeholder="نام و نام خانوادگی" class="w-full !rounded-xl" fluid />
</div>
<!-- 2. نام پدر مالک -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">نام پدر مالک</label>
<InputText v-model="property.fatherName" placeholder="نام پدر" class="w-full !rounded-xl" fluid />
</div>
<!-- 3. شماره شناسنامه مالک -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">شماره شناسنامه مالک</label>
<InputText v-model="property.idCardNumber" placeholder="شماره شناسنامه" class="w-full !rounded-xl" fluid />
</div>
<!-- 4. شماره ملی مالک یا شناسه ملی شرکت -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">شماره ملی مالک یا شناسه ملی شرکت</label>
<InputText v-model="property.nationalId" placeholder="شماره ملی (۱۰ رقم) / شناسه شرکت (۱۱ رقم)" class="w-full !rounded-xl" fluid />
</div>
<!-- 5. محل صدور شناسنامه مالک یا محل ثبت شرکت -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">محل صدور شناسنامه / محل ثبت شرکت</label>
<InputText v-model="property.issuePlace" placeholder="محل صدور یا ثبت" class="w-full !rounded-xl" fluid />
</div>
<!-- 6. تاریخ تولد مالک یا تاریخ ثبت شرکت -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">تاریخ تولد مالک / تاریخ ثبت شرکت</label>
<InputText v-model="property.birthDate" placeholder="مثلاً: ۱۳۶۵/۰۵/۱۲" class="w-full !rounded-xl" fluid />
</div>
<!-- 7. تابعیت -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">تابعیت</label>
<InputText v-model="property.nationality" placeholder="مثلاً: ایران" class="w-full !rounded-xl" fluid />
</div>
<!-- 8. میزان مالکیت (دانگ) -->
<div class="sm:col-span-2">
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-2">
میزان مالکیت (دانگ)
<span class="text-xs text-surface-400 font-normal mr-2">
(هر ملک از ۶ دانگ تشکیل شده)
</span>
</label>
<div class="flex gap-2 flex-wrap items-center">
<button
v-for="opt in dongOptions"
:key="opt.value"
type="button"
@click="property.dong = opt.value"
class="flex flex-col items-center justify-center px-3 py-1.5 rounded-xl border transition-all cursor-pointer min-w-[64px] text-xs"
:class="property.dong === opt.value
? 'bg-primary text-primary-contrast border-primary shadow-md shadow-primary/25 font-bold scale-[1.02]'
: 'bg-surface-0 dark:bg-surface-900 text-surface-700 dark:text-surface-200 border-surface-200 dark:border-surface-700 hover:border-primary/50 hover:bg-surface-50 dark:hover:bg-surface-800'"
>
<span class="text-xs font-bold leading-tight">{{ opt.label }}</span>
<span class="text-[10px] opacity-70 leading-tight mt-0.5">{{ opt.fraction }}</span>
</button>
</div>
</div>
<!-- 9. مستندات مالکیت -->
<div class="sm:col-span-2">
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">مستندات مالکیت</label>
<Textarea v-model="property.ownershipDocs" placeholder="شرح مستندات، شماره بنچاق، مبایعه‌نامه و انتقال..." rows="2" class="w-full !rounded-xl" fluid />
</div>
</div>
</div>
<!-- 3. Property Specifications Card (مشخصات ملک) -->
<div class="card p-4 sm:p-6 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl space-y-5">
<div class="flex items-center gap-2 text-primary font-bold text-lg border-b border-surface-100 dark:border-surface-800 pb-3">
<i class="pi pi-building text-xl"></i>
<span>مشخصات ملک</span>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<!-- 1. شماره فرعی -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">شماره فرعی</label>
<InputText v-model="property.subNumber" placeholder="شماره فرعی ثبت" class="w-full !rounded-xl" fluid />
</div>
<!-- 2. شماره اصلی -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">شماره اصلی</label>
<InputText v-model="property.mainNumber" placeholder="شماره اصلی ثبت" class="w-full !rounded-xl" fluid />
</div>
<!-- 3. مفروز و مجزی از -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">مفروز و مجزی از</label>
<InputText v-model="property.separatedFrom" placeholder="شماره پلاک یا بخش قبلی" class="w-full !rounded-xl" fluid />
</div>
<!-- 4. قطعه -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">قطعه</label>
<InputText v-model="property.plotNumber" placeholder="شماره قطعه" class="w-full !rounded-xl" fluid />
</div>
<!-- 5. بخش ثبتی -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">بخش ثبتی</label>
<InputText v-model="property.registrationSection" placeholder="مثلاً: بخش ۱ اهواز" class="w-full !rounded-xl" fluid />
</div>
<!-- 6. ناحیه -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">ناحیه</label>
<InputText v-model="property.district" placeholder="مثلاً: ناحیه ۲" class="w-full !rounded-xl" fluid />
</div>
<!-- 7. مساحت به متر مربع -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">مساحت به متر مربع</label>
<InputNumber v-model="property.area" placeholder="مثلاً: ۳۵۰.۵" class="w-full !rounded-xl" fluid />
</div>
<!-- 8. بلوک -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">بلوک</label>
<InputText v-model="property.blockNumber" placeholder="شماره بلوک" class="w-full !rounded-xl" fluid />
</div>
<!-- 9. سمت -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">سمت</label>
<Dropdown v-model="property.sideDirection" :options="sideDirectionOptions" placeholder="انتخاب سمت" class="w-full !rounded-xl" fluid showClear />
</div>
<!-- 10. طبقه -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">طبقه</label>
<InputText v-model="property.floor" placeholder="مثلاً: طبقه اول / همکف" class="w-full !rounded-xl" fluid />
</div>
<!-- 11. نوع ملک -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">
نوع ملک <span class="text-red-500">*</span>
</label>
<SelectButton v-model="property.propertyType" :options="propertyTypes" optionLabel="label" optionValue="value" class="w-full" />
</div>
<!-- 12. وضعیت خاص -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">وضعیت خاص</label>
<Dropdown v-model="property.specialStatus" :options="specialStatusOptions" placeholder="انتخاب وضعیت خاص" class="w-full !rounded-xl" fluid />
</div>
<!-- 13. کاربری -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">کاربری</label>
<Dropdown v-model="property.zoningType" :options="zoningOptions" placeholder="انتخاب کاربری" class="w-full !rounded-xl" fluid />
</div>
<!-- 14. نوع سند -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">نوع سند</label>
<Dropdown v-model="property.documentType" :options="documentTypeOptions" placeholder="انتخاب نوع سند" class="w-full !rounded-xl" fluid />
</div>
<!-- 15. نشانی ملک -->
<div class="sm:col-span-2">
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">نشانی ملک</label>
<Textarea v-model="property.address" placeholder="نشانی کامل و دقیق ملک..." rows="2" class="w-full !rounded-xl" fluid />
</div>
<!-- 16. کدپستی -->
<div>
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">کدپستی ۱۰ رقمی</label>
<InputText v-model="property.postalCode" placeholder="کدپستی ملک" class="w-full !rounded-xl" fluid />
</div>
<!-- 17. حدود مفروزات -->
<div class="sm:col-span-2">
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">حدود مفروزات</label>
<Textarea v-model="property.propertyBoundaries" placeholder="شرح تفصیلی حدود مفروزات و مجاورین (شمال، جنوب، شرق، غرب)..." rows="3" class="w-full !rounded-xl" fluid />
</div>
<!-- 18. محدودیت ها و نقل انتقالات -->
<div class="sm:col-span-2">
<label class="block text-sm font-medium text-surface-700 dark:text-surface-200 mb-1.5">محدودیت‌ها و نقل و انتقالات</label>
<Textarea v-model="property.restrictions" placeholder="شرح حقوق ارتفاقی، بازداشت، رهن و نقل و انتقالات ثبت‌شده..." rows="3" class="w-full !rounded-xl" fluid />
</div>
</div>
</div>
<!-- 5. Category Dynamic Features Card (if present) -->
<div v-if="features && features.length > 0" class="card p-4 sm:p-6 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl space-y-5">
<div class="flex items-center gap-2 text-primary font-bold text-lg border-b border-surface-100 dark:border-surface-800 pb-3">
<i class="pi pi-cog text-xl"></i>
<span>ویژگی‌های تکمیلی دسته‌بندی</span>
</div>
<div v-for="(groupFeats, tagName) in groupedFeatures" :key="tagName" class="space-y-3">
<h3 class="text-sm font-bold text-surface-600 dark:text-surface-400 border-b border-surface-100 dark:border-surface-800 pb-1">
{{ tagName }}
</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div v-for="feat in groupFeats" :key="feat._id" class="space-y-1">
<label class="block text-xs font-medium text-surface-600 dark:text-surface-300">
{{ feat.nativeName }}
</label>
<Dropdown
v-if="feat.predefinedValues && feat.predefinedValues.length > 0"
v-model="featuresValues[feat._id]"
:options="feat.predefinedValues"
placeholder="انتخاب کنید"
class="w-full !rounded-xl"
showClear
fluid
/>
<InputText v-else-if="feat.featureType === 'string' || feat.featureType === 'text' || feat.type === 'string'" v-model="featuresValues[feat._id]" class="w-full !rounded-xl" fluid />
<InputNumber v-else-if="feat.featureType === 'number' || feat.type === 'number'" v-model="featuresValues[feat._id]" class="w-full !rounded-xl" fluid />
<ToggleSwitch v-else-if="feat.featureType === 'boolean' || feat.type === 'boolean'" v-model="featuresValues[feat._id]" />
</div>
</div>
</div>
</div>
<!-- 6. Documents Section -->
<div class="card p-4 sm:p-6 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl space-y-5">
<div class="flex items-center gap-2 text-primary font-bold text-lg border-b border-surface-100 dark:border-surface-800 pb-3">
<i class="pi pi-file-pdf text-xl"></i>
<span>اسناد و مدارک تصویری / پی‌دی‌اف ملک</span>
</div>
<ImageUploader v-model="documentUrlsWithData" uploadUrl="/api/files/admin/upload-file" @uploaded="onDocumentUploaded" />
</div>
</div>
<!-- Sidebar Area -->
<div class="lg:col-span-4 space-y-6 w-full">
<!-- Location Map Card -->
<div class="card p-4 sm:p-6 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl space-y-4">
<div class="flex items-center gap-2 text-primary font-bold text-lg border-b border-surface-100 dark:border-surface-800 pb-3">
<i class="pi pi-map-marker text-xl"></i>
<span>موقعیت روی نقشه</span>
</div>
<div class="space-y-3">
<div class="grid grid-cols-3 gap-2">
<InputText v-model="easting" placeholder="Easting" class="!rounded-xl text-xs" />
<InputText v-model="northing" placeholder="Northing" class="!rounded-xl text-xs" />
<InputText v-model="zone" placeholder="Zone" class="!rounded-xl text-xs" />
</div>
<Button label="تبدیل UTM" size="small" severity="secondary" rounded @click="convertUTMtoLatLng" class="w-full" />
<div class="h-[600px] rounded-xl overflow-hidden border border-surface-200 dark:border-surface-800">
<MapComponent
ref="mapRef"
:locked="!!property.nationalGeoCode?.trim()"
@marker-updated="handleMarkerUpdated"
@cleared="property.nationalGeoCode = ''"
/>
</div>
</div>
</div>
<!-- Main Image Card -->
<div class="card p-4 sm:p-6 bg-surface-0 dark:bg-surface-900 shadow-sm border border-surface-200 dark:border-surface-800 rounded-2xl space-y-4">
<div class="flex items-center gap-2 text-primary font-bold text-lg border-b border-surface-100 dark:border-surface-800 pb-3">
<i class="pi pi-image text-xl"></i>
<span>تصاویر ملک</span>
</div>
<ImageUploader v-model="mainImageUrlsWithData" uploadUrl="/api/files/admin/upload-file" @uploaded="onMainImageUploaded" />
</div>
</div>
</div>
</div>
</template>
<style scoped>
.dir-rtl {
direction: rtl;
}
</style>
@@ -1,9 +1,8 @@
<script setup>
import { ProductService } from '@/service/ProductService';
import { FilterMatchMode } from '@primevue/core/api';
import { useToast } from 'primevue/usetoast';
import { onMounted, ref, watch } from 'vue';
import { BelongingService } from '@/service/BelongingService';
import { PropertyService } from '@/service/PropertyService';
import { useRouter, useRoute } from 'vue-router';
import Chip from 'primevue/chip';
import InputIcon from 'primevue/inputicon';
@@ -12,6 +11,7 @@ import LoadingCheck from '@/components/LoadingCheck.vue';
import { useConfirm } from 'primevue/useconfirm';
import ConfirmPopup from 'primevue/confirmpopup';
import axios from 'axios';
const deleteConfirm = useConfirm();
onMounted(() => {
loadData();
@@ -19,12 +19,12 @@ onMounted(() => {
const toast = useToast();
const dt = ref();
const belongings = ref();
const properties = ref();
const productDialog = ref(false);
const deleteProductDialog = ref(false);
const deleteProductsDialog = ref(false);
const belonging = ref({});
const selectedBelongings = ref();
const property = ref({});
const selectedProperties = ref();
const filters = ref({
global: { value: null, matchMode: FilterMatchMode.CONTAINS }
});
@@ -37,8 +37,8 @@ function hideDialog() {
const router = useRouter();
function editBelonging(belongingId) {
router.push('/belonging/edit-belonging/' + belongingId);
function editProperty(propertyId) {
router.push('/property/edit-property/' + propertyId);
}
const route = useRoute();
@@ -50,17 +50,15 @@ const pagesCount = ref(0);
let searchTimeout;
// Update your search watcher
watch(searchPhrase, (newPhrase, oldPhrase) => {
if (newPhrase !== oldPhrase) {
// Debounce search to avoid too many requests
if (searchTimeout) clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
router.push({
query: {
...route.query,
query: newPhrase || undefined,
page: 1 // Reset to first page on new search
page: 1
}
});
}, 300);
@@ -77,8 +75,9 @@ watch(
},
{ deep: true }
);
const handleRemoveSearch = () => {
removeFromQuery('searchPhrase'); // Ensure 'searchPhrase' is the correct key
removeFromQuery('searchPhrase');
searchPhrase.value = '';
};
@@ -110,10 +109,9 @@ const onPageChange = (event) => {
};
const loadData = async () => {
await BelongingService.searchBelongings(route.query)
await PropertyService.searchProperties(route.query)
.then((response) => {
console.log('response', response);
belongings.value = response.belongings || response;
properties.value = response.properties || response.belongings || response;
totalCount.value = response.totalCount || response.length || 0;
pagesCount.value = Math.ceil(totalCount.value / per_page.value);
})
@@ -128,34 +126,29 @@ const indexingFinished = ref(false);
const indexingMessage = ref('در حال ایندکس...');
const animationKey = ref(0);
// Function to handle indexing
const indexBelongings = async () => {
const indexProperties = async () => {
loading.value = true;
indexingFinished.value = false;
try {
// Your indexing logic here
// await new Promise((resolve) => setTimeout(resolve, 2000)); // Simulate API call
await BelongingService.indexBelongings();
// When indexing completes
await PropertyService.indexProperties();
loadData();
indexingFinished.value = true;
indexingMessage.value = 'ایندکس با موفقیت انجام شد';
} catch (error) {
indexingMessage.value = 'خطا در ایندکس';
} finally {
// Reset after some time
setTimeout(() => {
loading.value = false;
animationKey.value++; // Force re-render of animation
animationKey.value++;
}, 3000);
}
};
const confirmDeleteBelonging = (id, event) => {
const confirmDeleteProperty = (id, event) => {
deleteConfirm.require({
target: event.currentTarget,
message: `آیا از حذف این دارایی اطمینان دارید؟`,
message: `آیا از حذف این ملک اطمینان دارید؟`,
icon: 'pi pi-exclamation-triangle',
rejectProps: {
label: 'خیر',
@@ -167,7 +160,7 @@ const confirmDeleteBelonging = (id, event) => {
},
accept: async () => {
try {
let url = '/api/belongings/admin/delete/' + id;
let url = '/api/properties/admin/delete/' + id;
const method = 'delete';
const config = {
method,
@@ -175,21 +168,16 @@ const confirmDeleteBelonging = (id, event) => {
withCredentials: true
};
const response = await axios(config);
console.log(url, response);
toast.add({ severity: 'success', summary: 'موفقیت آمیز', detail: 'حذف دارایی با موفقیت انجام شد', life: 3000 });
toast.add({ severity: 'success', summary: 'موفقیت آمیز', detail: 'حذف ملک با موفقیت انجام شد', life: 3000 });
await indexBelongings();
await indexProperties();
await loadData();
} catch (error) {
// handle error
toast.add({ severity: 'error', summary: ' خطا در انجام عملیات ', detail: error.response?.data?.message || 'خطایی در حذف دارایی', life: 3000 });
toast.add({ severity: 'error', summary: ' خطا در انجام عملیات ', detail: error.response?.data?.message || 'خطایی در حذف ملک', life: 3000 });
console.log(error);
}
},
reject: () => {
// User rejected the confirmation, do nothing
}
reject: () => {}
});
};
</script>
@@ -200,10 +188,10 @@ const confirmDeleteBelonging = (id, event) => {
<div class="card">
<Toolbar class="mb-6">
<template #start>
<Button label="ساخت دارایی جدید" icon="pi pi-plus" severity="secondary" class="mr-2 mx-3" @click="router.push('/belonging/create-belonging')" />
<Button @click="indexBelongings" :disabled="loading" severity="secondary mx-3" class="indexing-button">
<Button label="ساخت ملک جدید" icon="pi pi-plus" severity="secondary" class="mr-2 mx-3" @click="router.push('/property/create-property')" />
<Button @click="indexProperties" :disabled="loading" severity="secondary mx-3" class="indexing-button">
<div class="button-content">
<div v-if="!loading">ایندکس کردن محصولات</div>
<div v-if="!loading">ایندکس کردن املاک</div>
<div v-else class="loading-content flex">
<LoadingCheck :key="animationKey" :is-complete="indexingFinished" />
<Transition enter-active-class="animate__animated animate__fadeIn animate__fast" leave-active-class="animate__animated animate__fadeOut animate__fast" mode="out-in">
@@ -219,8 +207,8 @@ const confirmDeleteBelonging = (id, event) => {
<DataTable
ref="dt"
v-model:selection="selectedBelongings"
:value="belongings"
v-model:selection="selectedProperties"
:value="properties"
dataKey="id"
:paginator="true"
:rows="per_page"
@@ -230,11 +218,11 @@ const confirmDeleteBelonging = (id, event) => {
@page="onPageChange($event)"
paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
:rowsPerPageOptions="[20, 40, 80]"
currentPageReportTemplate="نمایش {first} تا {last} از {totalRecords} دارایی"
currentPageReportTemplate="نمایش {first} تا {last} از {totalRecords} ملک"
>
<template #header>
<div class="flex flex-wrap gap-2 items-center justify-start">
<h4 class="m-0">مدیریت اموال</h4>
<h4 class="m-0">مدیریت املاک</h4>
<IconField>
<InputIcon>
<i class="pi pi-search" />
@@ -248,11 +236,12 @@ const confirmDeleteBelonging = (id, event) => {
<Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
<Column header="تصویر">
<template #body="slotProps">
<img :src="`${slotProps.data.imageUrl}`" :alt="slotProps.data.name" class="rounded" style="max-width: 64px" crossorigin="use-credentials" />
<img :src="`${slotProps.data.imageUrl || slotProps.data.mainImageUrls?.[0]}`" :alt="slotProps.data.name" class="rounded" style="max-width: 64px" crossorigin="use-credentials" />
</template>
</Column>
<Column field="belongingCode" header="کد" style="min-width: 4rem"></Column>
<Column field="name" header="نام" sortable style="min-width: 16rem"></Column>
<Column field="propertyCode" header="کد" style="min-width: 4rem"></Column>
<Column field="nationalGeoCode" header="شناسه ملی جغرافیایی" style="min-width: 10rem"></Column>
<Column field="name" header="نام" sortable style="min-width: 14rem"></Column>
<Column field="category" header="دسته بندی" sortable style="min-width: 6rem">
<template #body="slotProps">
{{ slotProps.data.category?.nativeName || slotProps.data.nativeCategory }}
@@ -260,36 +249,11 @@ const confirmDeleteBelonging = (id, event) => {
</Column>
<Column :exportable="false" style="min-width: 12rem">
<template #body="slotProps">
<Button icon="pi pi-pencil" outlined rounded class="mr-2 mx-3" @click="editBelonging(slotProps.data._id)" />
<Button icon="pi pi-trash" outlined rounded severity="danger" class="mx-3" @click="confirmDeleteBelonging(slotProps.data._id, $event)" />
<Button icon="pi pi-pencil" outlined rounded class="mr-2 mx-3" @click="editProperty(slotProps.data._id)" />
<Button icon="pi pi-trash" outlined rounded severity="danger" class="mx-3" @click="confirmDeleteProperty(slotProps.data._id, $event)" />
</template>
</Column>
</DataTable>
</div>
<Dialog v-model:visible="deleteProductDialog" :style="{ width: '450px' }" header="Confirm" :modal="true">
<div class="flex items-center gap-4">
<i class="pi pi-exclamation-triangle !text-3xl" />
<span v-if="product"
>Are you sure you want to delete <b>{{ product.name }}</b
>?</span
>
</div>
<template #footer>
<Button label="خیر" icon="pi pi-times" text @click="deleteProductDialog = false" />
<Button label="بله" icon="pi pi-check" @click="deleteProduct" />
</template>
</Dialog>
<Dialog v-model:visible="deleteProductsDialog" :style="{ width: '450px' }" header="Confirm" :modal="true">
<div class="flex items-center gap-4">
<i class="pi pi-exclamation-triangle !text-3xl" />
<span v-if="product">Are you sure you want to delete the selected products?</span>
</div>
<template #footer>
<Button label="No" icon="pi pi-times" text @click="deleteProductsDialog = false" />
<Button label="Yes" icon="pi pi-check" text @click="deleteselectedBelongings" />
</template>
</Dialog>
</div>
</template>
@@ -280,7 +280,7 @@ const toggle = (event, data) => {
</template>
<Column field="_id" header="شناسه" sortable style="width: 10%"></Column>
<Column field="belongingName" header="دارایی" sortable style="width: 15%"></Column>
<Column field="belongingName" header="ملک" sortable style="width: 15%"></Column>
<Column field="type" header="نوع تراکنش" sortable style="width: 15%">
<template #body="{ data }">
+498 -75
View File
@@ -1,141 +1,564 @@
<template>
<div class="map-container">
<!-- Search box -->
<div class="search-container">
<input v-model="searchQuery" @keyup.enter="handleSearch" placeholder="جستجو" class="search-input" />
<div ref="mapContainer" class="map-container" :class="{ 'map-fullscreen': isFullscreen }">
<!-- ── Top-left: Search bar ── -->
<div class="map-overlay search-bar-wrap">
<span class="search-icon">🔍</span>
<input
v-model="searchQuery"
@keyup.enter="handleSearch"
placeholder="جستجو روی نقشه..."
class="search-input"
/>
<button v-if="searchQuery" class="search-clear" @click="searchQuery = ''" title="پاک کردن">✕</button>
</div>
<l-map ref="map" v-model:zoom="zoom" :center="center" :use-global-leaflet="false" @click="handleClick($event)">
<!-- Base layers -->
<l-control-layers position="topright" />
<!-- ── Top-right: Action buttons ── -->
<div class="map-overlay action-buttons">
<!-- Fullscreen toggle -->
<button class="map-btn" @click="toggleFullscreen" :title="isFullscreen ? 'خروج از تمام‌صفحه' : 'تمام‌صفحه'">
<!-- Exit fullscreen icon -->
<svg v-if="isFullscreen" xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M8 3v3a2 2 0 0 1-2 2H3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/>
<path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M16 21v-3a2 2 0 0 1 2-2h3"/>
</svg>
<!-- Enter fullscreen icon -->
<svg v-else xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<path d="M3 7V3h4"/><path d="M21 7V3h-4"/>
<path d="M3 17v4h4"/><path d="M21 17v4h-4"/>
</svg>
</button>
<!-- Locate me -->
<button class="map-btn map-btn-locate" @click="locateMe" title="موقعیت من" :class="{ locating: isLocating }">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="3"/>
<path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>
<circle cx="12" cy="12" r="7" opacity="0.3"/>
</svg>
</button>
<!-- Clear marker -->
<button v-if="marker.length > 0" class="map-btn map-btn-danger" @click="clearMarker" title="حذف نشانگر">
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6"/>
<path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
<path d="M10 11v6M14 11v6"/>
<path d="M9 6V4h6v2"/>
</svg>
</button>
</div>
<!-- OpenStreetMap layer (default) -->
<l-tile-layer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" layer-type="base" name="نمای نقشه ای" :attribution="attribution" />
<!-- ── Bottom-left: Coordinate readout ── -->
<div v-if="hoverCoords" class="map-overlay coords-readout">
<svg xmlns="http://www.w3.org/2000/svg" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="opacity:0.7;flex-shrink:0">
<circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>
</svg>
<span>{{ hoverCoords.lat.toFixed(6) }}, {{ hoverCoords.lon.toFixed(6) }}</span>
</div>
<!-- Satellite layer (optional) -->
<!-- ── Bottom-right: Marker info pill ── -->
<div v-if="marker.length > 0" class="map-overlay marker-info">
<svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="#6366f1" stroke="#6366f1" stroke-width="1">
<path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
</svg>
<span class="marker-coords">{{ marker[0].toFixed(5) }}, {{ marker[1].toFixed(5) }}</span>
<button class="copy-btn" @click="copyCoords" :title="copied ? 'کپی شد!' : 'کپی مختصات'">
<svg v-if="!copied" xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
<rect x="9" y="9" width="13" height="13" rx="2"/>
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
</svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#22c55e" stroke-width="2.5">
<polyline points="20 6 9 17 4 12"/>
</svg>
</button>
</div>
<!-- Lock Indicator -->
<div v-if="locked" class="map-overlay lock-indicator">
🔒 قفل شده
</div>
<!-- ── Leaflet Map ── -->
<l-map
ref="map"
v-model:zoom="zoom"
:center="center"
:use-global-leaflet="false"
style="height: 100%; width: 100%;"
@click="handleClick($event)"
@mousemove="handleMouseMove($event)"
@mouseout="hoverCoords = null"
>
<!-- Layer switcher -->
<l-control-layers position="bottomright" />
<!-- OpenStreetMap -->
<l-tile-layer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
layer-type="base"
name="نمای نقشه‌ای"
:attribution="attribution"
/>
<!-- Satellite -->
<l-tile-layer
:visible="false"
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
layer-type="base"
name="نمای ماهواره ای"
attribution="Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community"
name="نمای ماهواره‌ای"
attribution="Tiles &copy; Esri"
/>
<!-- Marker -->
<!-- Scale control -->
<l-control-scale position="bottomleft" :imperial="false" :maxWidth="150" />
<!-- Marker with rich popup -->
<l-marker v-if="marker.length > 0" :lat-lng="marker">
<l-popup> نقطه انتخاب شده </l-popup>
<l-popup>
<div class="popup-content">
<strong>📍 نقطه انتخاب‌شده</strong><br />
<span>عرض: {{ marker[0].toFixed(6) }}</span><br />
<span>طول: {{ marker[1].toFixed(6) }}</span>
</div>
</l-popup>
</l-marker>
</l-map>
<!-- Locating spinner overlay -->
<div v-if="isLocating" class="locating-overlay">
<div class="locating-spinner"></div>
<span>در حال تعیین موقعیت...</span>
</div>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
import { ref, watch, nextTick } from 'vue';
import 'leaflet/dist/leaflet.css';
import { LMap, LTileLayer, LMarker, LPopup, LControlLayers } from '@vue-leaflet/vue-leaflet';
import { LMap, LTileLayer, LMarker, LPopup, LControlLayers, LControlScale } from '@vue-leaflet/vue-leaflet';
import axios from 'axios';
// Props and emits
// ── Props & Emits ──────────────────────────────────────────────────────────
const props = defineProps({
modelValue: {
type: Array,
default: () => []
},
lon: {
type: Number
},
lat: {
type: Number
}
modelValue: { type: Array, default: () => [] },
lon: { type: Number },
lat: { type: Number },
locked: { type: Boolean, default: false }
});
const emit = defineEmits(['update:modelValue']);
const emit = defineEmits(['update:modelValue', 'marker-updated', 'cleared']);
// Map configuration
// ── State ──────────────────────────────────────────────────────────────────
const zoom = ref(12);
const center = ref([31.3183, 48.6706]);
const attribution = ref('Nilgoon Team');
const attribution = ref('© OpenStreetMap contributors');
const marker = ref([...props.modelValue]);
const map = ref(null);
const mapContainer = ref(null);
// Search functionality
const searchQuery = ref('');
const hoverCoords = ref(null);
const copied = ref(false);
const isLocating = ref(false);
const isFullscreen = ref(false);
const searchByCoordinates = (lat, lon) => {
if (lat && lon) {
center.value = [parseFloat(lat), parseFloat(lon)];
zoom.value = 10;
marker.value = [parseFloat(lat), parseFloat(lon)];
emit('update:modelValue', marker.value);
// ── Core: set marker + flyTo ───────────────────────────────────────────────
const setMarker = (latVal, lonVal) => {
if (latVal !== null && lonVal !== null && !isNaN(latVal) && !isNaN(lonVal)) {
const newCoords = [parseFloat(latVal), parseFloat(lonVal)];
marker.value = newCoords;
center.value = newCoords;
zoom.value = 16;
emit('update:modelValue', newCoords);
emit('marker-updated', newCoords);
nextTick(() => {
if (map.value?.leafletObject) {
map.value.leafletObject.flyTo(newCoords, 16, { animate: true, duration: 0.8 });
}
});
}
};
defineExpose({
searchByCoordinates
const clearMarker = () => {
marker.value = [];
emit('update:modelValue', []);
emit('marker-updated', []);
emit('cleared'); // notify parent to also reset nationalGeoCode
};
// ── Fullscreen ─────────────────────────────────────────────────────────────
const toggleFullscreen = () => {
if (!isFullscreen.value) {
if (mapContainer.value?.requestFullscreen) {
mapContainer.value.requestFullscreen();
} else if (mapContainer.value?.webkitRequestFullscreen) {
mapContainer.value.webkitRequestFullscreen();
}
} else {
if (document.exitFullscreen) document.exitFullscreen();
else if (document.webkitExitFullscreen) document.webkitExitFullscreen();
}
};
document.addEventListener('fullscreenchange', () => {
isFullscreen.value = !!document.fullscreenElement;
// Invalidate map size so Leaflet redraws correctly after fullscreen
nextTick(() => map.value?.leafletObject?.invalidateSize());
});
const handleSearch = async () => {
if (!searchQuery.value) return;
// ── Locate Me ─────────────────────────────────────────────────────────────
const locateMe = () => {
if (!navigator.geolocation) return;
isLocating.value = true;
navigator.geolocation.getCurrentPosition(
(pos) => {
isLocating.value = false;
setMarker(pos.coords.latitude, pos.coords.longitude);
},
() => { isLocating.value = false; },
{ timeout: 10000, enableHighAccuracy: true }
);
};
try {
const response = await axios.get(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(searchQuery.value)}`);
if (response.data && response.data.length > 0) {
const { lat, lon } = response.data[0];
center.value = [parseFloat(lat), parseFloat(lon)];
zoom.value = 16;
marker.value = [parseFloat(lat), parseFloat(lon)];
emit('update:modelValue', marker.value);
}
} catch (error) {
console.error('Search failed:', error);
// ── Mouse hover coords ─────────────────────────────────────────────────────
const handleMouseMove = (event) => {
if (event?.latlng) {
hoverCoords.value = { lat: event.latlng.lat, lon: event.latlng.lng };
}
};
// Watch for changes in modelValue and sync with marker
// ── Copy coords ────────────────────────────────────────────────────────────
const copyCoords = () => {
if (!marker.value.length) return;
const text = `${marker.value[0].toFixed(6)}, ${marker.value[1].toFixed(6)}`;
navigator.clipboard?.writeText(text).then(() => {
copied.value = true;
setTimeout(() => (copied.value = false), 2000);
});
};
// ── Search ─────────────────────────────────────────────────────────────────
const searchLocation = async (query) => {
if (!query || typeof query !== 'string') return;
const trimmed = query.trim();
if (!trimmed) return;
// Direct lat,lon pair
const coordMatch = trimmed.match(/^([+-]?\d+(?:\.\d+)?)\s*[\s,]\s*([+-]?\d+(?:\.\d+)?)$/);
if (coordMatch) {
setMarker(parseFloat(coordMatch[1]), parseFloat(coordMatch[2]));
return;
}
// Geocoding
try {
const res = await axios.get(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(trimmed)}&limit=1`);
if (res.data?.length > 0) {
const { lat, lon } = res.data[0];
setMarker(parseFloat(lat), parseFloat(lon));
searchQuery.value = '';
}
} catch (e) {
console.error('Geo search failed:', e);
}
};
const handleSearch = () => searchLocation(searchQuery.value);
// ── Click on map ───────────────────────────────────────────────────────────
const handleClick = (event) => {
// When locked (nationalGeoCode is set), ignore map clicks — use trash to unlock
if (props.locked) return;
const coords = [event.latlng.lat, event.latlng.lng];
marker.value = coords;
emit('update:modelValue', coords);
emit('marker-updated', coords);
};
// ── Sync modelValue prop → marker ──────────────────────────────────────────
watch(
() => props.modelValue,
(newValue) => {
marker.value = [...newValue];
(val) => {
if (Array.isArray(val) && val.length === 2) {
marker.value = [...val];
center.value = [...val];
}
},
{ immediate: true }
);
// Update marker and emit changes to modelValue
const handleClick = (event) => {
marker.value = [event.latlng.lat, event.latlng.lng];
emit('update:modelValue', marker.value);
};
// ── Expose to parent ───────────────────────────────────────────────────────
defineExpose({ searchByCoordinates: setMarker, setCenterAndMarker: setMarker, searchLocation });
</script>
<style scoped>
/* ── Container ──────────────────────────────────────────────────────────── */
.map-container {
font-family: 'Estedad', sans-serif !important;
height: 500px;
height: 100%;
width: 100%;
position: relative;
border-radius: inherit;
}
.leaflet-container {
font-family: 'Estedad', serif !important;
.map-fullscreen {
border-radius: 0 !important;
}
.search-container {
:deep(.leaflet-container) {
font-family: 'Estedad', sans-serif !important;
border-radius: inherit;
}
/* ── Shared overlay pill style ──────────────────────────────────────────── */
.map-overlay {
position: absolute;
top: 10px;
left: 10px;
z-index: 1000;
background: white;
padding: 5px;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
pointer-events: auto;
}
/* ── Search bar ─────────────────────────────────────────────────────────── */
.search-bar-wrap {
top: 12px;
left: 12px;
display: flex;
align-items: center;
gap: 6px;
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border-radius: 12px;
padding: 6px 10px;
box-shadow: 0 4px 16px rgba(0,0,0,0.15);
border: 1px solid rgba(255,255,255,0.6);
max-width: 280px;
}
.search-icon { font-size: 13px; opacity: 0.5; }
.search-input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 250px;
border: none;
outline: none;
background: transparent;
font-family: 'Estedad', sans-serif;
font-size: 13px;
width: 210px;
color: #1a1a2e;
direction: rtl;
}
.search-input::placeholder { color: #9ca3af; }
.search-clear {
background: none;
border: none;
cursor: pointer;
color: #9ca3af;
font-size: 12px;
padding: 0 2px;
line-height: 1;
transition: color 0.15s;
}
.search-clear:hover { color: #ef4444; }
/* ── Action buttons (top-right) ─────────────────────────────────────────── */
.action-buttons {
top: 12px;
right: 12px; /* layer control is now at bottomright, so no offset needed */
display: flex;
flex-direction: column;
gap: 6px;
}
.map-btn {
width: 36px;
height: 36px;
border-radius: 10px;
border: none;
background: #6366f1;
color: #fff;
box-shadow: 0 3px 10px rgba(99,102,241,0.35);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.15s, transform 0.1s, box-shadow 0.15s;
}
.map-btn:hover {
background: #4f46e5;
box-shadow: 0 6px 18px rgba(79,70,229,0.45);
transform: scale(1.06);
}
.map-btn:active { transform: scale(0.95); }
.map-btn-locate {
background: #0ea5e9;
box-shadow: 0 3px 10px rgba(14,165,233,0.35);
}
.map-btn-locate:hover {
background: #0284c7;
box-shadow: 0 6px 18px rgba(2,132,199,0.45);
}
.map-btn.locating { animation: pulse-btn 1s infinite; }
.map-btn-danger {
background: #ef4444;
box-shadow: 0 3px 10px rgba(239,68,68,0.35);
}
.map-btn-danger:hover {
background: #dc2626;
box-shadow: 0 6px 18px rgba(220,38,38,0.45);
}
@keyframes pulse-btn {
0%, 100% { box-shadow: 0 0 0 0 rgba(14,165,233,0.5); }
50% { box-shadow: 0 0 0 8px rgba(14,165,233,0); }
}
/* ── Coordinate readout (bottom-left) ────────────────────────────────────────────── */
.coords-readout {
bottom: 62px; /* above the Leaflet scale bar + attribution */
left: 12px;
display: flex;
align-items: center;
gap: 5px;
background: rgba(15, 15, 35, 0.8);
backdrop-filter: blur(6px);
-webkit-backdrop-filter: blur(6px);
color: #c7d2fe;
font-size: 11px;
font-family: 'Courier New', monospace;
padding: 5px 10px;
border-radius: 8px;
letter-spacing: 0.04em;
pointer-events: none;
}
/* ── Marker info pill (bottom-right) ─────────────────────────────────────────────── */
.marker-info {
bottom: 62px; /* above the Leaflet layer-switcher control */
right: 12px;
display: flex;
align-items: center;
gap: 6px;
background: rgba(255,255,255,0.95);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border-radius: 20px;
padding: 5px 12px;
box-shadow: 0 4px 14px rgba(0,0,0,0.14);
border: 1px solid rgba(255,255,255,0.6);
font-size: 12px;
color: #1a1a2e;
max-width: 260px;
}
.marker-pin-icon { font-size: 14px; }
.marker-coords { font-family: 'Courier New', monospace; font-size: 11px; }
.copy-btn {
background: none;
border: none;
cursor: pointer;
font-size: 14px;
color: #6366f1;
padding: 0;
transition: transform 0.1s;
}
.copy-btn:hover { transform: scale(1.2); }
/* ── Locating overlay ───────────────────────────────────────────────────── */
.locating-overlay {
position: absolute;
inset: 0;
z-index: 1100;
background: rgba(255,255,255,0.55);
backdrop-filter: blur(4px);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
font-size: 14px;
color: #4f46e5;
font-weight: 600;
border-radius: inherit;
}
.locating-spinner {
width: 36px;
height: 36px;
border: 3px solid rgba(99,102,241,0.2);
border-top-color: #6366f1;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* ── Lock badge ──────────────────────────────────────────────────────────── */
.lock-badge {
top: 12px;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 5px;
background: rgba(99, 102, 241, 0.15);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border: 1px solid rgba(99, 102, 241, 0.35);
border-radius: 20px;
padding: 4px 12px;
font-size: 11px;
color: #6366f1;
font-weight: 600;
pointer-events: none;
white-space: nowrap;
}
</style>
<!-- Dark mode overrides (app-dark class on <html>) -->
<style>
/* Search bar */
.app-dark .search-bar-wrap {
background: rgba(30, 30, 50, 0.92) !important;
border-color: rgba(99, 102, 241, 0.25) !important;
box-shadow: 0 4px 16px rgba(0,0,0,0.4) !important;
}
.app-dark .search-input {
color: #e2e8f0 !important;
}
.app-dark .search-input::placeholder {
color: #6b7280 !important;
}
.app-dark .search-icon {
filter: invert(1) brightness(0.7);
}
/* Marker info pill */
.app-dark .marker-info {
background: rgba(30, 30, 50, 0.92) !important;
border-color: rgba(99, 102, 241, 0.25) !important;
color: #e2e8f0 !important;
box-shadow: 0 4px 14px rgba(0,0,0,0.4) !important;
}
/* Locating overlay */
.app-dark .locating-overlay {
background: rgba(15, 15, 30, 0.7) !important;
color: #a5b4fc !important;
}
.app-dark .locating-spinner {
border-color: rgba(99,102,241,0.15) !important;
border-top-color: #818cf8 !important;
}
</style>
+4
View File
@@ -20,5 +20,9 @@ export default defineConfig({
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
port: 5173,
host: true
}
});