Your Vue component for handling a "Verification Instructions Request" looks comprehensive and well-structured. Below is a detailed review with suggestions for improvements, potential issues to address, and best practices to enhance your implementation.
1. Component Structure and Organization
- Template: Well-organized with clear sections for displaying the main request details, education information, error messages, and action buttons.
- Script: Utilizes the Composition API effectively with
ref, reactive, and watch.
- Styles: Scoped styles ensure that your accordion transitions don't affect other parts of the application.
2. Imports and Dependencies
import { createDocumentResource, ErrorMessage } from 'frappe-ui'
import { ref, watch, reactive, nextTick } from 'vue'
// import ErrorMessage from 'frappe-ui/components/ErrorMessage.vue' // تأكد من المسار الصحيح للمكون
-
Issue: You are importing ErrorMessage directly from 'frappe-ui' and also have a commented import from 'frappe-ui/components/ErrorMessage.vue'. Ensure you are using the correct import path based on how frappe-ui exports its components.
-
Suggestion: Confirm the correct path for ErrorMessage. If frappe-ui exports it directly, your current import is fine. Otherwise, uncomment and adjust the path accordingly.
3. Data Management
-
Document Resource Initialization:
const request = createDocumentResource({
doctype: 'Verification Instructions Request',
// name: 'VIR-2024-26-09-000007', // إلغاء التعليق لإنشاء طلب جديد
})
- Suggestion: If you intend to create a new request, consider managing both creation and editing scenarios. You might need to handle cases where
name is provided (editing) or absent (creation).
-
Countries List:
const countries = ref([
{ label: 'مصر', value: 'EG' },
{ label: 'اليمن', value: 'YE' },
{ label: 'الإمارات', value: 'AE' },
{ label: 'قطر', value: 'QA' },
// أضف المزيد من البلدان حسب الحاجة
])
- Suggestion: For scalability, consider fetching the list of countries from an API or a centralized store, especially if the list is extensive or subject to change.
4. Reactivity and State Management
-
Ensuring education_information Initialization:
watch(() => request.doc, (newDoc) => {
if (newDoc && !newDoc.education_information) {
newDoc.education_information = []
}
}, { immediate: true })
-
Issue: Directly mutating newDoc might lead to unintended side effects, especially if request.doc is managed by a reactivity system or a state store.
-
Suggestion: Use Vue's reactivity methods to ensure changes are tracked appropriately.
watch(() => request.doc, (newDoc) => {
if (newDoc && !newDoc.education_information) {
request.doc.education_information = reactive([])
}
}, { immediate: true })
-
Managing Open Sections:
const openSections = reactive({})
-
Suggestion: Ensure that the id used for each education item is truly unique. Using Date.now() can lead to duplicates if multiple entries are added in quick succession. Consider using a UUID library for generating unique IDs.
import { v4 as uuidv4 } from 'uuid'
const addEducation = () => {
const newEducation = {
id: uuidv4(),
// ...other fields
}
// ...
}
5. Accessibility Enhancements
-
Labels and Inputs:
Ensure that each <label> is properly associated with its corresponding <input> using the for attribute.
<label for="company-{{ education.id }}" class="block text-gray-700">اسم الشركة:</label>
<input
id="company-{{ education.id }}"
v-model="education.company"
placeholder="اسم الشركة"
class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
-
Buttons and ARIA Attributes:
-
The accordion buttons have aria-expanded and aria-controls, which is excellent.
-
Consider adding id to the button for aria-labelledby in the region.
<button
:id="'section-button-' + education.id"
@click="toggleSection(education.id)"
:aria-expanded="isOpen(education.id)"
aria-controls="section-content-{{ education.id }}"
class="..."
>
<!-- Button content -->
</button>
6. Form Validation
-
Client-Side Validation:
Your saveRequest function includes comprehensive client-side validation, which is great.
-
Enhancement: Consider providing immediate feedback as users fill out the form, rather than only upon saving. This can improve user experience.
watch(() => request.doc.education_information, (newEducations) => {
newEducations.forEach((education, index) => {
// Validate each field and update errors accordingly
})
}, { deep: true })
-
Server-Side Validation:
While client-side validation improves user experience, ensure that server-side validation is also in place to maintain data integrity.
7. User Experience Improvements
8. Performance Optimizations
-
List Rendering:
- Use
:key attributes effectively to help Vue optimize rendering. You're already using education.id, which is good.
-
Debouncing Save Operations:
If the saveRequest is triggered frequently (e.g., auto-save), consider debouncing to prevent excessive API calls.
9. Code Maintenance and Scalability
10. Styling and Responsiveness
11. Error Handling Enhancements
-
Displaying Server Errors:
Currently, server errors are captured and pushed to the errors array. Ensure that these messages are user-friendly and possibly mapped to specific fields if applicable.
catch (error) {
if (error.response && error.response.data) {
// Parse and display server-side validation errors
errors.value.push(...parseServerErrors(error.response.data))
} else {
errors.value.push(`حدث خطأ أثناء حفظ الطلب: ${error.message}`)
}
}
-
ErrorMessage Component:
Ensure that your ErrorMessage component is accessible and styled appropriately to capture user attention without being obtrusive.
12. Security Considerations
-
Input Sanitization:
Even though front-end validation is in place, always sanitize and validate inputs on the server side to prevent malicious data from being processed or stored.
-
CSRF Protection:
Ensure that your application is protected against Cross-Site Request Forgery (CSRF) attacks, especially for forms that modify data.
13. Internationalization (i18n)
-
Dynamic Content:
Your component uses hardcoded Arabic strings. For scalability and to support multiple languages, consider implementing an internationalization (i18n) solution.
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
// Usage in template
<label class="block text-gray-700">{{ t('companyName') }}</label>
- Advantage: Facilitates easy addition of other languages and consistency across the application.
14. Final Recommendations
-
Testing:
Implement unit and integration tests for your components to ensure reliability. Tools like Jest and Vue Test Utils can be beneficial.
-
Documentation:
Comment your code where necessary and maintain documentation for your components, especially if they are part of a larger team or project.
-
Optimization:
Regularly profile your application for performance bottlenecks, especially as the number of education entries grows.
Revised Code Snippet with Enhancements
Here's a revised version of a portion of your code incorporating some of the suggestions:
<template>
<div dir="rtl" class="p-6 bg-gray-100 min-h-screen">
<div v-if="request.doc" class="max-w-7xl mx-auto bg-white shadow-md rounded-lg p-6">
<h1 class="text-2xl font-bold mb-4">طلب تعليمات التحقق: {{ request.doc.name }}</h1>
<!-- عرض رسائل الخطأ إذا وجدت -->
<div v-if="errors.length > 0" class="mb-4 space-y-2">
<ErrorMessage
v-for="(error, index) in errors"
:key="index"
:message="error"
/>
</div>
<!-- عرض معلومات الطلب الرئيسي -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
<div>
<label for="customer" class="block text-gray-700 font-semibold">العميل:</label>
<span id="customer" class="text-gray-900">{{ request.doc.customer }}</span>
</div>
<div>
<label for="order_date" class="block text-gray-700 font-semibold">تاريخ الطلب:</label>
<span id="order_date" class="text-gray-900">{{ formatDate(request.doc.order_date) }}</span>
</div>
</div>
<!-- قائمة المعلومات التعليمية الفرعية على شكل ترويجات (Toggles) -->
<h2 class="text-xl font-semibold mb-4">المعلومات التعليمية</h2>
<div class="space-y-4">
<EducationSection
v-for="education in request.doc.education_information"
:key="education.id"
:education="education"
:countries="countries"
@toggle="toggleSection"
@remove="confirmRemove"
:is-open="isOpen(education.id)"
/>
</div>
<!-- أزرار الإضافة والحفظ -->
<div class="flex items-center mt-6 space-x-4">
<button
@click="addEducation"
class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md"
>
إضافة سجل تعليمي
</button>
<button
@click="saveRequest"
class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md"
>
حفظ الطلب
</button>
</div>
</div>
<div v-else class="flex justify-center items-center h-full">
<Spinner /> <!-- Assume a Spinner component exists -->
<p class="text-gray-700 ml-2">جاري التحميل...</p>
</div>
</div>
</template>
<script setup>
import { createDocumentResource, ErrorMessage } from 'frappe-ui'
import { ref, watch, reactive, nextTick } from 'vue'
import { v4 as uuidv4 } from 'uuid'
import EducationSection from './EducationSection.vue' // New component
import { useToast } from 'vue-toastification'
const toast = useToast()
const request = createDocumentResource({
doctype: 'Verification Instructions Request',
// name: 'VIR-2024-26-09-000007', // Uncomment to edit an existing request
})
const countries = ref([
{ label: 'مصر', value: 'EG' },
{ label: 'اليمن', value: 'YE' },
{ label: 'الإمارات', value: 'AE' },
{ label: 'قطر', value: 'QA' },
// Add more countries as needed
])
watch(() => request.doc, (newDoc) => {
if (newDoc && !newDoc.education_information) {
newDoc.education_information = reactive([])
}
}, { immediate: true })
const openSections = reactive({})
const toggleSection = (id) => {
openSections[id] = !openSections[id]
}
const isOpen = (id) => {
return openSections[id]
}
const errors = ref([])
const addEducation = () => {
const newEducation = {
id: uuidv4(),
company: '',
continuous: false,
country: '',
from_date: '',
phone: '',
type_of_employment: '',
}
request.doc.education_information.push(newEducation)
nextTick(() => {
openSections[newEducation.id] = true
})
}
const confirmRemove = (id) => {
if (confirm('هل أنت متأكد من رغبتك في حذف هذا السجل التعليمي؟')) {
removeEducation(id)
}
}
const removeEducation = (id) => {
const index = request.doc.education_information.findIndex(edu => edu.id === id)
if (index !== -1) {
request.doc.education_information.splice(index, 1)
delete openSections[id]
}
}
const saveRequest = async () => {
errors.value = [] // Reset errors before validation
request.doc.education_information.forEach((education, index) => {
if (!education.company) {
errors.value.push(`اسم الشركة مطلوب في السجل رقم ${index + 1}.`)
}
if (!education.country) {
errors.value.push(`البلد مطلوب في السجل رقم ${index + 1}.`)
}
if (!education.from_date) {
errors.value.push(`تاريخ البدء مطلوب في السجل رقم ${index + 1}.`)
}
if (!education.type_of_employment) {
errors.value.push(`نوع التوظيف مطلوب في السجل رقم ${index + 1}.`)
}
// Additional phone pattern check
const phonePattern = /^[0-9]{10,15}$/
if (education.phone && !phonePattern.test(education.phone)) {
errors.value.push(`رقم الهاتف غير صالح في السجل رقم ${index + 1}.`)
}
})
if (errors.value.length > 0) {
return
}
try {
await request.save({
education_information: request.doc.education_information,
// Add other fields if necessary
})
toast.success('تم حفظ الطلب بنجاح!')
} catch (error) {
errors.value.push(`حدث خطأ أثناء حفظ الطلب: ${error.message}`)
toast.error('حدث خطأ أثناء حفظ الطلب.')
}
}
const formatDate = (dateStr) => {
if (!dateStr) return ''
const date = new Date(dateStr)
return date.toLocaleDateString('ar-EG')
}
</script>
<style scoped>
.accordion-enter-active, .accordion-leave-active {
transition: max-height 0.3s ease;
}
.accordion-enter-from, .accordion-leave-to {
max-height: 0;
overflow: hidden;
}
</style>
Summary
Your component is robust and covers many necessary features for managing verification instructions requests. By implementing the above suggestions, you can enhance its functionality, maintainability, and user experience. Remember to test thoroughly, especially when dealing with dynamic data and user interactions, to ensure a smooth and reliable application.
If you have specific questions or encounter particular issues while implementing these suggestions, feel free to ask!