Your Vue component for managing employment history is comprehensive and well-structured. However, there are a few areas where improvements can be made to enhance functionality, maintainability, and ensure correct behavior. Below, I’ve outlined the key issues along with suggestions and code corrections to address them.
1. Validation Function for type_of_employment
Issue:
In your Autocomp component for type_of_employment, the :isValid prop incorrectly calls validateCountry instead of a dedicated validation function for employment type.
Solution:
Create a dedicated validateTypeOfEmployment function and ensure it’s correctly referenced in the Autocomp component.
Corrections:
In the <template>:
<Autocomp
labelText="Type of Employment"
:isMandatory="true"
infoText="Type of Employment"
inputType="text"
name="type_of_employment"
:id="`type_of_employment-${employment.id}`"
:options="optionsTypeEmployment"
v-model="employment.type_of_employment"
@input-change="(value) => handleTypeOfEmployment(index, value)"
:isValid="validateTypeOfEmployment(employment.type_of_employment)"
validationMessage="Type of Employment is required."
/>
In the <script setup>:
// Validation Function for Type of Employment
const validateTypeOfEmployment = (type_of_employment) => {
return typeof type_of_employment === 'string' && type_of_employment.trim() !== ''
}
2. Initialization of type_of_employment Field
Issue:
The type_of_employment field is commented out in both the initialization and the addEmployment function, which means new employment entries won’t have this field initialized.
Solution:
Uncomment and include the type_of_employment field during initialization to ensure it starts with a default value.
Corrections:
In the watch function:
// Ensure all fields are initialized, including type_of_employment
newDoc.employment_history.forEach(employment => {
employment.company = employment.company || ''
employment.contact_the_employer = employment.contact_the_employer || false
employment.issuing_salary = employment.issuing_salary || false
employment.name_of_your_employer = employment.name_of_your_employer || ''
employment.country = employment.country || ''
employment.city = employment.city || ''
employment.governorate = employment.governorate || ''
employment.location_text = employment.location_text || ''
employment.continuous = employment.continuous || false
employment.activity_has_stopped = employment.activity_has_stopped || false
employment.from_date = employment.from_date || ''
employment.end_date = employment.end_date || ''
employment.phone = employment.phone || ''
employment.ext = employment.ext || ''
employment.official_job_title_held_currently = employment.official_job_title_held_currently || ''
employment.type_of_employment = employment.type_of_employment || '' // Un-commented
employment.the_company_has_different_names = employment.the_company_has_different_names || false
employment.different_company_names = employment.different_company_names || ''
employment.you_have_a_nickname = employment.you_have_a_nickname || false // Corrected name
})
In the addEmployment function:
const addEmployment = () => {
const newEmployment = {
id: uuidv4(), // Unique identifier
company: '',
contact_the_employer: false, // Initialized as boolean
issuing_salary: false, // Initialized as boolean
name_of_your_employer: '',
country: '',
city: '',
governorate: '',
location_text: '',
continuous: false, // Initialized as boolean
activity_has_stopped: false, // Initialized as boolean
from_date: '',
end_date: '',
phone: '',
ext: '',
official_job_title_held_currently: '',
type_of_employment: '', // Un-commented
the_company_has_different_names: false, // Initialized as boolean
different_company_names: '',
you_have_a_nickname: false, // Corrected name
}
request.doc.employment_history.push(newEmployment)
nextTick(() => {
openSections[newEmployment.id] = true
})
}
3. Correcting Checkbox Names and IDs
Issue:
Multiple checkboxes share the same name and id attributes using the template string permission-${employment.id}, which can lead to conflicts and unintended behavior.
Solution:
Ensure each checkbox has a unique name and id by specifying different identifiers based on their purpose.
Corrections:
For contact_the_employer:
<CheckBox
:name="`contact_permission-${employment.id}`"
:id="`contact_permission-${employment.id}`"
v-model="employment.contact_the_employer"
>
Do we have permission to contact this current employer?
</CheckBox>
For issuing_salary:
<CheckBox
:name="`issuing_salary_permission-${employment.id}`"
:id="`issuing_salary_permission-${employment.id}`"
v-model="employment.issuing_salary"
>
Does this employer issue your paycheck?
</CheckBox>
Similarly, update other checkboxes:
-
For continuous:
<CheckBox
:name="`continuous-${employment.id}`"
:id="`continuous-${employment.id}`"
v-model="employment.continuous"
>
Continuous
</CheckBox>
-
For activity_has_stopped:
<CheckBox
:name="`activity_has_stopped-${employment.id}`"
:id="`activity_has_stopped-${employment.id}`"
v-model="employment.activity_has_stopped"
>
Activity Has Stopped
</CheckBox>
-
For the_company_has_different_names:
<CheckBox
:name="`different_names-${employment.id}`"
:id="`different_names-${employment.id}`"
v-model="employment.the_company_has_different_names"
>
The Company has Different Names
</CheckBox>
-
For you_have_a_nickname:
<CheckBox
:name="`nickname_checkbox-${employment.id}`"
:id="`nickname_checkbox-${employment.id}`"
v-model="employment.you_have_a_nickname"
>
You Have a Nickname?
</CheckBox>
4. Correcting the you_have_a_nicknamecx Field Name
Issue:
There appears to be a typo in the field name you_have_a_nicknamecx, which likely should be you_have_a_nickname for clarity and consistency.
Solution:
Rename the field appropriately throughout the component.
Corrections:
In the <script setup>:
// During initialization in the watch function
employment.you_have_a_nickname = employment.you_have_a_nickname || false
In the addEmployment function:
you_have_a_nickname: false, // Corrected name
In the <template>:
<CheckBox
:name="`nickname_checkbox-${employment.id}`"
:id="`nickname_checkbox-${employment.id}`"
v-model="employment.you_have_a_nickname"
>
You Have a Nickname?
</CheckBox>
<FieldContainer>
<StyledInput
labelText="Nickname"
:isMandatory="false"
infoText="Nickname"
inputType="text"
name="nickname"
:id="`nickname-${employment.id}`"
v-model="employment.nickname"
:isValid="false"
validationMessage="You can edit the message."
/>
</FieldContainer>
5. Initializing Checkboxes with Boolean Values
Issue:
Checkboxes are being initialized with empty strings (''), whereas they should be initialized with boolean values (false).
Solution:
Ensure all checkbox-related fields are initialized as booleans.
Corrections:
In the watch function and addEmployment:
Initialize the following fields as false instead of '':
contact_the_employer
issuing_salary
continuous
activity_has_stopped
the_company_has_different_names
you_have_a_nickname
Example:
employment.contact_the_employer = employment.contact_the_employer || false
employment.issuing_salary = employment.issuing_salary || false
employment.continuous = employment.continuous || false
employment.activity_has_stopped = employment.activity_has_stopped || false
employment.the_company_has_different_names = employment.the_company_has_different_names || false
employment.you_have_a_nickname = employment.you_have_a_nickname || false
6. Ensuring Unique Names and IDs for Checkboxes
Issue:
Using the same name and id for multiple checkboxes (even if tied to unique employment.id), can still be confusing. It’s better to have descriptive and unique identifiers.
Solution:
Further refine the name and id attributes to reflect the specific purpose of each checkbox.
Corrections:
As shown in Point 3, ensure each checkbox has a unique and descriptive name and id. This improves accessibility and prevents potential conflicts.
7. Handling Validation for Optional Fields
Issue:
Fields like different_company_names and nickname have :isValid="false", which means they're perpetually marked as invalid.
Solution:
For optional fields, you can either omit the :isValid prop or implement conditional validation that allows them to be valid when empty.
Corrections:
Option 1: Omit :isValid for Optional Fields:
<StyledInput
labelText="Different Company Names"
:isMandatory="false"
infoText="Different Company Names"
inputType="text"
name="different_company_names"
:id="`different_company_names-${employment.id}`"
v-model="employment.different_company_names"
validationMessage="You can edit the message."
/>
Option 2: Implement Conditional Validation:
const validateDifferentCompanyNames = (names) => {
return true // Always valid because it's optional
}
const validateNickname = (nickname) => {
return true // Always valid because it's optional
}
And in the <template>:
<StyledInput
labelText="Different Company Names"
:isMandatory="false"
infoText="Different Company Names"
inputType="text"
name="different_company_names"
:id="`different_company_names-${employment.id}`"
v-model="employment.different_company_names"
:isValid="validateDifferentCompanyNames(employment.different_company_names)"
validationMessage="You can edit the message."
/>
<StyledInput
labelText="Nickname"
:isMandatory="false"
infoText="Nickname"
inputType="text"
name="nickname"
:id="`nickname-${employment.id}`"
v-model="employment.nickname"
:isValid="validateNickname(employment.nickname)"
validationMessage="You can edit the message."
/>
8. Enhancing File Upload Handling
Issue:
The FileUpload component is bound to employment.file, but there's no validation or feedback regarding the uploaded file.
Solution:
Implement file validation and provide user feedback to ensure correct file types and sizes are uploaded.
Corrections:
Add Validation Function:
const validateFile = (file) => {
if (!file) return true // Optional field
const allowedTypes = ['application/pdf', 'image/jpeg', 'image/png']
const maxSize = 5 * 1024 * 1024 // 5MB
return allowedTypes.includes(file.type) && file.size <= maxSize
}
In the <template>:
<FileUpload
:name="`file-${employment.id}`"
:id="`file-${employment.id}`"
v-model="employment.file"
:isValid="validateFile(employment.file)"
validationMessage="Please upload a valid file (PDF, JPG, PNG) under 5MB."
/>
Note: Ensure your FileUpload component supports isValid and validationMessage props.
9. Optimizing the Save Functionality
Issue:
Both saveRequest and saveEmployment functions currently submit the entire request.doc. If the backend supports partial updates, consider implementing partial saves to reduce overhead.
Solution:
Modify the saveEmployment function to send only the specific employment entry for update, assuming your backend API supports it.
Corrections:
Example Implementation:
const saveEmployment = async (index) => {
try {
const employment = request.doc.employment_history[index]
// Assuming you have an API endpoint to update a single employment entry
await updateEmploymentAPI(employment.id, employment)
toast.success(`Employment ${index + 1} has been saved successfully!`)
} catch (error) {
console.error(`Failed to save employment ${index + 1}:`, error)
toast.error(`Failed to save employment ${index + 1}.`)
}
}
Note: You need to implement the updateEmploymentAPI function based on your backend's specifications.
10. Refining the FieldsToggleContainer Behavior
Issue:
The FieldsToggleContainer component likely manages the visibility of each employment section. However, the state openSections used in addEmployment isn't defined in the script.
Solution:
Initialize and manage the openSections reactive state to control the visibility of each employment section.
Corrections:
In the <script setup>:
const openSections = reactive({})
// Initialize openSections when employment history is loaded
watch(() => request.doc.employment_history, (newHistory) => {
newHistory.forEach(employment => {
if (!(employment.id in openSections)) {
openSections[employment.id] = false
}
})
}, { immediate: true })
// Modify addEmployment to open the new section
const addEmployment = () => {
const newEmployment = {
id: uuidv4(),
// ...other fields
}
request.doc.employment_history.push(newEmployment)
nextTick(() => {
openSections[newEmployment.id] = true
})
}
In the <template>:
<FieldsToggleContainer
v-for="(employment, index) in request.doc.employment_history"
:key="employment.id"
:title="employment.company || `Employment ${index + 1}`"
v-model="openSections[employment.id]"
>
<!-- Employment Content -->
</FieldsToggleContainer>
Note: Ensure FieldsToggleContainer emits an update:modelValue event to sync with openSections.
11. Ensuring Reactive Updates for request.doc
Issue:
Directly mutating nested properties in a reactive object like request.doc may not always trigger reactivity as expected, especially for deeply nested structures.
Solution:
Use Vue’s set method or ensure that request.doc is a reactive object that supports deep reactivity.
Corrections:
If using Vue 3's reactive, it should handle deep reactivity properly. However, to ensure reactivity when adding new properties dynamically, use Vue.set or spread operators.
Example:
import { set } from 'vue'
// When adding newEmployment properties dynamically
// Not required if all properties are predefined as in `addEmployment`
Alternatively, ensure all properties are defined upfront as done in addEmployment.
12. General Code Enhancements
a. Use Computed Properties for Validation Status
Instead of calling validation functions directly in the template, use computed properties to improve readability and performance.
Example:
const computedValidations = (employment) => ({
company: validateCompany(employment.company),
name_of_your_employer: validateNameOfYourEmployer(employment.name_of_your_employer),
country: validateCountry(employment.country),
city: validateCity(employment.city),
governorate: validateGovernorate(employment.governorate),
from_date: validateFromDate(employment.from_date),
end_date: validateEndDate(employment.end_date),
phone: validatePhone(employment.phone),
official_job_title_held_currently: validateOfficialJobTitleHeldCurrently(employment.official_job_title_held_currently),
type_of_employment: validateTypeOfEmployment(employment.type_of_employment),
// Add other validations as needed
})
In the <template>:
: isValid="computedValidations(employment).company"
b. Modularize Validation Logic
Consider moving validation functions to a separate file or using a validation library like Vuelidate or Yup for more scalable validation management.
Final Revised Code Snippet
Taking into account the corrections and enhancements mentioned above, here is a portion of the revised component to illustrate the applied changes:
<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">
<!-- Iterate Over Employment History -->
<FieldsToggleContainer
v-for="(employment, index) in request.doc.employment_history"
:key="employment.id"
:title="employment.company || `Employment ${index + 1}`"
v-model="openSections[employment.id]"
>
<div class="lg:grid grid-cols-2 lg:gap-2">
<!-- Company Field -->
<FieldContainer>
<StyledInput
labelText="Company"
:isMandatory="true"
infoText="Company"
inputType="text"
name="company"
:id="`company-${employment.id}`"
v-model="employment.company"
:isValid="validateCompany(employment.company)"
validationMessage="Company name is required."
/>
</FieldContainer>
<!-- Name of Employer Field -->
<FieldContainer>
<StyledInput
labelText="Name of Your Employer"
:isMandatory="true"
infoText="Name of Your Employer"
inputType="text"
name="name_of_your_employer"
:id="`name_of_your_employer-${employment.id}`"
v-model="employment.name_of_your_employer"
:isValid="validateNameOfYourEmployer(employment.name_of_your_employer)"
validationMessage="Employer name is required."
/>
</FieldContainer>
</div>
<!-- Other Fields... -->
<!-- Save Employment Button -->
<div class="flex justify-end py-2">
<Button level="primary" @clicked="saveEmployment(index)">Save</Button>
</div>
</FieldsToggleContainer>
<!-- Add Employment Button -->
<div class="flex justify-center py-3">
<Button level="secondary" @clicked="addEmployment">+ Add Employment History</Button>
</div>
</div>
</template>
<script setup>
import { ref, computed, watch, reactive, nextTick } from 'vue'
import { createDocumentResource } from 'frappe-ui'
import { useToast } from 'vue-toastification'
import { v4 as uuidv4 } from 'uuid'
// Components
import Button from '../../components/button.vue'
import FieldContainer from '../../components/fieldContainer.vue'
import FieldsToggleContainer from '../../components/fieldsToggleContainer.vue'
import StyledInput from '../../components/styledInput.vue'
import Autocomp from '../../components/autocomp.vue'
import { location } from '../../data/useAddressLogic'
import CheckBox from '../../components/checkBox.vue'
import FileUpload from '../../components/fileUpload.vue'
// Initialize Toast
const toast = useToast()
// Document Resource
const request = createDocumentResource({
doctype: 'Verification Instructions Request',
name: 'VIR-2024-26-09-000007',
})
// Employment Type Options
const optionsTypeEmployment = reactive([
{ value: "Full-Time", label: "Full-Time" },
{ value: "Part-Time", label: "Part-Time" },
{ value: "Contract", label: "Contract" },
{ value: "Internship", label: "Internship" },
])
// ... (Remaining functions as previously corrected)
// Reactive state to manage open sections
const openSections = reactive({})
// Initialize openSections when employment history is loaded
watch(() => request.doc.employment_history, (newHistory) => {
newHistory.forEach(employment => {
if (!(employment.id in openSections)) {
openSections[employment.id] = false
}
})
}, { immediate: true })
// Add a new employment entry
const addEmployment = () => {
const newEmployment = {
id: uuidv4(),
company: '',
contact_the_employer: false,
issuing_salary: false,
name_of_your_employer: '',
country: '',
city: '',
governorate: '',
location_text: '',
continuous: false,
activity_has_stopped: false,
from_date: '',
end_date: '',
phone: '',
ext: '',
official_job_title_held_currently: '',
type_of_employment: '',
the_company_has_different_names: false,
different_company_names: '',
you_have_a_nickname: false,
file: null, // Assuming file upload is optional
}
request.doc.employment_history.push(newEmployment)
nextTick(() => {
openSections[newEmployment.id] = true
})
}
// Save the entire request
const saveRequest = async () => {
try {
await request.setValue.submit(request.doc)
toast.success('Request has been successfully saved!')
} catch (error) {
console.error('Failed to save the request:', error)
toast.error('Failed to save the request.')
}
}
// Save individual employment entry
const saveEmployment = async (index) => {
try {
const employment = request.doc.employment_history[index]
// Implement a partial save API call if available
await request.setValue.submit(request.doc)
toast.success(`Employment ${index + 1} has been saved successfully!`)
} catch (error) {
console.error(`Failed to save employment ${index + 1}:`, error)
toast.error(`Failed to save employment ${index + 1}.`)
}
}
// Validation Functions
const validateCompany = (company) => {
return typeof company === 'string' && company.trim() !== ''
}
const validateNameOfYourEmployer = (name_of_your_employer) => {
return typeof name_of_your_employer === 'string' && name_of_your_employer.trim() !== ''
}
const validateCountry = (country) => {
return typeof country === 'string' && country.trim() !== ''
}
const validateCity = (city) => {
return typeof city === 'string' && city.trim() !== ''
}
const validateGovernorate = (governorate) => {
return typeof governorate === 'string' && governorate.trim() !== ''
}
const validateFromDate = (from_date) => {
return typeof from_date === 'string' && from_date.trim() !== ''
}
const validateEndDate = (end_date) => {
return typeof end_date === 'string' && end_date.trim() !== ''
}
const validatePhone = (phone) => {
// Simple phone validation; consider using a regex for better accuracy
return typeof phone === 'string' && phone.trim() !== ''
}
const validateTypeOfEmployment = (type_of_employment) => {
return typeof type_of_employment === 'string' && type_of_employment.trim() !== ''
}
const validateOfficialJobTitleHeldCurrently = (official_job_title_held_currently) => {
return typeof official_job_title_held_currently === 'string' && official_job_title_held_currently.trim() !== ''
}
</script>
<style scoped>
/* Add any component-specific styles here */
</style>
Conclusion
By addressing the issues outlined above, your component will be more robust, maintainable, and user-friendly. Ensure that any additional functionality or backend integrations are handled consistently with these improvements. Furthermore, consider implementing a validation library for more complex validation needs and to streamline the validation process across your application.