اريد من ان ترجع لي الكود الكامل لكل ملف قمت بتعديل علية كل ملف على حده
Assistant
// دالة لتحديث أي حقل في `home`
updateHome<K extends keyof VerificationRequestStoreState['home']>(
field: K,
payload: Partial<VerificationRequestStoreState['home'][K]>
) {
this.home[field] = { ...this.home[field], ...payload };
},
// دالة لتحديث أي حقل في `step1`
updateStep1<K extends keyof VerificationRequestStoreState['step1']>(
field: K,
payload: Partial<VerificationRequestStoreState['step1'][K]>
) {
this.step1[field] = { ...this.step1[field], ...payload };
},
// دالة لتحديث أي حقل في `step2`
updateStep2<K extends keyof VerificationRequestStoreState['step2']>(
field: K,
payload: Partial<VerificationRequestStoreState['step2'][K]>
) {
this.step2[field] = { ...this.step2[field], ...payload };
},
// إعادة تعيين الستور إلى الحالة الافتراضية
resetStore() {
Object.assign(this, getDefaultState());
},
/**
* تحميل الوثيقة الحالية
*/
async loadDocument() {
const toast = useToast();
const requestList = createRequestList(['name', 'user_id']);
try {
// انتظار جلب البيانات
await requestList.fetch();
if (requestList.data.length > 0) {
this.documentName = requestList.data[0].name;
toast.success("تم تحميل الوثيقة بنجاح.");
} else {
// لا توجد وثيقة، نقوم بإنشاء واحدة جديدة
const initialFields: UpdateFields = {
country: this.home.country.value,
mobile_number: this.home.mobile_number.value,
is_degree_or_diploma: this.home.is_degree_or_diploma.value,
from_time: this.home.from_time.value,
to_time: this.home.to_time.value,
};
await this.createNewDocument(initialFields);
}
} catch (error) {
console.error("Error loading document:", error);
toast.error("حدث خطأ أثناء تحميل الوثيقة.");
}
},
/**
* إنشاء وثيقة جديدة
*/
async createNewDocument(initialFields: UpdateFields) {
const toast = useToast();
try {
const newDoc = await createDocumentResource({
doctype: 'Verification Instructions Request',
fields: initialFields,
});
this.documentName = newDoc.name;
toast.success("تم إنشاء الوثيقة الجديدة بنجاح.");
} catch (error) {
console.error("Error creating new document:", error);
toast.error("حدث خطأ أثناء إنشاء الوثيقة الجديدة.");
}
},
/**
* تحديث الحقول في الوثيقة الحالية
*/
async updateDocumentFields(updatedFields: UpdateFields) {
const toast = useToast();
if (!this.documentName) {
toast.error("لم يتم العثور على اسم الوثيقة. يرجى إنشاء وثيقة أولاً.");
return;
}
try {
const request = createDocumentResource({
doctype: 'Verification Instructions Request',
name: this.documentName,
});
await request.setValue.submit(updatedFields);
toast.success("تم تحديث الوثيقة بنجاح.");
} catch (error) {
console.error("Error updating document fields:", error);
toast.error("حدث خطأ أثناء تحديث الوثيقة.");
}
},
/**
* دالة التحقق من صحة بيانات Step 1
*/
validateStep1(): boolean {
let isValid = true;
const requiredFields: (keyof Step1Data)[] = [
'employer_name',
'first_name',
'last_name',
// 'country_now',
// 'city',
// 'governorate',
'zip_code',
'location_text',
// 'street_address',
'date_living_address',
'email',
'date_of_birth',
];
requiredFields.forEach((field) => {
const fieldData = this.step1[field];
if (!fieldData.value || (Array.isArray(fieldData.value) && fieldData.value.length === 0)) {
this.updateStep1(field, {
isValid: false,
validationMessage: 'هذا الحقل مطلوب.',
});
isValid = false;
} else {
this.updateStep1(field, {
isValid: true,
validationMessage: '',
});
}
});
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (this.step1.email.value && !emailPattern.test(this.step1.email.value)) {
this.updateStep1('email', {
isValid: false,
validationMessage: 'يرجى إدخال بريد إلكتروني صحيح.',
});
isValid = false;
} else if (this.step1.email.value) {
this.updateStep1('email', {
isValid: true,
validationMessage: '',
});
}
return isValid;
},
/**
* دالة التحقق من صحة بيانات Step 2
*/
validateStep2(): boolean {
let isValid = true;
this.step2.educationInformation.forEach(education => {
if (!education.name_of_school_or_college_university || !education.field_of_study_or_major) {
isValid = false;
}
});
return isValid;
},
/**
* دالة الحفظ لخطوة Step 1
*/
async saveStep1() {
const toast = useToast();
// التحقق من صحة البيانات
if (!this.validateStep1()) {
toast.error('يرجى تصحيح الأخطاء قبل الحفظ.');
throw new Error('Validation failed');
}
// تجهيز البيانات للإرسال
const dataToSubmit: UpdateFields = {};
for (const key in this.step1) {
if (Object.prototype.hasOwnProperty.call(this.step1, key)) {
const field = key as keyof Step1Data;
dataToSubmit[key] = this.step1[field].value;
}
}
// إرسال البيانات إلى Doctype
try {
await this.updateDocumentFields(dataToSubmit);
toast.success('تم حفظ البيانات بنجاح.');
} catch (error) {
throw error;
}
},
/**
* دالة الحفظ لخطوة Step 2
*/
async saveStep2() {
const toast = useToast();
if (!this.validateStep2()) {
toast.error('يرجى تصحيح الأخطاء قبل الحفظ.');
throw new Error('Validation failed');
}
const dataToSubmit: UpdateFields = {
education_information: this.step2.educationInformation,
};
try {
await this.updateDocumentFields(dataToSubmit);
toast.success('تم حفظ بيانات التعليم بنجاح.');
} catch (error) {
throw error;
}
},
},
});
The verificationRequest.ts file you've provided is a Pinia store for managing state related to a verification request form. Here's an explanation of its components and functionality:
Structure and Components
Imports:
defineStore from Pinia to define a new state management store.
Data types such as HomeData, Step1Data, Step2Data, RequestData, ValidationResult, and UpdateFields from an assumed types file.
Functions such as createDocumentResource, createRequestList, and updateFieldsInRequestList are likely API functions used for interacting with a backend service.
The ref function from Vue for creating reactive state.
useToast from vue-toastification for displaying notifications.
Interfaces and State:
StepValidation: Represents a validation result structure.
VerificationRequestStoreState: Represents the state structure for the store, containing fields for different steps, such as home, step1, and step2, along with a documentName and validations.
Default State:
getDefaultState: A function that initializes the store's default state. This includes default values and validation status for various fields in home, step1, and step2.
Store Definition:
The store is named verificationRequest and includes state, actions, and potentially other options for managing the form data and interactions with a backend service.
Key Actions
State Management:
setDocumentName: Sets the document name.
State update functions (updateHome, updateStep1, updateStep2) for updating fields in the home, step1, and step2 sections respectively.
resetStore: Resets the store to its default state.
Document Operations:
loadDocument: Loads an existing document or creates a new one if none exists.
createNewDocument: Creates a new document with initial fields.
updateDocumentFields: Updates fields within the current document.
Validation Functions:
validateStep1: Validates the fields for Step 1 with conditions for required fields and email format.
validateStep2: Validates Step 2 to ensure education information is complete.
Save Functions:
saveStep1 and saveStep2: Save functions for respective steps that validate data and update the document fields upon passing validation.
Usage and Flow
The store assumes a multi-step form process where the user fills out information in steps. Each step has its own validation and persistence logic.
The loadDocument function initializes the form state by fetching or creating a document.
Users can update fields interactively using the state update functions. These functions ensure that only specified parts of the state are updated without impacting the rest.
Validation ensures that the required data is present and correctly formatted before saving to the backend.
Notifications inform the user of success or errors in document operations.
This Pinia store is structured to manage a form-driven process with robust validation, state management, and backend interaction, likely making it a component of a larger application involving user document verification or similar tasks.
The types.ts file you've provided defines TypeScript interfaces that represent the structure and types of form-related data for a multi-step verification request process. Here's an explanation of its components:
FormField Interface
FormField<T = any>: A generic interface representing a form field with:
value: The actual value of the form field.
isValid: Indicates if the value is valid.
validationMessage: A message indicating validation feedback.
touched (optional): Indicates if the field has been interacted with, useful for determining when to show validation messages.
Interfaces for Step Data
These interfaces define the structure of data for each form step:
HomeData:
Represents the form fields related to the "home" step.
Includes fields like country, mobile_number, is_degree_or_diploma, from_time, and to_time.
Step1Data:
Includes personal and contact information fields such as employer_name, first_name, last_name, middle_name, suffix, alias_name, country_now, city, governorate, zip_code, location_text, street_address, date_living_address, phone, email, and date_of_birth.
EducationInformation:
Represents detailed education information used in Step2Data, including fields like name_of_school_or_college_university, field_of_study_or_major, and dates.
Step2Data:
Contains an array of EducationInformation objects.
Validation Result Interface
ValidationResult: Represents the result of a validation process, mapping field names to validation status and messages.
Request Data Interface
RequestData:
Represents a comprehensive set of data meant to be sent to a server.
Combines fields from HomeData, Step1Data, and Step2Data to encapsulate all form data.
Update Fields Interface
UpdateFields:
A flexible structure to represent any updated fields when sending changes to a backend service.
Key-value pairs where keys are field names and values are new data for those fields.
FormData Type
FormData:
A utility type combining HomeData, Step1Data, and Step2Data for easy handling of form data in other parts of the application.
Usage Summary
These interfaces serve as a blueprint for managing form data in your application using TypeScript's type-checking features.
They ensure consistency in data handling across multiple components and steps, and they help to catch type-related errors during development.
When interacting with the Pinia store or any other logic processing this data, these types provide a clear contract for what shape the data should take.
Having these typed definitions is crucial in maintaining clarity and consistency in a complex form-driven application, significantly enhancing maintainability and reducing bugs related to data handling.
حتى الآن قمت بمشاركة ملفين فقط وهما verificationRequest.ts و types.ts. سأعيد مشاركتها بشكل كامل دون إدخال أية تعديلات، كل ملف على حدى: