bug fixed in admin

This commit is contained in:
Malini 2025-11-06 23:45:36 +05:30
parent b5f8cb4014
commit b25e35d4c9
3 changed files with 232 additions and 103 deletions

View File

@ -525,8 +525,15 @@ const CompanyProfile = () => {
/>
<SelectField
label="Emirate"
value={form.contactEmirate}
onChange={handleFormChange('contactEmirate')}
value={form.contactEmirateId} // Changed from form.contactEmirate to form.contactEmirateId
onChange={(e) => {
// When emirate changes, update both the ID and name
const selectedEmirate = emirateOptions.find(opt => opt.value === e.target.value);
handleFormChange('contactEmirateId')(e);
handleFormChange('contactEmirate')({
target: { value: selectedEmirate?.label || '' }
});
}}
options={emirateOptions}
placeholder="Select Emirate"
width="100%"
@ -535,10 +542,16 @@ const CompanyProfile = () => {
/>
<SelectField
label="City/Town"
value={form.contactCityTown}
onChange={handleFormChange('contactCityTown')}
value={form.contactCityTownId}
onChange={(e) => {
const selectedCity = contactCityOptions.find(opt => opt.value === e.target.value);
handleFormChange('contactCityTownId')(e);
handleFormChange('contactCityTown')({
target: { value: selectedCity?.label || '' }
});
}}
options={contactCityOptions}
placeholder="Select city or town"
placeholder="Select City/Town"
width="100%"
required
error={fieldErrors.contactCityTown}
@ -654,10 +667,17 @@ const CompanyProfile = () => {
/>
<SelectField
label="Emirate"
value={form.corporateEmirate}
onChange={handleFormChange('corporateEmirate')}
value={form.corporateEmirateId} // Changed from form.corporateEmirate to form.corporateEmirateId
onChange={(e) => {
// When emirate changes, update both the ID and name
const selectedEmirate = emirateOptions.find(opt => opt.value === e.target.value);
handleFormChange('corporateEmirateId')(e);
handleFormChange('corporateEmirate')({
target: { value: selectedEmirate?.label || '' }
});
}}
options={emirateOptions}
placeholder="Select emirate"
placeholder="Select Emirate"
width="100%"
required
error={fieldErrors.corporateEmirate}
@ -665,10 +685,16 @@ const CompanyProfile = () => {
/>
<SelectField
label="City/Town"
value={form.corporateCityTown}
onChange={handleFormChange('corporateCityTown')}
value={form.corporateCityTownId}
onChange={(e) => {
const selectedCity = corporateCityOptions.find(opt => opt.value === e.target.value);
handleFormChange('corporateCityTownId')(e);
handleFormChange('corporateCityTown')({
target: { value: selectedCity?.label || '' }
});
}}
options={corporateCityOptions}
placeholder="Select city or town"
placeholder="Select City/Town"
width="100%"
required
error={fieldErrors.corporateCityTown}
@ -1262,7 +1288,7 @@ const corporateFieldKeys = Object.values(contactToCorporateMap);
isicCode: item?.isic_code ?? '',
industryCodeBusiness: item?.industry_code ?? base.industryCodeBusiness,
industryCodeCurrent: item?.isic_code ?? base.industryCodeCurrent,
industryDescription: item?.industry_description ?? base.industryDescription,
industryDescription: item?.description ?? base.industryDescription,
establishmentId: item?.establishment_code ?? '',
contactAddress: item?.establishment_address ?? base.contactAddress,
contactCityTown: establishmentCityName || base.contactCityTown,
@ -1710,45 +1736,92 @@ const requiredFields = [
if (next.corporateSameAs && contactToCorporateMap[field]) {
next[contactToCorporateMap[field]] = value;
}
if (field === 'contactEmirate') {
const foundOption = emirateOptions.find((option) => option.value === value || option.label === value);
if (foundOption) {
next.contactEmirate = foundOption.label;
next.contactEmirateId = foundOption.value;
} else {
next.contactEmirateId = '';
}
loadContactCityOptions(next.contactEmirateId);
next.contactCityTown = '';
next.contactCityTownId = '';
// if (field === 'contactEmirate') {
// const foundOption = emirateOptions.find((option) => option.value === value || option.label === value);
// if (foundOption) {
// next.contactEmirate = foundOption.label;
// next.contactEmirateId = foundOption.value;
// } else {
// next.contactEmirateId = '';
// }
// loadContactCityOptions(next.contactEmirateId);
// next.contactCityTown = '';
// next.contactCityTownId = '';
// }
// Handle emirate changes
if (field === 'contactEmirateId') {
const selectedEmirate = emirateOptions.find(opt => opt.value === value);
if (selectedEmirate) {
next.contactEmirate = selectedEmirate.label;
next.contactEmirateId = selectedEmirate.value;
loadContactCityOptions(selectedEmirate.value);
} else {
next.contactEmirate = '';
next.contactEmirateId = '';
}
if (field === 'corporateEmirate') {
const foundOption = emirateOptions.find((option) => option.value === value || option.label === value);
if (foundOption) {
next.corporateEmirate = foundOption.label;
next.corporateEmirateId = foundOption.value;
} else {
next.corporateEmirateId = '';
}
loadCorporateCityOptions(next.corporateEmirateId);
next.corporateCityTown = '';
next.corporateCityTownId = '';
next.contactCityTown = '';
next.contactCityTownId = '';
}
// if (field === 'corporateEmirate') {
// const foundOption = emirateOptions.find((option) => option.value === value || option.label === value);
// if (foundOption) {
// next.corporateEmirate = foundOption.label;
// next.corporateEmirateId = foundOption.value;
// } else {
// next.corporateEmirateId = '';
// }
// loadCorporateCityOptions(next.corporateEmirateId);
// next.corporateCityTown = '';
// next.corporateCityTownId = '';
// }
if (field === 'corporateEmirateId') {
const selectedEmirate = emirateOptions.find(opt => opt.value === value);
if (selectedEmirate) {
next.corporateEmirate = selectedEmirate.label;
next.corporateEmirateId = selectedEmirate.value;
loadCorporateCityOptions(selectedEmirate.value);
} else {
next.corporateEmirate = '';
next.corporateEmirateId = '';
}
if (field === 'contactCityTown') {
const foundCity = contactCityOptions.find((option) => option.value === value || option.label === value);
if (foundCity) {
next.contactCityTown = foundCity.label;
next.contactCityTownId = foundCity.value;
next.corporateCityTown = '';
next.corporateCityTownId = '';
}
// if (field === 'contactCityTown') {
// const foundCity = contactCityOptions.find((option) => option.value === value || option.label === value);
// if (foundCity) {
// next.contactCityTown = foundCity.label;
// next.contactCityTownId = foundCity.value;
// } else {
// next.contactCityTownId = '';
// }
// }
if (field === 'contactCityTownId') {
const selectedCity = contactCityOptions.find(opt => opt.value === value);
if (selectedCity) {
next.contactCityTown = selectedCity.label;
next.contactCityTownId = selectedCity.value;
} else {
next.contactCityTown = '';
next.contactCityTownId = '';
}
}
if (field === 'corporateCityTown') {
const foundCity = corporateCityOptions.find((option) => option.value === value || option.label === value);
if (foundCity) {
next.corporateCityTown = foundCity.label;
next.corporateCityTownId = foundCity.value;
// if (field === 'corporateCityTown') {
// const foundCity = corporateCityOptions.find((option) => option.value === value || option.label === value);
// if (foundCity) {
// next.corporateCityTown = foundCity.label;
// next.corporateCityTownId = foundCity.value;
// } else {
// next.corporateCityTownId = '';
// }
// }
if (field === 'corporateCityTownId') {
const selectedCity = corporateCityOptions.find(opt => opt.value === value);
if (selectedCity) {
next.corporateCityTown = selectedCity.label;
next.corporateCityTownId = selectedCity.value;
} else {
next.corporateCityTown = '';
next.corporateCityTownId = '';
}
}

View File

@ -21,6 +21,10 @@ const createEmptyCodeForm = () => ({
product: '',
unit: '',
status: '',
createdBy: '',
createdOn: '',
updated: '',
description: ''
});
// Toast notification component
@ -124,7 +128,35 @@ const IsicHsCodes = () => {
if (products.length > 0) {
const formattedData = await Promise.all(products.map(async (product) => {
// Try to get creator's name if available
let createdByName = '-';
let createdByName = '-';
const createdById = product.created_by;
// If still not available, try to fetch the creator's name by ID
// if (!createdByName && product.created_by) {
try {
const userProfileStr = sessionStorage.getItem('user_profile');
if (userProfileStr) {
const userProfile = JSON.parse(userProfileStr);
// If the current user is the creator, use their name
if (createdById && createdById === userProfile.id) {
createdByName = userProfile.name || '-';
}
}
} catch (error) {
console.error('Error getting user from session:', error);
}
const createdDate = product.created_at
? new Date(product.created_at).toLocaleDateString('en-GB')
: '-';
const updatedDate = product.updated_at
? new Date(product.updated_at).toLocaleDateString('en-GB')
: createdDate; // Fallback to created date if updated_at is not available
if (product.created_by) {
try {
// If the API returns the creator's name in the product data, use it
@ -141,12 +173,14 @@ const IsicHsCodes = () => {
unit: product.unit?.uom || 'N/A',
estimatedMapped: 0,
createdBy: createdByName,
createdById: product.created_by || null,
updated: product.updated_at
? new Date(product.updated_at).toLocaleDateString()
: '-',
createdOn: createdDate || null,
updated: updatedDate,
createdById: createdById, // Store the ID for reference
status: product.is_active ? 'Active' : 'Inactive',
description: product.hs_description || '',
_createdAt: product.created_at,
_updatedAt: product.updated_at
};
}));
setRowsData(formattedData);
@ -194,16 +228,34 @@ const IsicHsCodes = () => {
setCurrentPage(1); // Reset to first page when searching
}, [searchTerm, rowsData]);
const rows = filteredData.map((item) => [
const rows = filteredData.map((item) => {
// If we only have the ID and it matches the current user, use the current user's name
let displayName = item.createdBy;
if (displayName === '-' && item.createdById) {
try {
const userProfileStr = sessionStorage.getItem('user_profile');
if (userProfileStr) {
const userProfile = JSON.parse(userProfileStr);
if (item.createdById === userProfile.id) {
displayName = userProfile.name || '-';
}
}
} catch (error) {
console.error('Error getting user from session:', error);
}
}
return [
item.code,
item.product,
item.unit,
item.estimatedMapped,
item.createdBy || '',
item.updated,
displayName, // Use the resolved display name
item.updated || item.createdOn || '-',
item.status,
'actions',
]);
];
});
const handleView = async (index) => {
const selected = rowsData[index];
@ -226,7 +278,10 @@ const IsicHsCodes = () => {
product: product.product_name || '',
unit: product.unit_id ? String(product.unit_id) : '',
status: product.is_active ? 'Active' : 'Inactive',
description: product.hs_description || ''
description: product.hs_description || '',
createdBy: selected.createdBy,
createdOn: selected.createdOn,
updated: selected.updated
});
setModalMode('view');
} else {

View File

@ -53,31 +53,20 @@ const UnitMaster = () => {
// }
// };
const fetchUnits = async () => {
const fetchUnits = async () => {
try {
setLoading(true);
const response = await getUnits();
const response = await getUnits();
const unitsData = response.data || [];
// Process units to ensure mapped_products_count is included
const processedUnits = unitsData.map(unit => {
return {
...unit,
mapped_products_count: unit.mapped_products_count !== undefined
? unit.mapped_products_count
: (Array.isArray(unit.productsMapped) ? unit.productsMapped.length : 0)
};
});
// Sort by latest created_at date (newest first)
const sortedUnits = [...processedUnits].sort(
// Sort by latest created_at date (newest first)
const sortedUnits = [...unitsData].sort(
(a, b) => new Date(b.created_at) - new Date(a.created_at)
);
setUnits(sortedUnits);
} catch (error) {
console.error('Error fetching units:', error);
toast.error('Failed to fetch units. Please try again.');
} finally {
setLoading(false);
}
@ -96,7 +85,7 @@ const fetchUnits = async () => {
'Mapped Products',
'Created By',
'Created On',
'Last Updated',
'Last Updated', // New column
'Status',
'Actions',
];
@ -116,15 +105,17 @@ const fetchUnits = async () => {
return [
item.uom || item.unitName, // Unit Name
item.uom_short_name || item.description, // Description
item.mapped_products_count !== undefined ? item.mapped_products_count : '-', // Mapped Products Count
item.mapped_products_count !== undefined
? item.mapped_products_count
: (Array.isArray(item.productsMapped) ? item.productsMapped.length : 0),
item.created_by_name || currentUserName || '-', // Created By
createdDate, // Created On
updatedDate, // Last Update
updatedDate, // Last Update (moved here)
<StatusBadge
status={item.is_active ? 'Active' : 'Inactive'}
tone={item.is_active ? 'green' : 'gray'}
/>, // Status
'actions', // Actions
/>, // Status
'actions', // Actions
];
});
}, [units, currentUser]);
@ -302,7 +293,7 @@ const fetchUnits = async () => {
const handleSave = async () => {
const selectedProducts = Array.isArray(form.productsMapped) ? form.productsMapped : [];
// Validation checks
// Validation checks
if (!form.unitName) {
toast.error('Please enter Unit Name.');
return;
@ -316,7 +307,7 @@ const handleSave = async () => {
return;
}
// Check for duplicate unit name
// Check for duplicate unit name
const nameExists = units.some(
unit => unit.uom?.toLowerCase().trim() === form.unitName.toLowerCase().trim()
);
@ -426,39 +417,47 @@ const handleSave = async () => {
<div className="px-6 py-3 flex items-center justify-between border-b border-[#E5E7EB]">
<h3 className="text-[16px] font-medium text-[#232528]">Unit Master</h3>
<div className="flex items-center gap-2">
{/* <button className="h-10 px-4 rounded-[6px] bg-[#F7F7F7] border border-[#C3C6CB] text-sm inline-flex items-center gap-2 cursor-pointer">
<img src={downloadIconSrc} alt="Export" className="h-5 w-5" />
<span className="font-medium text-[#232528]">Export CSV</span>
</button> */}
<button
<button
type="button"
onClick={() => {
if (!filteredRows.length) return;
if (!units.length) return;
//Remove "Actions" column from header
// Prepare headers (excluding the last 'Actions' column)
const csvHeader = headers.slice(0, headers.length - 1).join(',');
//Map data fields based on Unit Master structure
const csvRows = filteredRows.map((item) =>
[
item.unitName,
item.description,
// (item.productsMapped || []).join('; '), // Mapped Products
item.mapped_products_count , // Mapped Products Count
item.createdBy,
item.createdOn,
item.status,
// Map each unit to a CSV row
const csvRows = units.map((item) => {
const createdDate = item.created_at
? new Date(item.created_at).toLocaleDateString('en-GB')
: '-';
const updatedDate =
item.updated_at && item.updated_at !== item.created_at
? new Date(item.updated_at).toLocaleDateString('en-GB')
: '-';
const status = item.is_active ? 'Active' : 'Inactive';
const mappedProducts = Array.isArray(item.productsMapped)
? item.productsMapped.join('; ')
: '0';
return [
item.uom || item.unitName || '',
item.uom_short_name || item.description || '',
mappedProducts,
item.created_by_name || currentUser?.name || '-',
createdDate,
updatedDate,
status,
]
.map((value) => `"${String(value ?? '').replace(/"/g, '""')}"`)
.join(',')
);
// Create CSV file
const blob = new Blob([csvHeader + '\n' + csvRows.join('\n')], {
type: 'text/csv;charset=utf-8;',
.join(',');
});
// Download the file
// Combine header and rows into one CSV content
const csvContent = csvHeader + '\n' + csvRows.join('\n');
// Create a downloadable CSV file
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
@ -469,16 +468,18 @@ const handleSave = async () => {
URL.revokeObjectURL(url);
}}
className={`h-10 px-4 rounded-[6px] border text-sm inline-flex items-center gap-2 ${
filteredRows.length
? 'bg-[#F7F7F7] border-[#C3C6CB] text-[#232528] cursor-pointer'
units.length
? 'bg-[#F7F7F7] border-[#C3C6CB] text-[#232528]'
: 'bg-[#F3F4F6] border-[#E5E7EB] text-[#9CA3AF] cursor-not-allowed'
}`}
disabled={!filteredRows.length}
disabled={!units.length}
>
<img src={downloadIconSrc} alt="Export" className="h-5 w-5" />
<span className="font-medium">Export CSV</span>
</button>
<button
type="button"