Your Vue.js component for managing employment history is well-structured, but there are a few areas that could be improved to ensure functionality and maintainability. Below are some recommendations and corrections based on your provided code:
1. Ensure Unique Identifiers for Employment Records
Issue:
You have commented out the id: uuidv4() line in the addEmployment function. This means new employment entries won't have unique IDs, leading to potential issues with v-for keys and form field bindings.
Solution:
Uncomment the uuidv4 import and the id assignment to ensure each employment record has a unique identifier.
// Uncomment the import
import { v4 as uuidv4 } from 'uuid';
// In addEmployment function
const addEmployment = () => {
const newEmployment = {
id: uuidv4(), // Ensure each employment has a unique ID
company: '',
name_of_your_employer: '',
type_of_employment: '',
continuous: false,
country: '',
city: '',
governorate: '',
from_date: '',
to_date: '',
phone: '',
ext: '',
do_we_have_permission_to_contact_this_current_employer: false,
issuing_salary: false,
activity_has_stopped: false,
the_company_has_different_names: false,
different_company_names: '',
name_of_the_last_position_you_held: '',
you_have_a_nicknamecx: false, // Note: This might be a typo
nickname: '',
isValid: true,
validationMessage: ''
};
request.doc.employment_history.push(newEmployment);
nextTick(() => {
openSections[newEmployment.id] = true;
});
};
2. Fix the Typo in the Nickname Field
Issue:
There’s an inconsistency in the naming of the you_have_a_nickname field. In the checkbox, it's referenced as you_have_a_nicknamecx instead of you_have_a_nickname.
Solution:
Standardize the field name to avoid confusion and potential bugs.
<!-- Rename to 'you_have_a_nickname' -->
<CheckBox
:name="`you_have_a_nickname-${employment.id}`"
:id="`you_have_a_nickname-${employment.id}`"
@input-change="value => handleInput(employment.id, 'you_have_a_nickname', value)" <!-- Corrected field name -->
v-model="employment.you_have_a_nickname" <!-- Corrected field name -->
>
You have a nickname?
</CheckBox>
<FieldContainer v-if="employment.you_have_a_nickname"> <!-- Corrected condition -->
<StyledInput
labelText="Nickname"
isMandatory="false"
infoText="Nickname"
inputType="text"
:name="`nickname-${employment.id}`"
:id="`nickname-${employment.id}`"
:isValid="employment.isValid"
:validationMessage="employment.validationMessage"
v-model="employment.nickname"
/>
</FieldContainer>
Script Adjustments:
const addEmployment = () => {
const newEmployment = {
id: uuidv4(),
// ... other fields
you_have_a_nickname: false, // Corrected field name
nickname: '',
// ... other fields
};
// ... rest of the function
};
// Update handleInput to use the correct field name
const handleInput = (id, field, value) => {
const employment = request.doc.employment_history.find(emp => emp.id === id);
if (employment) {
employment[field] = value;
validateField(employment, field);
}
};
// In the validateField function, ensure 'you_have_a_nickname' is handled if needed
const validateField = (employment, field) => {
switch(field) {
// ... existing cases
case 'you_have_a_nickname':
// Add validation if needed
break;
// ... other cases
default:
break;
}
};
3. Enhance Validation Logic
Issue:
Currently, isValid and validationMessage are set at the employment level, which may not accurately reflect the validation state of individual fields.
Solution:
Consider maintaining a validation state for each field within an employment record. This provides more granular control and better user feedback.
Example:
const addEmployment = () => {
const newEmployment = {
id: uuidv4(),
// ... other fields
validation: {
company: { isValid: true, message: '' },
name_of_your_employer: { isValid: true, message: '' },
// Add validation objects for each field
}
};
request.doc.employment_history.push(newEmployment);
nextTick(() => {
openSections[newEmployment.id] = true;
});
};
const validateField = (employment, field) => {
switch(field) {
case 'company':
case 'name_of_your_employer':
case 'type_of_employment':
case 'country':
case 'city':
case 'governorate':
case 'from_date':
case 'phone':
case 'ext':
case 'name_of_the_last_position_you_held':
if (!employment[field] || (typeof employment[field] === 'string' && !employment[field].trim())) {
employment.validation[field].isValid = false;
employment.validation[field].message = `${field.replace(/_/g, ' ')} is required.`;
} else {
employment.validation[field].isValid = true;
employment.validation[field].message = '';
}
break;
// Add more cases as needed for other fields
default:
break;
}
};
Template Adjustments:
Update the bindings to use the new validation structure.
<StyledInput
labelText="Company"
isMandatory="true"
infoText="Company"
inputType="text"
:name="`company-${employment.id}`"
:id="`company-${employment.id}`"
:isValid="employment.validation.company.isValid"
:validationMessage="employment.validation.company.message"
v-model="employment.company"
/>
4. Implement Dependent Dropdowns for Country, City, and Governorate
Issue:
While you have functions to retrieve cities and governorates based on the selected country and city, these aren't utilized in the template.
Solution:
Add Autocomp components for city and governorate, updating their options based on the selected country and city respectively.
Template Example:
<FieldContainer>
<Autocomp
labelText="City"
isMandatory="true"
infoText="City"
inputType="text"
:name="`city-${employment.id}`"
:id="`city-${employment.id}`"
:options="getOptionCity(employment.country)"
:isValid="employment.validation.city.isValid"
:validationMessage="employment.validation.city.message"
v-model="employment.city"
@input-change="value => handleInput(employment.id, 'city', value)"
/>
</FieldContainer>
<FieldContainer>
<Autocomp
labelText="Governorate"
isMandatory="true"
infoText="Governorate"
inputType="text"
:name="`governorate-${employment.id}`"
:id="`governorate-${employment.id}`"
:options="getOptionGovernorate(employment.city)"
:isValid="employment.validation.governorate.isValid"
:validationMessage="employment.validation.governorate.message"
v-model="employment.governorate"
@input-change="value => handleInput(employment.id, 'governorate', value)"
/>
</FieldContainer>
5. Handle Validation on Form Submission
Issue:
Currently, validation occurs on individual field changes, but you might want to perform a comprehensive validation before form submission.
Solution:
Implement a validateForm function that checks all fields of each employment record before submitting.
const validateForm = () => {
let isFormValid = true;
request.doc.employment_history.forEach(employment => {
Object.keys(employment.validation).forEach(field => {
validateField(employment, field);
if (!employment.validation[field].isValid) {
isFormValid = false;
}
});
});
return isFormValid;
};
const saveRequest = async () => {
if (!validateForm()) {
toast.error('Please fix the errors in the form.');
return;
}
try {
await request.setValue.submit({
employment_history: request.doc.employment_history,
});
toast.success('Request has been successfully saved!');
} catch (error) {
if (!errors.global) {
errors.global = [];
}
errors.global.push(`An error occurred while saving the request: ${error.message}`);
}
};
6. Enhance User Experience with Clear Validation Messages
Suggestion:
Display validation messages near the corresponding fields to provide immediate feedback to users.
Template Example:
Assuming your StyledInput or other components can display validation messages, ensure they are properly bound.
<StyledInput
labelText="Company"
isMandatory="true"
infoText="Company"
inputType="text"
:name="`company-${employment.id}`"
:id="`company-${employment.id}`"
:isValid="employment.validation.company.isValid"
:validationMessage="employment.validation.company.message"
v-model="employment.company"
/>
Ensure that your StyledInput, Autocomp, Select, and other input components are designed to display validation messages based on the isValid and validationMessage props.
7. Optimize Reactive Data Handling
Issue:
Using reactive for openSections is functional, but for better scalability and reactivity handling, you might consider using ref with an object or leveraging Vue's reactive efficiently.
Solution:
Your current usage is acceptable, but ensure that all reactive dependencies are correctly managed.
8. Code Cleanup and Best Practices
-
Remove Unused Imports:
If you’re not using certain imports (like nextTick unless needed), consider removing them to keep your code clean.
-
Consistent Naming Conventions:
Ensure all your fields follow consistent naming conventions to avoid confusion and bugs.
-
Error Handling:
Improve error handling to provide more descriptive messages and possibly retry mechanisms.
Final Revised Code Snippets
Script Setup:
<script setup>
import Button from '../../components/button.vue';
import CheckBox from '../../components/checkBox.vue';
import FieldContainer from '../../components/fieldContainer.vue';
import FieldsToggleContainer from '../../components/fieldsToggleContainer.vue';
import FileUpload from '../../components/fileUpload.vue';
import Select from '../../components/select.vue';
import StyledInput from '../../components/styledInput.vue';
import Autocomp from '../../components/autocomp.vue';
import { ref, computed, watch, reactive, nextTick } from 'vue';
import { createDocumentResource } from 'frappe-ui';
import { location } from '../../data/useAddressLogic';
import { v4 as uuidv4 } from 'uuid'; // Ensure uuid is installed
const optionsTypeEmployment = [
{ value: "Full-Time", label: "Full-Time" },
{ value: "Part-Time", label: "Part-Time" },
{ value: "Contract", label: "Contract" },
{ value: "Internship", label: "Internship" },
];
const request = createDocumentResource({
doctype: 'Verification Instructions Request',
name: 'VIR-2024-26-09-000007',
});
const optionCountry = computed(() => {
return location.data
.filter(loc => loc.location_type === 'Country')
.map(loc => ({
label: loc.location_name,
value: loc.location_name
}));
});
const getOptionCity = (country) => {
if (!country) return [];
return location.data
.filter(loc => loc.location_type === 'City' && loc.parent_location === country)
.map(loc => ({
label: loc.location_name,
value: loc.location_name
}));
};
const getOptionGovernorate = (city) => {
if (!city) return [];
return location.data
.filter(loc => loc.location_type === 'Governorate' && loc.parent_location === city)
.map(loc => ({
label: loc.location_name,
value: loc.location_name
}));
};
watch(() => request.doc, (newDoc) => {
if (newDoc && !newDoc.employment_history) {
newDoc.employment_history = [];
}
}, { immediate: true });
const openSections = reactive({});
const toggleSection = (id) => {
openSections[id] = !openSections[id];
};
const isOpen = (id) => {
return openSections[id];
};
const addEmployment = () => {
const newEmployment = {
id: uuidv4(),
company: '',
name_of_your_employer: '',
type_of_employment: '',
continuous: false,
country: '',
city: '',
governorate: '',
from_date: '',
to_date: '',
phone: '',
ext: '',
do_we_have_permission_to_contact_this_current_employer: false,
issuing_salary: false,
activity_has_stopped: false,
the_company_has_different_names: false,
different_company_names: '',
name_of_the_last_position_you_held: '',
you_have_a_nickname: false,
nickname: '',
validation: {
company: { isValid: true, message: '' },
name_of_your_employer: { isValid: true, message: '' },
type_of_employment: { isValid: true, message: '' },
country: { isValid: true, message: '' },
city: { isValid: true, message: '' },
governorate: { isValid: true, message: '' },
from_date: { isValid: true, message: '' },
to_date: { isValid: true, message: '' },
phone: { isValid: true, message: '' },
ext: { isValid: true, message: '' },
name_of_the_last_position_you_held: { isValid: true, message: '' },
// Add other fields as needed
}
};
request.doc.employment_history.push(newEmployment);
nextTick(() => {
openSections[newEmployment.id] = true;
});
};
const confirmRemove = (id) => {
if (confirm('Are you sure you want to delete this employment record?')) {
removeEmployment(id);
}
};
const removeEmployment = (id) => {
const index = request.doc.employment_history.findIndex(emp => emp.id === id);
if (index !== -1) {
request.doc.employment_history.splice(index, 1);
delete openSections[id];
}
};
const handleInput = (id, field, value) => {
const employment = request.doc.employment_history.find(emp => emp.id === id);
if (employment) {
employment[field] = value;
validateField(employment, field);
}
};
const validateField = (employment, field) => {
switch(field) {
case 'company':
case 'name_of_your_employer':
case 'type_of_employment':
case 'country':
case 'city':
case 'governorate':
case 'from_date':
case 'phone':
case 'ext':
case 'name_of_the_last_position_you_held':
if (!employment[field] || (typeof employment[field] === 'string' && !employment[field].trim())) {
employment.validation[field].isValid = false;
employment.validation[field].message = `${field.replace(/_/g, ' ')} is required.`;
} else {
employment.validation[field].isValid = true;
employment.validation[field].message = '';
}
break;
case 'you_have_a_nickname':
// Example validation: no specific validation
break;
// Add more cases as needed for other fields
default:
break;
}
};
const validateForm = () => {
let isFormValid = true;
request.doc.employment_history.forEach(employment => {
Object.keys(employment.validation).forEach(field => {
validateField(employment, field);
if (!employment.validation[field].isValid) {
isFormValid = false;
}
});
});
return isFormValid;
};
const saveRequest = async () => {
if (!validateForm()) {
toast.error('Please fix the errors in the form.');
return;
}
try {
await request.setValue.submit({
employment_history: request.doc.employment_history,
});
toast.success('Request has been successfully saved!');
} catch (error) {
if (!errors.global) {
errors.global = [];
}
errors.global.push(`An error occurred while saving the request: ${error.message}`);
}
};
// Props
const props = defineProps({
stepData: {
type: Object,
required: true,
},
});
</script>
Template Adjustments:
Ensure all input components utilize the updated validation structure and bindings.
<template>
<div class="pt-3 container">
<h3 class="text-lg font-medium mb-3 text-black">Employment History</h3>
</div>
<div class="space-y-2">
<FieldsToggleContainer
v-for="(employment, index) in request.doc.employment_history"
:key="employment.id"
:title="'Company ' + (index + 1)"
>
<div class="lg:grid grid-cols-2 lg:gap-2">
<FieldContainer>
<StyledInput
labelText="Company"
isMandatory="true"
infoText="Company"
inputType="text"
:name="`company-${employment.id}`"
:id="`company-${employment.id}`"
:isValid="employment.validation.company.isValid"
:validationMessage="employment.validation.company.message"
v-model="employment.company"
@input-change="value => handleInput(employment.id, 'company', value)"
/>
</FieldContainer>
<FieldContainer>
<StyledInput
labelText="Name of Your Employer"
isMandatory="true"
infoText="Name of Your Employer"
inputType="text"
:name="`name_of_your_employer-${employment.id}`"
:id="`name_of_your_employer-${employment.id}`"
:isValid="employment.validation.name_of_your_employer.isValid"
:validationMessage="employment.validation.name_of_your_employer.message"
v-model="employment.name_of_your_employer"
@input-change="value => handleInput(employment.id, 'name_of_your_employer', value)"
/>
</FieldContainer>
<!-- Repeat similar structure for other fields -->
<FieldContainer>
<CheckBox
:name="`continuous-${employment.id}`"
:id="`continuous-${employment.id}`"
@input-change="value => handleInput(employment.id, 'continuous', value)"
v-model="employment.continuous"
>
Continuous
</CheckBox>
</FieldContainer>
<FieldContainer>
<Autocomp
labelText="Country"
isMandatory="true"
infoText="Country"
inputType="text"
:name="`country-${employment.id}`"
:id="`country-${employment.id}`"
:options="optionCountry"
:isValid="employment.validation.country.isValid"
:validationMessage="employment.validation.country.message"
v-model="employment.country"
@input-change="value => handleInput(employment.id, 'country', value)"
/>
</FieldContainer>
<FieldContainer>
<Autocomp
labelText="City"
isMandatory="true"
infoText="City"
inputType="text"
:name="`city-${employment.id}`"
:id="`city-${employment.id}`"
:options="getOptionCity(employment.country)"
:isValid="employment.validation.city.isValid"
:validationMessage="employment.validation.city.message"
v-model="employment.city"
@input-change="value => handleInput(employment.id, 'city', value)"
/>
</FieldContainer>
<FieldContainer>
<Autocomp
labelText="Governorate"
isMandatory="true"
infoText="Governorate"
inputType="text"
:name="`governorate-${employment.id}`"
:id="`governorate-${employment.id}`"
:options="getOptionGovernorate(employment.city)"
:isValid="employment.validation.governorate.isValid"
:validationMessage="employment.validation.governorate.message"
v-model="employment.governorate"
@input-change="value => handleInput(employment.id, 'governorate', value)"
/>
</FieldContainer>
<FieldContainer>
<StyledInput
id="from_date"
:name="`from_date-${employment.id}`"
labelText="From"
isMandatory="true"
infoText="From Date"
inputType="date"
@input-change="value => handleInput(employment.id, 'from_date', value)"
v-model="employment.from_date"
:isValid="employment.validation.from_date.isValid"
:validationMessage="employment.validation.from_date.message"
/>
</FieldContainer>
<FieldContainer>
<StyledInput
id="to_date"
:name="`to_date-${employment.id}`"
labelText="To"
isMandatory="true"
infoText="To Date"
inputType="date"
@input-change="value => handleInput(employment.id, 'to_date', value)"
v-model="employment.to_date"
:isValid="employment.validation.to_date.isValid"
:validationMessage="employment.validation.to_date.message"
/>
</FieldContainer>
<!-- Phone Field -->
<FieldContainer>
<StyledInput
labelText="Phone"
isMandatory="true"
infoText="+999-77885951"
inputType="text"
:name="`phone-${employment.id}`"
:id="`phone-${employment.id}`"
:isValid="employment.validation.phone.isValid"
:validationMessage="employment.validation.phone.message"
v-model="employment.phone"
@input-change="value => handleInput(employment.id, 'phone', value)"
/>
</FieldContainer>
<!-- Type of Employment -->
<FieldContainer>
<Select
:id="`type_of_employment-${employment.id}`"
:name="`type_of_employment-${employment.id}`"
labelText="Type of Employment"
isMandatory="true"
infoText="Type of Employment"
:options="optionsTypeEmployment"
@input-change="value => handleInput(employment.id, 'type_of_employment', value)"
v-model="employment.type_of_employment"
:isValid="employment.validation.type_of_employment.isValid"
:validationMessage="employment.validation.type_of_employment.message"
/>
</FieldContainer>
<!-- Extension -->
<FieldContainer>
<StyledInput
labelText="Extension"
isMandatory="true"
infoText="Extension"
inputType="text"
:name="`ext-${employment.id}`"
:id="`ext-${employment.id}`"
:isValid="employment.validation.ext.isValid"
:validationMessage="employment.validation.ext.message"
v-model="employment.ext"
@input-change="value => handleInput(employment.id, 'ext', value)"
/>
</FieldContainer>
<!-- Permissions and Flags -->
<FieldContainer>
<CheckBox
:name="`do_we_have_permission_to_contact_this_current_employer-${employment.id}`"
:id="`do_we_have_permission_to_contact_this_current_employer-${employment.id}`"
@input-change="value => handleInput(employment.id, 'do_we_have_permission_to_contact_this_current_employer', value)"
v-model="employment.do_we_have_permission_to_contact_this_current_employer"
>
Do we have permission to contact this current employer?
</CheckBox>
</FieldContainer>
<!-- Repeat for other CheckBoxes -->
<!-- Different Company Names -->
<FieldContainer>
<StyledInput
labelText="Different Company Names"
isMandatory="false"
infoText="Different Company Names"
inputType="text"
:name="`different_company_names-${employment.id}`"
:id="`different_company_names-${employment.id}`"
:isValid="employment.validation.different_company_names.isValid"
:validationMessage="employment.validation.different_company_names.message"
v-model="employment.different_company_names"
@input-change="value => handleInput(employment.id, 'different_company_names', value)"
/>
</FieldContainer>
<!-- Last Position -->
<FieldContainer>
<StyledInput
labelText="Name of the Last Position You Held"
isMandatory="true"
infoText="Name of the Last Position You Held"
inputType="text"
:name="`name_of_the_last_position_you_held-${employment.id}`"
:id="`name_of_the_last_position_you_held-${employment.id}`"
:isValid="employment.validation.name_of_the_last_position_you_held.isValid"
:validationMessage="employment.validation.name_of_the_last_position_you_held.message"
v-model="employment.name_of_the_last_position_you_held"
@input-change="value => handleInput(employment.id, 'name_of_the_last_position_you_held', value)"
/>
</FieldContainer>
<!-- Nickname -->
<FieldContainer>
<CheckBox
:name="`you_have_a_nickname-${employment.id}`"
:id="`you_have_a_nickname-${employment.id}`"
@input-change="value => handleInput(employment.id, 'you_have_a_nickname', value)"
v-model="employment.you_have_a_nickname"
>
You have a nickname?
</CheckBox>
</FieldContainer>
<FieldContainer v-if="employment.you_have_a_nickname">
<StyledInput
labelText="Nickname"
isMandatory="false"
infoText="Nickname"
inputType="text"
:name="`nickname-${employment.id}`"
:id="`nickname-${employment.id}`"
:isValid="employment.validation.nickname.isValid"
:validationMessage="employment.validation.nickname.message"
v-model="employment.nickname"
@input-change="value => handleInput(employment.id, 'nickname', value)"
/>
</FieldContainer>
</div>
<FileUpload
:name="`file-${employment.id}`"
:id="`file-${employment.id}`"
/>
<Button level="danger" @clicked="() => confirmRemove(employment.id)">
Remove
</Button>
<!-- <Button level="danger" @clicked="() => saveRequest(employment.id)">
Add
</Button> -->
</FieldsToggleContainer>
<div class="flex justify-center py-3">
<Button level="secondary" @clicked="addEmployment">+ Add Employment History</Button>
</div>
</div>
</template>
9. Additional Recommendations
-
Accessibility: Ensure all form fields are accessible, with appropriate aria attributes and labels.
-
Performance: If the form grows large, consider implementing lazy loading or pagination for better performance.
-
Testing: Implement unit and integration tests to ensure the form behaves as expected under various scenarios.
By addressing these points, your component will be more robust, maintainable, and user-friendly. Make sure to test thoroughly after implementing these changes to ensure everything works seamlessly.