Your Vue.js component for managing Verification Instructions Requests is well-structured and leverages modern Vue 3 features effectively. However, there are a few areas where improvements can enhance functionality, maintainability, and user experience. Below are detailed suggestions and adjustments to optimize your component:
1. Handling openSections More Reliably
Issue:
Using the index as the key for openSections can lead to inconsistencies when items are added or removed. For example, deleting an item changes the indices of subsequent items, which can cause the wrong sections to open or close.
Solution:
Introduce a unique identifier for each education entry. This ensures that each section's open state is consistently tracked regardless of the list's modifications.
Implementation:
-
Add an id Field to Each Education Entry:
const addEducation = () => {
const newEducation = {
id: Date.now(), // Simple unique ID; consider using a UUID library for more robust IDs
company: '',
continuous: false,
country: '',
from_date: '',
phone: '',
type_of_employment: '',
}
request.doc.education_information.push(newEducation)
nextTick(() => {
openSections[newEducation.id] = true
})
}
-
Update the v-for Key and Methods:
<div
v-for="(education, index) in request.doc.education_information"
:key="education.id"
class="border border-gray-200 rounded-md"
>
const toggleSection = (id) => {
openSections[id] = !openSections[id]
}
const isOpen = (id) => {
return openSections[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]
}
}
-
Adjust Template Button Events:
<button
@click="toggleSection(education.id)"
:aria-expanded="isOpen(education.id)"
...
>
<button
@click="confirmRemove(education.id)"
...
>
2. Streamlining Data Binding with v-model
Issue:
Currently, you're using both v-model and event listeners like @input or @change to update the education data. This redundancy can lead to unnecessary re-rendering and potential bugs.
Solution:
Leverage v-model exclusively for two-way data binding unless additional logic is required during updates.
Implementation:
-
Remove Redundant Event Handlers:
<!-- Before -->
<input
v-model="education.company"
placeholder="اسم الشركة"
@input="updateEducation(index, 'company', education.company)"
class="..."
/>
<!-- After -->
<input
v-model="education.company"
placeholder="اسم الشركة"
class="..."
/>
-
Remove the updateEducation Method if It's Solely for Setting Values:
If updateEducation doesn't contain additional logic beyond setting the field, you can eliminate it entirely.
// Remove this method
const updateEducation = (index, field, value) => {
request.doc.education_information[index][field] = value
}
Note: If you need to perform validations or other side effects when a field changes, consider using Vue's Watchers or computed properties.
3. Ensuring Correct Submission Method
Issue:
The method request.setValue.submit might not align with the actual API provided by frappe-ui. Typically, resources have a save method for submitting data.
Solution:
Double-check the frappe-ui documentation to confirm the correct submission method. If save is the appropriate method, update it accordingly.
Implementation:
const saveRequest = () => {
const errors = []
// ... (validation logic remains the same)
if (errors.length > 0) {
toast.error(errors.join('<br>'), { html: true })
return
}
request.save({
education_information: request.doc.education_information,
// إضافة حقول أخرى إذا لزم الأمر
})
.then(() => {
toast.success('تم حفظ الطلب بنجاح!')
})
.catch((error) => {
toast.error(`حدث خطأ أثناء حفظ الطلب: ${error.message}`)
})
}
Ensure that save is the correct method. If setValue.submit is accurate per your specific frappe-ui setup, you can retain it.
4. Improving Error Message Display
Issue:
Using <br> within toast messages assumes that the toast library supports HTML. If it doesn't, the line breaks won't render correctly, affecting readability.
Solution:
Verify that your toast library (vue-toastification in this case) supports HTML in messages. If not, consider alternative approaches such as joining messages with newline characters or displaying multiple toast notifications.
Implementation:
-
Check vue-toastification Configuration:
Ensure that the vue-toastification instance is configured to allow HTML. When initializing vue-toastification, set the allowHtml option if necessary.
import Toast, { POSITION } from "vue-toastification"
import "vue-toastification/dist/index.css"
const options = {
// You can set your default options here
position: POSITION.TOP_RIGHT,
// ...
}
app.use(Toast, options)
-
Use Template Literals or Arrays for Better Formatting:
If HTML is supported, your current implementation is fine. Otherwise, consider alternative formatting.
if (errors.length > 0) {
toast.error(errors.join('\n'))
return
}
Or display each error as a separate toast:
if (errors.length > 0) {
errors.forEach(error => toast.error(error))
return
}
5. Enhancing Phone Number Validation
Issue:
The current phone number pattern strictly expects exactly 10 digits, which might not accommodate all valid phone number formats across different countries.
Solution:
Consider a more flexible validation pattern or integrate a library like libphonenumber for comprehensive phone number validation.
Implementation:
-
Update the Regex Pattern:
const phonePattern = /^[0-9]{10,15}$/ // Allows 10 to 15 digits
if (education.phone && !phonePattern.test(education.phone)) {
errors.push(`رقم الهاتف غير صالح في السجل رقم ${index + 1}.`)
}
-
Alternatively, Use a Validation Library:
Implement a dedicated phone number validation library to handle various international formats more effectively.
// Example using libphonenumber-js
import { isValidPhoneNumber } from 'libphonenumber-js'
if (education.phone && !isValidPhoneNumber(education.phone, education.country)) {
errors.push(`رقم الهاتف غير صالح في السجل رقم ${index + 1}.`)
}
Note: This approach requires installing the libphonenumber-js package and handling its import and usage appropriately.
6. Accessibility Improvements
Issue:
While the component is functional, enhancing accessibility ensures it’s usable by a broader audience, including those relying on assistive technologies.
Solution:
Implement ARIA roles and ensure that interactive elements are keyboard navigable.
Implementation:
-
Ensure Buttons Are Accessible:
- Use semantic HTML elements (e.g.,
<button>) which are inherently focusable and operable via keyboard.
- Provide meaningful
aria-label attributes if necessary.
-
Manage Focus:
- When adding or removing sections, consider setting focus to relevant elements to aid keyboard navigation.
-
Enhance the Accordion for Screen Readers:
<button
@click="toggleSection(education.id)"
:aria-expanded="isOpen(education.id)"
aria-controls="section-content-{{ education.id }}"
class="..."
>
...
</button>
<transition name="accordion">
<div
v-show="isOpen(education.id)"
class="p-4 space-y-4"
id="section-content-{{ education.id }}"
role="region"
aria-labelledby="section-button-{{ education.id }}"
>
...
</div>
</transition>
7. Final Revised Code Snippet
Incorporating the above suggestions, here's a revised version of your component:
<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 class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
<div>
<label class="block text-gray-700 font-semibold">العميل:</label>
<span class="text-gray-900">{{ request.doc.customer }}</span>
</div>
<div>
<label class="block text-gray-700 font-semibold">تاريخ الطلب:</label>
<span 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">
<div
v-for="(education, index) in request.doc.education_information"
:key="education.id"
class="border border-gray-200 rounded-md"
>
<!-- رأس القسم الذي يمكن النقر عليه لتوسيع/طي -->
<button
@click="toggleSection(education.id)"
:aria-expanded="isOpen(education.id)"
aria-controls="section-content-{{ education.id }}"
class="w-full flex justify-between items-center px-4 py-2 bg-gray-50 hover:bg-gray-100 rounded-t-md focus:outline-none"
>
<span>{{ education.company || 'سجل تعليمي جديد' }}</span>
<svg
:class="{'transform rotate-180': isOpen(education.id)}"
class="w-5 h-5 transition-transform duration-200"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
</svg>
</button>
<!-- محتوى القسم القابل للتوسيع -->
<transition name="accordion">
<div
v-show="isOpen(education.id)"
class="p-4 space-y-4"
id="section-content-{{ education.id }}"
role="region"
aria-labelledby="section-button-{{ education.id }}"
>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label class="block text-gray-700">اسم الشركة:</label>
<input
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"
/>
</div>
<div>
<label class="text-gray-700 mr-2">مستمر:</label>
<input
type="checkbox"
v-model="education.continuous"
class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
/>
</div>
<div>
<label class="block text-gray-700">البلد:</label>
<select
v-model="education.country"
class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">اختر بلد</option>
<option v-for="country in countries" :key="country.value" :value="country.value">
{{ country.label }}
</option>
</select>
</div>
<div>
<label class="block text-gray-700">من تاريخ:</label>
<input
type="date"
v-model="education.from_date"
class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label class="block text-gray-700">الهاتف:</label>
<input
type="tel"
v-model="education.phone"
placeholder="الهاتف"
pattern="[0-9]{10,15}"
class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<div>
<label class="block text-gray-700">نوع التوظيف:</label>
<select
v-model="education.type_of_employment"
class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="">اختر نوع التوظيف</option>
<option value="Full-time">دوام كامل</option>
<option value="Part-time">دوام جزئي</option>
<option value="Contract">عقد</option>
<option value="Internship">تدريب</option>
</select>
</div>
</div>
<!-- زر حذف السجل -->
<div class="flex justify-end">
<button
@click="confirmRemove(education.id)"
class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-md"
>
حذف السجل
</button>
</div>
</div>
</transition>
</div>
</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">
<p class="text-gray-700">جاري التحميل...</p>
</div>
</div>
</template>
<script setup>
import { createDocumentResource } from 'frappe-ui'
import { ref, watch, reactive, nextTick } from 'vue'
import { useToast } from 'vue-toastification'
// إنشاء مورد الوثيقة للـ DocType الرئيسي
const request = createDocumentResource({
doctype: 'Verification Instructions Request',
// name: 'VIR-2024-26-09-000007', // إلغاء التعليق لإنشاء طلب جديد
})
// تعريف قائمة البلدان
const countries = ref([
{ label: 'مصر', value: 'EG' },
{ label: 'اليمن', value: 'YE' },
{ label: 'الإمارات', value: 'AE' },
{ label: 'قطر', value: 'QA' },
// أضف المزيد من البلدان حسب الحاجة
])
// تأكد من تهيئة education_information كصفيف
watch(() => request.doc, (newDoc) => {
if (newDoc && !newDoc.education_information) {
newDoc.education_information = []
}
}, { immediate: true })
// حالة التوسعة لكل قسم باستخدام معرف فريد
const openSections = reactive({})
// دالة للتحكم في توسيع/طي كل قسم
const toggleSection = (id) => {
openSections[id] = !openSections[id]
}
const isOpen = (id) => {
return openSections[id]
}
// إضافة سجل تعليمي جديد
const addEducation = () => {
const newEducation = {
id: Date.now(), // أو استخدم مكتبة UUID
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 toast = useToast()
// حفظ الطلب
const saveRequest = () => {
const errors = []
request.doc.education_information.forEach((education, index) => {
if (!education.company) {
errors.push(`اسم الشركة مطلوب في السجل رقم ${index + 1}.`)
}
if (!education.country) {
errors.push(`البلد مطلوب في السجل رقم ${index + 1}.`)
}
if (!education.from_date) {
errors.push(`تاريخ البدء مطلوب في السجل رقم ${index + 1}.`)
}
if (!education.type_of_employment) {
errors.push(`نوع التوظيف مطلوب في السجل رقم ${index + 1}.`)
}
// تحقق إضافي لنمط الهاتف
const phonePattern = /^[0-9]{10,15}$/
if (education.phone && !phonePattern.test(education.phone)) {
errors.push(`رقم الهاتف غير صالح في السجل رقم ${index + 1}.`)
}
})
if (errors.length > 0) {
toast.error(errors.join('<br>'), { html: true })
return
}
request.save({
education_information: request.doc.education_information,
// إضافة حقول أخرى إذا لزم الأمر
})
.then(() => {
toast.success('تم حفظ الطلب بنجاح!')
})
.catch((error) => {
toast.error(`حدث خطأ أثناء حفظ الطلب: ${error.message}`)
})
}
// تنسيق التاريخ
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>
8. Additional Recommendations
-
Unique Identifiers: For a more robust solution, especially in larger applications, consider using UUIDs (uuid library) instead of Date.now() to generate unique IDs.
-
Form Reset After Submission: After successfully saving the request, you might want to reset the form or provide options to create a new entry.
-
Enhanced User Feedback: Incorporate loading indicators during data submission to inform users that their request is being processed.
-
Modularize Components: If the education section becomes more complex, consider extracting it into a separate child component to improve readability and maintainability.
-
Unit Testing: Implement unit tests for your component to ensure reliability, especially for critical functions like saveRequest.
By addressing the above points, your component will be more reliable, maintainable, and user-friendly. This will not only enhance the developer experience but also provide a better interface for your end-users.