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

View File

@ -21,6 +21,10 @@ const createEmptyCodeForm = () => ({
product: '', product: '',
unit: '', unit: '',
status: '', status: '',
createdBy: '',
createdOn: '',
updated: '',
description: ''
}); });
// Toast notification component // Toast notification component
@ -124,7 +128,35 @@ const IsicHsCodes = () => {
if (products.length > 0) { if (products.length > 0) {
const formattedData = await Promise.all(products.map(async (product) => { const formattedData = await Promise.all(products.map(async (product) => {
// Try to get creator's name if available // 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) { if (product.created_by) {
try { try {
// If the API returns the creator's name in the product data, use it // 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', unit: product.unit?.uom || 'N/A',
estimatedMapped: 0, estimatedMapped: 0,
createdBy: createdByName, createdBy: createdByName,
createdById: product.created_by || null, createdOn: createdDate || null,
updated: product.updated_at updated: updatedDate,
? new Date(product.updated_at).toLocaleDateString() createdById: createdById, // Store the ID for reference
: '-',
status: product.is_active ? 'Active' : 'Inactive', status: product.is_active ? 'Active' : 'Inactive',
description: product.hs_description || '', description: product.hs_description || '',
_createdAt: product.created_at,
_updatedAt: product.updated_at
}; };
})); }));
setRowsData(formattedData); setRowsData(formattedData);
@ -194,16 +228,34 @@ const IsicHsCodes = () => {
setCurrentPage(1); // Reset to first page when searching setCurrentPage(1); // Reset to first page when searching
}, [searchTerm, rowsData]); }, [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.code,
item.product, item.product,
item.unit, item.unit,
item.estimatedMapped, item.estimatedMapped,
item.createdBy || '', displayName, // Use the resolved display name
item.updated, item.updated || item.createdOn || '-',
item.status, item.status,
'actions', 'actions',
]); ];
});
const handleView = async (index) => { const handleView = async (index) => {
const selected = rowsData[index]; const selected = rowsData[index];
@ -226,7 +278,10 @@ const IsicHsCodes = () => {
product: product.product_name || '', product: product.product_name || '',
unit: product.unit_id ? String(product.unit_id) : '', unit: product.unit_id ? String(product.unit_id) : '',
status: product.is_active ? 'Active' : 'Inactive', 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'); setModalMode('view');
} else { } else {

View File

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