update create client form

This commit is contained in:
Casey Wittrock 2025-11-03 01:54:55 -06:00
parent 1f33262e90
commit 2cfe7ed8e6
9 changed files with 1856 additions and 1412 deletions

2
.gitignore vendored
View File

@ -5,6 +5,8 @@
tags
node_modules
__pycache__
venv/
.venv/
*dist/
.vscode/

View File

@ -5,28 +5,27 @@ from urllib.parse import urlparse
allowed_hosts = ["api.zippopotam.us"] # Update this list with trusted domains as needed
@frappe.whitelist(allow_guest=True)
def proxy_request(url, method="GET", data=None, headers=None):
def request(url, method="GET", data=None, headers=None):
"""
Generic proxy for external API requests.
WARNING: Only allow requests to trusted domains.
"""
parsed_url = urlparse(url)
if parsed_url.hostname not in allowed_hosts:
frappe.throw(f"Rquests to {parsed_url.hostname} are not allowed.", frappe.PermissionError)
frappe.throw(f"Requests to {parsed_url.hostname} are not allowed.", frappe.PermissionError)
try:
resp = requests.request(
method=method.upper(),
url=url,
json=frappe.parse_json(data) if data else None,
headers=frappe.parse_json(headers) if headers else None,
timeout=10
)
resp.raise_for_status()
try:
resp = requests.request(
method=method.upper(),
url=url,
json=frappe.parse_json(data) if data else None,
headers=frappe.parse_json(headers) if headers else None,
timeout=10
)
resp.raise_for_status()
try:
return resp.json()
except ValueError:
return {"text": resp.text}
except requests.exceptions.RequestException as e:
frappe.log_error(message=str(e), title="Proxy Request Failed")
frappe.throw("Failed to fetch data from external API.")
return resp.json()
except ValueError:
return {"text": resp.text}
except requests.exceptions.RequestException as e:
frappe.log_error(message=str(e), title="Proxy Request Failed")
frappe.throw("Failed to fetch data from external API.")

File diff suppressed because it is too large Load Diff

View File

@ -35,10 +35,10 @@ import ScrollPanel from "primevue/scrollpanel";
border-radius: 10px;
padding: 10px;
border: 4px solid rgb(235, 230, 230);
max-width: 1280px;
min-width: 800px;
max-width: 2500px;
width: 100%;
margin: 10px auto;
min-height: 87vh;
height: 83vh;
}
#display-content {
@ -47,6 +47,6 @@ import ScrollPanel from "primevue/scrollpanel";
margin-right: auto;
max-width: 50vw;
min-width: 80%;
max-height: 87vh;
height: 100%;
}
</style>

View File

@ -1,25 +1,20 @@
import DataUtils from "./utils";
import axios from "axios";
const ZIPPOPOTAMUS_BASE_URL = "https://api.zippopotam.us/us";
class Api {
static async request(url, method = "get", data = {}) {
static async request(url, method = "GET", data = {}) {
try {
const response = await axios({
url,
method,
data,
withCredentials: false,
timeout: 10000, // 10 second timeout
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
console.log("DEBUG: API - Request Response: ", response.data);
return response.data;
const response = await frappe.call({
method: "custom_ui.api.proxy.request",
args: {
url,
method,
data: JSON.stringify(data),
},
});
console.log("DEBUG: API - Request Response: ", response);
return response.message;
} catch (error) {
console.error("DEBUG: API - Request Error: ", error);
// Re-throw the error so calling code can handle it
@ -80,8 +75,8 @@ class Api {
/**
* Fetch a list of documents from a specific doctype.
*
* @param {String} doctype
* @param {string[]} fields
* @param {String} doctype
* @param {string[]} fields
* @returns {Promise<Object[]>}
*/
static async getDocsList(doctype, fields = []) {
@ -93,8 +88,8 @@ class Api {
/**
* Fetch a detailed document by doctype and name.
*
* @param {String} doctype
* @param {String} name
* @param {String} doctype
* @param {String} name
* @returns {Promise<Object>}
*/
static async getDetailedDoc(doctype, name) {
@ -105,36 +100,27 @@ class Api {
/**
* Fetch a list of places (city/state) by zipcode using Zippopotamus API.
*
*
* @param {String} zipcode
* @returns {Promise<Object[]>}
*/
static async getCityStateByZip(zipcode) {
const url = `${ZIPPOPOTAMUS_BASE_URL}/${zipcode}`;
try {
const response = await this.request(url);
const { places } = response || {};
if (!places || places.length === 0) {
throw new Error(`No location data found for zip code ${zipcode}`);
}
return places;
} catch (error) {
console.error("DEBUG: API - getCityStateByZip Error: ", error);
// Provide more specific error information
if (error.code === 'ERR_NETWORK') {
throw new Error('Network error: Unable to connect to location service. This may be due to CORS restrictions or network connectivity issues.');
} else if (error.response?.status === 404) {
throw new Error(`Zip code ${zipcode} not found in database.`);
} else if (error.code === 'ECONNABORTED') {
throw new Error('Request timeout: Location service is taking too long to respond.');
}
// Re-throw the original error if we can't categorize it
throw error;
const response = await this.request(url);
const { places } = response || {};
if (!places || places.length === 0) {
throw new Error(`No location data found for zip code ${zipcode}`);
}
return places;
}
/**
* Fetch a list of Customer names.
* @returns {Promise<String[]>}
*/
static async getCustomerNames() {
const customers = await this.getDocsList("Customer", ["name"]);
return customers.map((customer) => customer.name);
}
}

View File

@ -1,336 +0,0 @@
<!-- Modal Usage Examples -->
<template>
<div class="modal-examples">
<h2>Modal Component Examples</h2>
<!-- Example buttons to trigger different modal types -->
<div class="example-buttons">
<v-btn @click="showBasicModal" color="primary">Basic Modal</v-btn>
<v-btn @click="showFormModal" color="secondary">Form Modal</v-btn>
<v-btn @click="showConfirmModal" color="warning">Confirmation Modal</v-btn>
<v-btn @click="showFullscreenModal" color="success">Fullscreen Modal</v-btn>
<v-btn @click="showCustomModal" color="info">Custom Styled Modal</v-btn>
</div>
<!-- Basic Modal -->
<Modal
v-model:visible="basicModalVisible"
:options="basicModalOptions"
@close="onBasicModalClose"
@confirm="onBasicModalConfirm"
>
<p>This is a basic modal with default settings.</p>
<p>You can put any content here!</p>
</Modal>
<!-- Form Modal -->
<Modal
v-model:visible="formModalVisible"
:options="formModalOptions"
@close="onFormModalClose"
@confirm="onFormModalConfirm"
>
<template #title>
<v-icon class="mr-2">mdi-account-plus</v-icon>
Add New User
</template>
<v-form ref="userForm" v-model="formValid">
<v-text-field
v-model="userForm.name"
label="Full Name"
:rules="[v => !!v || 'Name is required']"
required
/>
<v-text-field
v-model="userForm.email"
label="Email"
type="email"
:rules="emailRules"
required
/>
<v-select
v-model="userForm.role"
:items="roleOptions"
label="Role"
:rules="[v => !!v || 'Role is required']"
required
/>
</v-form>
</Modal>
<!-- Confirmation Modal -->
<Modal
v-model:visible="confirmModalVisible"
:options="confirmModalOptions"
@confirm="onDeleteConfirm"
@cancel="onDeleteCancel"
>
<div class="text-center">
<v-icon size="64" color="warning" class="mb-4">mdi-alert-circle</v-icon>
<h3 class="mb-2">Are you sure?</h3>
<p>This action cannot be undone. The item will be permanently deleted.</p>
</div>
</Modal>
<!-- Fullscreen Modal -->
<Modal
v-model:visible="fullscreenModalVisible"
:options="fullscreenModalOptions"
@close="onFullscreenModalClose"
>
<template #title>
Fullscreen Content
</template>
<div class="fullscreen-content">
<v-row>
<v-col cols="12" md="6">
<v-card>
<v-card-title>Left Panel</v-card-title>
<v-card-text>
<p>This is a fullscreen modal that can contain complex layouts.</p>
<v-list>
<v-list-item v-for="i in 10" :key="i">
<v-list-item-title>Item {{ i }}</v-list-item-title>
</v-list-item>
</v-list>
</v-card-text>
</v-card>
</v-col>
<v-col cols="12" md="6">
<v-card>
<v-card-title>Right Panel</v-card-title>
<v-card-text>
<v-img
src="https://picsum.photos/400/200"
height="200"
class="mb-4"
/>
<p>You can include any Vue components here.</p>
</v-card-text>
</v-card>
</v-col>
</v-row>
</div>
</Modal>
<!-- Custom Styled Modal -->
<Modal
v-model:visible="customModalVisible"
:options="customModalOptions"
@close="onCustomModalClose"
>
<template #title>
<div class="custom-title">
<v-icon class="mr-2">mdi-palette</v-icon>
Custom Styled Modal
</div>
</template>
<div class="custom-content">
<v-card variant="outlined" class="mb-4">
<v-card-text>
<v-icon size="32" color="primary" class="mr-2">mdi-information</v-icon>
This modal demonstrates custom styling options.
</v-card-text>
</v-card>
<v-timeline density="compact">
<v-timeline-item
v-for="item in timelineItems"
:key="item.id"
:dot-color="item.color"
size="small"
>
<v-card>
<v-card-title>{{ item.title }}</v-card-title>
<v-card-subtitle>{{ item.time }}</v-card-subtitle>
</v-card>
</v-timeline-item>
</v-timeline>
</div>
<template #actions="{ close }">
<v-btn color="gradient" variant="elevated" @click="close">
<v-icon class="mr-1">mdi-check</v-icon>
Got it!
</v-btn>
</template>
</Modal>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import Modal from './common/Modal.vue'
// Basic Modal
const basicModalVisible = ref(false)
const basicModalOptions = {
title: 'Basic Modal',
maxWidth: '400px',
showActions: true
}
// Form Modal
const formModalVisible = ref(false)
const formValid = ref(false)
const userForm = reactive({
name: '',
email: '',
role: ''
})
const formModalOptions = {
maxWidth: '500px',
persistent: true,
confirmButtonText: 'Save User',
confirmButtonColor: 'success',
loading: false
}
const roleOptions = ['Admin', 'User', 'Manager', 'Viewer']
const emailRules = [
v => !!v || 'Email is required',
v => /.+@.+\..+/.test(v) || 'Email must be valid'
]
// Confirmation Modal
const confirmModalVisible = ref(false)
const confirmModalOptions = {
title: 'Confirm Deletion',
maxWidth: '400px',
persistent: false,
confirmButtonText: 'Delete',
confirmButtonColor: 'error',
cancelButtonText: 'Keep',
cardColor: 'surface-variant'
}
// Fullscreen Modal
const fullscreenModalVisible = ref(false)
const fullscreenModalOptions = {
fullscreen: true,
showActions: false,
scrollable: true
}
// Custom Modal
const customModalVisible = ref(false)
const customModalOptions = {
maxWidth: '600px',
cardColor: 'primary',
cardVariant: 'elevated',
elevation: 12,
headerClass: 'custom-header',
contentClass: 'custom-content-class',
showActions: false,
overlayOpacity: 0.8,
transition: 'scale-transition'
}
const timelineItems = [
{ id: 1, title: 'Project Started', time: '2 hours ago', color: 'primary' },
{ id: 2, title: 'First Milestone', time: '1 hour ago', color: 'success' },
{ id: 3, title: 'Review Phase', time: '30 minutes ago', color: 'warning' }
]
// Modal event handlers
const showBasicModal = () => {
basicModalVisible.value = true
}
const onBasicModalClose = () => {
console.log('Basic modal closed')
}
const onBasicModalConfirm = () => {
console.log('Basic modal confirmed')
}
const showFormModal = () => {
formModalVisible.value = true
}
const onFormModalClose = () => {
// Reset form
Object.assign(userForm, { name: '', email: '', role: '' })
}
const onFormModalConfirm = async () => {
if (formValid.value) {
formModalOptions.loading = true
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 1000))
console.log('User saved:', userForm)
formModalOptions.loading = false
}
}
const showConfirmModal = () => {
confirmModalVisible.value = true
}
const onDeleteConfirm = () => {
console.log('Item deleted')
}
const onDeleteCancel = () => {
console.log('Deletion cancelled')
}
const showFullscreenModal = () => {
fullscreenModalVisible.value = true
}
const onFullscreenModalClose = () => {
console.log('Fullscreen modal closed')
}
const showCustomModal = () => {
customModalVisible.value = true
}
const onCustomModalClose = () => {
console.log('Custom modal closed')
}
</script>
<style scoped>
.modal-examples {
padding: 20px;
}
.example-buttons {
display: flex;
gap: 16px;
flex-wrap: wrap;
margin-bottom: 20px;
}
.fullscreen-content {
height: 100%;
}
.custom-title {
display: flex;
align-items: center;
color: white;
}
.custom-content {
background: linear-gradient(45deg, #f3f4f6 0%, #ffffff 100%);
padding: 16px;
border-radius: 8px;
}
.custom-header {
background: linear-gradient(45deg, #1976d2 0%, #42a5f5 100%);
color: white;
}
.custom-content-class {
background-color: #fafafa;
}
</style>

File diff suppressed because it is too large Load Diff

View File

@ -1,413 +1,473 @@
<template>
<Modal
:visible="isVisible"
:options="modalOptions"
@update:visible="handleVisibilityChange"
@close="handleClose"
>
<template #title>
Create New Client
</template>
<!-- Status Message -->
<div v-if="statusMessage" class="status-message" :class="`status-${statusType}`">
<v-icon
:icon="statusType === 'warning' ? 'mdi-alert' : statusType === 'error' ? 'mdi-alert-circle' : 'mdi-information'"
size="small"
class="mr-2"
/>
{{ statusMessage }}
</div>
<Form
:fields="formFields"
:form-data="formData"
:on-submit="handleSubmit"
:show-cancel-button="true"
:validate-on-change="false"
:validate-on-blur="true"
:validate-on-submit="true"
submit-button-text="Create Client"
cancel-button-text="Cancel"
@submit="handleSubmit"
@cancel="handleCancel"
@change="handleFieldChange"
@blur="handleFieldBlur"
/>
</Modal>
<Modal
:visible="isVisible"
:options="modalOptions"
@update:visible="handleVisibilityChange"
@close="handleClose"
>
<template #title> Create New Client </template>
<!-- Status Message -->
<div v-if="statusMessage" class="status-message" :class="`status-${statusType}`">
<i :class="getStatusIcon(statusType)" class="status-icon"></i>
{{ statusMessage }}
</div>
<Form
:fields="formFields"
:form-data="formData"
:show-cancel-button="true"
:validate-on-change="false"
:validate-on-blur="true"
:validate-on-submit="true"
submit-button-text="Create Client"
cancel-button-text="Cancel"
@submit="handleSubmit"
@cancel="handleCancel"
/>
</Modal>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useModalStore } from '@/stores/modal'
import Modal from '@/components/common/Modal.vue'
import Form from '@/components/common/Form.vue'
import Api from '@/api'
import { ref, reactive, computed, watch, watchEffect } from "vue";
import { useModalStore } from "@/stores/modal";
import Modal from "@/components/common/Modal.vue";
import Form from "@/components/common/Form.vue";
import Api from "@/api";
import DataUtils from "../../utils";
const modalStore = useModalStore()
const modalStore = useModalStore();
// Modal visibility computed property
const isVisible = computed(() => modalStore.isModalOpen('createClient'))
const isVisible = computed(() => modalStore.isModalOpen("createClient"));
const customerNames = ref([]);
// Form data
const formData = reactive({
name: '',
address: '',
phone: '',
email: '',
zipcode: '',
city: '',
state: ''
})
name: "",
address: "",
phone: "",
email: "",
zipcode: "",
city: "",
state: "",
});
// Available cities for the selected zipcode
const availableCities = ref([])
const availableCities = ref([]);
// Loading state for zipcode lookup
const isLoadingZipcode = ref(false)
const isLoadingZipcode = ref(false);
// Status message for user feedback
const statusMessage = ref('')
const statusType = ref('info') // 'info', 'warning', 'error', 'success'
// US State abbreviations for validation
const US_STATES = [
'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA',
'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD',
'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ',
'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC',
'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY',
'DC' // District of Columbia
]
const statusMessage = ref("");
const statusType = ref("info"); // 'info', 'warning', 'error', 'success'
// Modal configuration
const modalOptions = {
maxWidth: '600px',
persistent: false,
showActions: false,
title: 'Create New Client',
overlayColor: 'rgb(59, 130, 246)', // Blue background
overlayOpacity: 0.8,
cardClass: 'create-client-modal',
closeOnOutsideClick: true,
closeOnEscape: true
}
maxWidth: "600px",
persistent: false,
showActions: false,
title: "Create New Client",
overlayColor: "rgb(59, 130, 246)", // Blue background
overlayOpacity: 0.8,
cardClass: "create-client-modal",
closeOnOutsideClick: true,
closeOnEscape: true,
};
// Form field definitions
const formFields = computed(() => [
{
name: 'name',
label: 'Client Name',
type: 'text',
required: true,
placeholder: 'Enter client name',
cols: 12,
md: 12
},
{
name: 'address',
label: 'Address',
type: 'text',
required: true,
placeholder: 'Enter street address',
cols: 12,
md: 12
},
{
name: 'phone',
label: 'Phone Number',
type: 'text',
required: true,
placeholder: 'Enter phone number',
format: 'tel',
cols: 12,
md: 6,
validate: (value) => {
if (value && !/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/.test(value)) {
return 'Please enter a valid phone number'
}
return null
}
},
{
name: 'email',
label: 'Email Address',
type: 'text',
required: true,
placeholder: 'Enter email address',
format: 'email',
cols: 12,
md: 6
},
{
name: 'zipcode',
label: 'Zip Code',
type: 'text',
required: true,
placeholder: 'Enter zip code',
cols: 12,
md: 4,
onChangeOverride: handleZipcodeChange,
validate: (value) => {
if (value && !/^\d{5}(-\d{4})?$/.test(value)) {
return 'Please enter a valid zip code'
}
return null
}
},
{
name: 'city',
label: 'City',
type: availableCities.value.length > 0 ? 'select' : 'text',
required: true,
disabled: false,
placeholder: availableCities.value.length > 0 ? 'Select city' : 'Enter city name',
options: availableCities.value.map(place => ({
label: place['place name'],
value: place['place name']
})),
cols: 12,
md: 4,
helpText: isLoadingZipcode.value
? 'Loading cities...'
: availableCities.value.length > 0
? 'Select from available cities'
: 'Enter city manually (auto-lookup unavailable)'
},
{
name: 'state',
label: 'State',
type: 'text',
required: true,
disabled: availableCities.value.length > 0,
placeholder: availableCities.value.length > 0 ? 'Auto-populated' : 'Enter state (e.g., CA, TX, NY)',
cols: 12,
md: 4,
helpText: availableCities.value.length > 0
? 'Auto-populated from zip code'
: 'Enter state abbreviation manually',
validate: (value) => {
// Only validate manually entered states (when API lookup failed)
if (availableCities.value.length === 0 && value) {
const upperValue = value.toUpperCase()
if (!US_STATES.includes(upperValue)) {
return 'Please enter a valid US state abbreviation (e.g., CA, TX, NY)'
}
// Auto-correct to uppercase
if (value !== upperValue) {
formData.state = upperValue
}
}
return null
}
}
])
{
name: "name",
label: "Client Name",
type: "autocomplete", // Changed from 'select' to 'autocomplete'
required: true,
placeholder: "Type or select client name",
cols: 12,
options: customerNames.value, // Direct array of strings
forceSelection: false, // Allow custom entries not in the list
dropdown: true,
// For string arrays, don't set optionLabel at all
helpText: "Select an existing client or enter a new client name",
// Let the Form component handle filtering automatically
},
{
name: "address",
label: "Address",
type: "text",
required: true,
placeholder: "Enter street address",
cols: 12,
md: 12,
},
{
name: "phone",
label: "Phone Number",
type: "text",
required: true,
placeholder: "Enter phone number",
format: "tel",
cols: 12,
md: 6,
validate: (value) => {
if (value && !/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/.test(value)) {
return "Please enter a valid phone number";
}
return null;
},
},
{
name: "email",
label: "Email Address",
type: "text",
required: true,
placeholder: "Enter email address",
format: "email",
cols: 12,
md: 6,
},
{
name: "zipcode",
label: "Zip Code",
type: "text",
required: true,
placeholder: "Enter zip code",
cols: 12,
md: 4,
onChangeOverride: handleZipcodeChange,
validate: (value) => {
if (value && !/^\d{5}(-\d{4})?$/.test(value)) {
return "Please enter a valid zip code";
}
return null;
},
},
{
name: "city",
label: "City",
type: availableCities.value.length > 0 ? "select" : "text",
required: true,
disabled: false,
placeholder: availableCities.value.length > 0 ? "Select city" : "Enter city name",
options: availableCities.value.map((place) => ({
label: place["place name"],
value: place["place name"],
})),
cols: 12,
md: 4,
helpText: isLoadingZipcode.value
? "Loading cities..."
: availableCities.value.length > 0
? "Select from available cities"
: "Enter city manually (auto-lookup unavailable)",
},
{
name: "state",
label: "State",
type: "select",
options: DataUtils.US_STATES.map((stateAbbr) => ({
label: stateAbbr,
value: stateAbbr,
})),
required: true,
disabled: availableCities.value.length > 0,
placeholder:
availableCities.value.length > 0 ? "Auto-populated" : "Enter state (e.g., CA, TX, NY)",
cols: 12,
md: 4,
helpText:
availableCities.value.length > 0
? "Auto-populated from zip code"
: "Enter state abbreviation manually",
validate: (value) => {
// Only validate manually entered states (when API lookup failed)
if (availableCities.value.length === 0 && value) {
const upperValue = value.toUpperCase();
if (!DataUtils.US_STATES.includes(upperValue)) {
return "Please enter a valid US state abbreviation (e.g., CA, TX, NY)";
}
}
return null;
},
},
]);
// Handle zipcode change and API lookup
async function handleZipcodeChange(value, fieldName, formData) {
if (fieldName === 'zipcode' && value && value.length >= 5) {
// Only process if it's a valid zipcode format
const zipcode = value.replace(/\D/g, '').substring(0, 5)
if (zipcode.length === 5) {
isLoadingZipcode.value = true
try {
const places = await Api.getCityStateByZip(zipcode)
if (places && places.length > 0) {
availableCities.value = places
// Auto-populate state from first result
formData.state = places[0].state
// If only one city, auto-select it
if (places.length === 1) {
formData.city = places[0]['place name']
showStatusMessage(`Location found: ${places[0]['place name']}, ${places[0].state}`, 'success')
} else {
// Clear city selection if multiple cities
formData.city = ''
showStatusMessage(`Found ${places.length} cities for this zip code. Please select one.`, 'info')
}
} else {
// No results found - enable manual entry
handleApiFailure(formData, 'No location data found for this zip code')
}
} catch (error) {
console.error('Error fetching city/state data:', error)
// Check if it's a network/CORS error
if (error.code === 'ERR_NETWORK' || error.message.includes('Network Error')) {
handleApiFailure(formData, 'Unable to fetch location data. Please enter city and state manually.')
} else {
handleApiFailure(formData, 'Location lookup failed. Please enter city and state manually.')
}
} finally {
isLoadingZipcode.value = false
}
}
}
async function handleZipcodeChange(value, fieldName, currentFormData) {
if (fieldName === "zipcode" && value && value.length >= 5) {
// Only process if it's a valid zipcode format
const zipcode = value.replace(/\D/g, "").substring(0, 5);
if (zipcode.length === 5) {
isLoadingZipcode.value = true;
try {
const places = await Api.getCityStateByZip(zipcode);
console.log("API response for zipcode", zipcode, ":", places);
if (places && places.length > 0) {
availableCities.value = places;
// Update the reactive formData directly to ensure reactivity
// Use "state abbreviation" instead of "state" for proper abbreviation format
const stateValue = places[0]["state abbreviation"] || places[0].state;
console.log("Setting state to:", stateValue, "from place object:", places[0]);
formData.state = stateValue;
// If only one city, auto-select it
if (places.length === 1) {
formData.city = places[0]["place name"];
showStatusMessage(
`Location found: ${places[0]["place name"]}, ${places[0]["state abbreviation"] || places[0].state}`,
"success",
);
} else {
// Clear city selection if multiple cities
formData.city = "";
showStatusMessage(
`Found ${places.length} cities for this zip code. Please select one.`,
"info",
);
}
} else {
// No results found - enable manual entry
handleApiFailure("No location data found for this zip code");
}
} catch (error) {
console.error("Error fetching city/state data:", error);
// Check if it's a network/CORS error
if (error.code === "ERR_NETWORK" || error.message.includes("Network Error")) {
handleApiFailure(
"Unable to fetch location data. Please enter city and state manually.",
);
} else {
handleApiFailure(
"Location lookup failed. Please enter city and state manually.",
);
}
} finally {
isLoadingZipcode.value = false;
}
}
}
}
// Handle API failure by enabling manual entry
function handleApiFailure(formData, message) {
console.warn('Zipcode API failed:', message)
// Clear existing data
availableCities.value = []
formData.city = ''
formData.state = ''
// Show user-friendly message
showStatusMessage(message, 'warning')
// Handle API failure by enabling manual entry
function handleApiFailure(message) {
console.warn("Zipcode API failed:", message);
// Clear existing data
availableCities.value = [];
formData.city = "";
formData.state = "";
// Show user-friendly message
showStatusMessage(message, "warning");
}
// Show status message to user
function showStatusMessage(message, type = 'info') {
statusMessage.value = message
statusType.value = type
// Auto-clear message after 5 seconds
setTimeout(() => {
statusMessage.value = ''
}, 5000)
function showStatusMessage(message, type = "info") {
statusMessage.value = message;
statusType.value = type;
// Auto-clear message after 5 seconds
setTimeout(() => {
statusMessage.value = "";
}, 5000);
}
// Handle form field changes
function handleFieldChange(event) {
console.log('Field changed:', event)
}
// Handle form field blur
function handleFieldBlur(event) {
console.log('Field blurred:', event)
// Get icon class for status messages
function getStatusIcon(type) {
switch (type) {
case "warning":
return "pi pi-exclamation-triangle";
case "error":
return "pi pi-times-circle";
case "success":
return "pi pi-check-circle";
default:
return "pi pi-info-circle";
}
}
// Handle form submission
function handleSubmit(data) {
console.log('Form submitted with data:', data)
// TODO: Add API call to create client when ready
// For now, just log the data and close the modal
// Show success message (you can customize this)
alert('Client would be created with the following data:\n' + JSON.stringify(data, null, 2))
// Close the modal
handleClose()
async function handleSubmit(submittedFormData) {
try {
showStatusMessage("Creating client...", "info");
// Convert form data to the expected format
const clientData = {
name: submittedFormData.name,
address: submittedFormData.address,
phone: submittedFormData.phone,
email: submittedFormData.email,
zipcode: submittedFormData.zipcode,
city: submittedFormData.city,
state: submittedFormData.state,
};
// Call API to create client
const response = await Api.createClient(clientData);
if (response && response.success) {
showStatusMessage("Client created successfully!", "success");
// Close modal after a brief delay
setTimeout(() => {
handleClose();
}, 1500);
} else {
throw new Error(response?.message || "Failed to create client");
}
} catch (error) {
console.error("Error creating client:", error);
showStatusMessage(error.message || "Failed to create client. Please try again.", "error");
}
}
// Handle cancel action
function handleCancel() {
handleClose()
handleClose();
}
// Handle modal close
function handleClose() {
modalStore.closeCreateClient()
resetForm()
modalStore.closeCreateClient();
resetForm();
}
// Handle visibility changes
function handleVisibilityChange(visible) {
if (!visible) {
handleClose()
}
if (!visible) {
handleClose();
}
}
// Reset form data
function resetForm() {
Object.keys(formData).forEach(key => {
formData[key] = ''
})
availableCities.value = []
isLoadingZipcode.value = false
statusMessage.value = ''
statusType.value = 'info'
Object.keys(formData).forEach((key) => {
formData[key] = "";
});
availableCities.value = [];
isLoadingZipcode.value = false;
statusMessage.value = "";
statusType.value = "info";
}
// Initialize modal in store when component mounts
modalStore.initializeModal('createClient', {
closeOnEscape: true,
closeOnOutsideClick: true
})
modalStore.initializeModal("createClient", {
closeOnEscape: true,
closeOnOutsideClick: true,
});
watch(isVisible, async () => {
if (isVisible.value) {
try {
const names = await Api.getCustomerNames();
console.log("Loaded customer names:", names);
console.log("Customer names type:", typeof names, Array.isArray(names));
console.log("First customer name:", names[0], typeof names[0]);
customerNames.value = names;
// Debug: Let's also set some test data to see if autocomplete works at all
console.log("Setting customerNames to:", customerNames.value);
} catch (error) {
console.error("Error loading customer names:", error);
// Set some test data to debug if autocomplete works
customerNames.value = ["Test Customer 1", "Test Customer 2", "Another Client"];
console.log("Using test customer names:", customerNames.value);
}
}
});
</script>
<style scoped>
.create-client-modal {
border-radius: 12px;
border-radius: 12px;
}
/* Custom styling for the modal content */
:deep(.modal-header) {
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
color: white;
background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
color: white;
}
:deep(.modal-title) {
font-weight: 600;
font-size: 1.25rem;
font-weight: 600;
font-size: 1.25rem;
}
:deep(.modal-close-btn) {
color: white !important;
color: white !important;
}
:deep(.modal-content) {
padding: 24px;
padding: 24px;
}
/* Form styling adjustments */
:deep(.v-text-field) {
margin-bottom: 8px;
/* Form styling adjustments for PrimeVue components */
:deep(.p-inputtext),
:deep(.p-dropdown),
:deep(.p-autocomplete) {
margin-bottom: 8px;
}
:deep(.v-select) {
margin-bottom: 8px;
/* Ensure AutoComplete panel appears above modal */
:global(.p-autocomplete-overlay) {
z-index: 9999 !important;
}
:deep(.v-btn) {
text-transform: none;
font-weight: 500;
:global(.p-autocomplete-panel) {
z-index: 9999 !important;
}
:deep(.v-btn.v-btn--variant-elevated) {
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
:deep(.p-button) {
text-transform: none;
font-weight: 500;
}
:deep(.p-button:not(.p-button-text)) {
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
/* Status message styling */
.status-message {
padding: 12px 16px;
margin-bottom: 16px;
border-radius: 6px;
display: flex;
align-items: center;
font-size: 0.9rem;
border-left: 4px solid;
padding: 12px 16px;
margin-bottom: 16px;
border-radius: 6px;
display: flex;
align-items: center;
font-size: 0.9rem;
border-left: 4px solid;
}
.status-icon {
margin-right: 8px;
font-size: 1rem;
}
.status-info {
background-color: #e3f2fd;
color: #1565c0;
border-left-color: #2196f3;
background-color: #e3f2fd;
color: #1565c0;
border-left-color: #2196f3;
}
.status-warning {
background-color: #fff3e0;
color: #ef6c00;
border-left-color: #ff9800;
background-color: #fff3e0;
color: #ef6c00;
border-left-color: #ff9800;
}
.status-error {
background-color: #ffebee;
color: #c62828;
border-left-color: #f44336;
background-color: #ffebee;
color: #c62828;
border-left-color: #f44336;
}
.status-success {
background-color: #e8f5e8;
color: #2e7d32;
border-left-color: #4caf50;
background-color: #e8f5e8;
color: #2e7d32;
border-left-color: #4caf50;
}
</style>
</style>

View File

@ -1639,6 +1639,14 @@ class DataUtils {
materials: ["Sprinkler heads - 3", "Nozzles - 5", "Wire nuts - 10"],
},
];
static US_STATES = [
'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'FL', 'GA',
'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MD',
'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ',
'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC',
'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'
];
}
export default DataUtils;