Adding authnet not tested

This commit is contained in:
2025-09-15 15:30:50 -04:00
parent 7d59c07881
commit 3cf6d1911a
4 changed files with 501 additions and 547 deletions

View File

@@ -1,7 +1,6 @@
<!-- src/pages/card/addcard.vue -->
<template> <template>
<div class="flex"> <div class="flex">
<div class="w-full px-4 md:px-10 py-4"> <div class="w-full px-4 md-px-10 py-4">
<!-- Breadcrumbs --> <!-- Breadcrumbs -->
<div class="text-sm breadcrumbs"> <div class="text-sm breadcrumbs">
<ul> <ul>
@@ -15,27 +14,7 @@
<!-- TOP SECTION: Customer Info --> <!-- TOP SECTION: Customer Info -->
<div class="my-6"> <div class="my-6">
<div class="bg-neutral rounded-lg p-5"> <div class="bg-neutral rounded-lg p-5">
<div class="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-4"> <!-- ... (this section is fine, no changes needed) ... -->
<div>
<div class="text-xl font-bold">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</div>
<div class="text-sm text-gray-400">Account: {{ customer.account_number }}</div>
</div>
<router-link :to="{ name: 'customerProfile', params: { id: customer.id } }" class="btn btn-secondary btn-sm mt-2 sm:mt-0">
View Profile
</router-link>
</div>
<div>
<div>{{ customer.customer_address }}</div>
<div v-if="customer.customer_apt && customer.customer_apt !== 'None'">{{ customer.customer_apt }}</div>
<div>{{ customer.customer_town }}, <span v-if="customer.customer_state == 0">Massachusetts</span>
<span v-else-if="customer.customer_state == 1">Rhode Island</span>
<span v-else-if="customer.customer_state == 2">New Hampshire</span>
<span v-else-if="customer.customer_state == 3">Maine</span>
<span v-else-if="customer.customer_state == 4">Vermont</span>
<span v-else-if="customer.customer_state == 5">Connecticut</span>
<span v-else-if="customer.customer_state == 6">New York</span>
<span v-else>Unknown state</span> {{ customer.customer_zip }}</div>
</div>
</div> </div>
</div> </div>
@@ -44,45 +23,44 @@
<h2 class="text-2xl font-bold mb-4">Add a New Credit Card</h2> <h2 class="text-2xl font-bold mb-4">Add a New Credit Card</h2>
<form @submit.prevent="onSubmit" class="space-y-4"> <form @submit.prevent="onSubmit" class="space-y-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<!-- Name -->
<!-- Name on Card -->
<div class="form-control"> <div class="form-control">
<label class="label"><span class="label-text font-bold">Name on Card</span></label> <label class="label"><span class="label-text font-bold">Name on Card</span></label>
<input v-model="CardForm.name_on_card" type="text" placeholder="" class="input input-bordered input-sm w-full" /> <input v-model="CardForm.name_on_card" type="text" placeholder="Name" class="input input-bordered input-sm w-full" />
<span v-if="v$.CardForm.name_on_card.$error" class="text-red-500 text-xs mt-1">Required.</span> <span v-if="v$.CardForm.name_on_card.$error" class="text-red-500 text-xs mt-1">A valid name_on_card is required.</span>
</div> </div>
<!-- Card Number --> <!-- Card Number -->
<div class="form-control"> <div class="form-control">
<label class="label"><span class="label-text font-bold">Card Number</span></label> <label class="label"><span class="label-text font-bold">Card Number</span></label>
<input v-model="CardForm.card_number" type="text" placeholder="" class="input input-bordered input-sm w-full" /> <input v-model="CardForm.card_number" type="text" placeholder="•••• •••• •••• ••••" class="input input-bordered input-sm w-full" />
<span v-if="v$.CardForm.card_number.$error" class="text-red-500 text-xs mt-1">Required.</span> <span v-if="v$.CardForm.card_number.$error" class="text-red-500 text-xs mt-1">A valid card number is required.</span>
</div>
<!-- CVV (Security Code) -->
<div class="form-control">
<label class="label"><span class="label-text font-bold">CVV</span></label>
<input v-model="CardForm.cvv" type="text" placeholder="123" class="input input-bordered input-sm w-full" />
<span v-if="v$.CardForm.cvv.$error" class="text-red-500 text-xs mt-1">CVV is required.</span>
</div> </div>
<!-- Expiration --> <!-- Expiration -->
<div class="form-control"> <div class="form-control">
<label class="label"><span class="label-text font-bold">Expiration</span></label> <label class="label"><span class="label-text font-bold">Expiration Date</span></label>
<div class="flex gap-2"> <div class="flex gap-2">
<select v-model="CardForm.expiration_month" class="select select-bordered select-sm w-full"> <select v-model="CardForm.expiration_month" class="select select-bordered select-sm w-full">
<option disabled value="">MM</option> <option disabled value="">Month</option>
<option v-for="m in 12" :key="m" :value="String(m).padStart(2, '0')">{{ String(m).padStart(2, '0') }}</option> <option v-for="m in 12" :key="m" :value="String(m).padStart(2, '0')">{{ String(m).padStart(2, '0') }}</option>
</select> </select>
<select v-model="CardForm.expiration_year" class="select select-bordered select-sm w-full"> <select v-model="CardForm.expiration_year" class="select select-bordered select-sm w-full">
<option disabled value="">YYYY</option> <option disabled value="">Year</option>
<option v-for="y in 10" :key="y" :value="new Date().getFullYear() + y - 1">{{ new Date().getFullYear() + y - 1 }}</option> <option v-for="y in 10" :key="y" :value="new Date().getFullYear() + y - 1">{{ new Date().getFullYear() + y - 1 }}</option>
</select> </select>
</div> </div>
<span v-if="v$.CardForm.expiration_month.$error || v$.CardForm.expiration_year.$error" class="text-red-500 text-xs mt-1">Required.</span> <span v-if="v$.CardForm.expiration_month.$error || v$.CardForm.expiration_year.$error" class="text-red-500 text-xs mt-1">Both month and year are required.</span>
</div> </div>
<!-- Security Number (CVV) --> <!-- Card Type dropdown -->
<div class="form-control">
<label class="label"><span class="label-text font-bold">CVV</span></label>
<input v-model="CardForm.security_number" type="text" placeholder="" class="input input-bordered input-sm w-full" />
<span v-if="v$.CardForm.security_number.$error" class="text-red-500 text-xs mt-1">Required.</span>
</div>
<!-- Card Type -->
<div class="form-control"> <div class="form-control">
<label class="label"><span class="label-text font-bold">Card Type</span></label> <label class="label"><span class="label-text font-bold">Card Type</span></label>
<select v-model="CardForm.type_of_card" class="select select-bordered select-sm w-full"> <select v-model="CardForm.type_of_card" class="select select-bordered select-sm w-full">
@@ -95,24 +73,30 @@
<span v-if="v$.CardForm.type_of_card.$error" class="text-red-500 text-xs mt-1">Required.</span> <span v-if="v$.CardForm.type_of_card.$error" class="text-red-500 text-xs mt-1">Required.</span>
</div> </div>
<!-- Billing Zip Code --> <!-- Billing Zip Code input -->
<div class="form-control"> <div class="form-control">
<label class="label"><span class="label-text font-bold">Billing Zip Code</span></label> <label class="label"><span class="label-text font-bold">Billing Zip Code</span></label>
<input v-model="CardForm.zip_code" type="text" placeholder="" class="input input-bordered input-sm w-full" /> <input v-model="CardForm.zip_code" type="text" placeholder="12345" class="input input-bordered input-sm w-full" />
<span v-if="v$.CardForm.zip_code.$error" class="text-red-500 text-xs mt-1">Required.</span>
</div> </div>
<!-- Main Card Checkbox --> <!-- --- FIX: Main Card Checkbox --- -->
<div class="form-control md:col-span-2"> <div class="form-control md:col-span-2">
<label class="label cursor-pointer justify-start gap-4"> <label class="label cursor-pointer justify-start gap-4">
<span class="label-text font-bold">Set as Main Card for this customer</span> <span class="label-text font-bold">Set as Main Card for this customer</span>
<!-- `v-model` binds the checkbox's checked state to the boolean `CardForm.main_card` -->
<input v-model="CardForm.main_card" type="checkbox" class="checkbox checkbox-sm" /> <input v-model="CardForm.main_card" type="checkbox" class="checkbox checkbox-sm" />
</label> </label>
</div> </div>
</div> </div>
<!-- SUBMIT BUTTON --> <!-- SUBMIT BUTTON -->
<div class="pt-4"> <div class="pt-4">
<button type="submit" class="btn btn-primary btn-sm">Save Credit Card</button> <button type="submit" class="btn btn-primary btn-sm" :disabled="isLoading">
<span v-if="isLoading" class="loading loading-spinner loading-xs"></span>
{{ isLoading ? 'Saving...' : 'Save Credit Card' }}
</button>
</div> </div>
</form> </form>
</div> </div>
@@ -120,7 +104,6 @@
</div> </div>
<Footer /> <Footer />
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent } from 'vue' import { defineComponent } from 'vue'
import axios from 'axios' import axios from 'axios'
@@ -140,29 +123,29 @@ export default defineComponent({
v$: useValidate(), v$: useValidate(),
user: null, user: null,
customer: {} as any, customer: {} as any,
// --- REFACTORED: Simplified, flat form object --- isLoading: false,
CardForm: { CardForm: {
name_on_card: '', main_card: false,
card_number: '',
expiration_month: '', expiration_month: '',
expiration_year: '', expiration_year: '',
cvv: '',
type_of_card: '', type_of_card: '',
security_number: '',
card_number: '',
zip_code: '', zip_code: '',
main_card: false, name_on_card: '',
}, },
} }
}, },
validations() { validations() {
return { return {
// --- REFACTORED: Validation points to the flat form object ---
CardForm: { CardForm: {
name_on_card: { required, minLength: minLength(1) }, card_number: { required, minLength: minLength(13) },
expiration_month: { required }, expiration_month: { required },
expiration_year: { required }, expiration_year: { required },
security_number: { required, minLength: minLength(1) }, cvv: { required, minLength: minLength(3) },
type_of_card: { required }, type_of_card: { required },
card_number: { required, minLength: minLength(1) }, zip_code: { required, minLength: minLength(5) },
name_on_card: { required },
}, },
}; };
}, },
@@ -187,24 +170,71 @@ export default defineComponent({
notify({ title: "Error", text: "Could not find customer", type: "error" }); notify({ title: "Error", text: "Could not find customer", type: "error" });
}); });
}, },
CreateCard(payload: any) { async onSubmit() {
const path = `${import.meta.env.VITE_BASE_URL}/payment/card/create/${this.customer.id}`;
axios.post(path, payload, { withCredentials: true, headers: authHeader() })
.then((response: any) => {
if (response.data.ok) {
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
} else {
notify({ title: "Error", text: response.data.error || "Failed to create card.", type: "error" });
}
});
},
onSubmit() {
this.v$.$validate(); this.v$.$validate();
if (!this.v$.$error) { if (this.v$.$error) {
this.CreateCard(this.CardForm);
} else {
notify({ title: "Validation Error", text: "Please fill out all required fields.", type: "error" }); notify({ title: "Validation Error", text: "Please fill out all required fields.", type: "error" });
return;
} }
this.isLoading = true;
// --- STEP 1: PREPARE PAYLOADS FOR BOTH SERVICES ---
// Payload for your Flask backend (it takes all the raw details for your DB)
const flaskPayload = {
card_number: this.CardForm.card_number,
expiration_month: this.CardForm.expiration_month,
expiration_year: this.CardForm.expiration_year,
type_of_card: this.CardForm.type_of_card,
security_number: this.CardForm.cvv, // Your Flask app expects 'security_number'
main_card: this.CardForm.main_card,
zip_code: this.CardForm.zip_code,
name_on_card: this.CardForm.name_on_card, // Your Flask app expects 'name_on_card'
};
// Payload for your FastAPI backend (it only needs the essentials for Authorize.Net)
const fastapiPayload = {
card_number: this.CardForm.card_number.replace(/\s/g, ''),
expiration_date: `${this.CardForm.expiration_year}-${this.CardForm.expiration_month}`,
cvv: this.CardForm.cvv,
main_card: this.CardForm.main_card, // Send this to FastAPI as well
};
// --- STEP 2: CRITICAL CALL - SAVE CARD TO LOCAL DATABASE VIA FLASK ---
try {
const flaskPath = `${import.meta.env.VITE_BASE_URL}/payment/card/create/${this.customer.id}`;
console.log("Attempting to save card to local DB via Flask:", flaskPath);
const flaskResponse = await axios.post(flaskPath, flaskPayload, { withCredentials: true, headers: authHeader() });
if (!flaskResponse.data.ok) {
// If the primary save fails, stop everything and show an error.
throw new Error(flaskResponse.data.error || "Failed to save card.");
}
console.log("Card successfully saved to local database via Flask.");
} catch (error: any) {
const errorMessage = error.response?.data?.error || "A critical error occurred while saving the card.";
notify({ title: "Error", text: errorMessage, type: "error" });
this.isLoading = false; // Stop loading spinner
return; // End the function here
}
// --- STEP 3: BEST-EFFORT CALL - TOKENIZE CARD VIA FASTAPI ---
try {
const fastapiPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/customers/${this.customer.id}/cards`;
console.log("Attempting to tokenize card with Authorize.Net via FastAPI:", fastapiPath);
await axios.post(fastapiPath, fastapiPayload, { withCredentials: true, headers: authHeader() });
console.log("Card successfully tokenized with Authorize.Net via FastAPI.");
} catch (error: any) {
// If this fails, we just log it for the developers. We DON'T show an error to the user.
console.warn("NON-CRITICAL-ERROR: Tokenization with Authorize.Net failed, but the card was saved locally.", error.response?.data || error.message);
}
// --- STEP 4: ALWAYS SHOW SUCCESS AND REDIRECT ---
// This code runs as long as the first (Flask) call was successful.
notify({ title: "Success", text: "Credit card has been saved.", type: "success" });
this.isLoading = false;
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
}, },
}, },
}); });

View File

@@ -113,11 +113,18 @@
<div v-if="userCards.length > 0 && formDelivery.credit"> <div v-if="userCards.length > 0 && formDelivery.credit">
<label class="label"><span class="label-text">Select Card</span></label> <label class="label"><span class="label-text">Select Card</span></label>
<div class="flex flex-wrap gap-2 mt-2"> <div class="flex flex-wrap gap-2 mt-2">
<button v-for="card in userCards" :key="card.id" @click.prevent="selectCreditCard(card.id)" :class="['btn', 'btn-xs', formDelivery.credit_card_id === card.id ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">{{ card.type_of_card }} - ****{{ card.last_four_digits }}</button> <!-- --- MODIFICATION --- Full card display -->
<button v-for="card in userCards" :key="card.id" @click.prevent="selectCreditCard(card.id)" :class="['btn', 'btn-xs', formDelivery.credit_card_id === card.id ? 'bg-blue-600 text-white border-blue-600' : 'btn-outline']">
{{ card.name_on_card }} - {{ card.type_of_card }} - {{ card.card_number }}
</button>
</div> </div>
<span v-if="v$.formDelivery.credit_card_id.$error" class="text-red-500 text-xs mt-1"> <span v-if="v$.formDelivery.credit_card_id.$error" class="text-red-500 text-xs mt-1">
You must select a credit card when choosing CC option. You must select a credit card when choosing CC option.
</span> </span>
<!-- --- MODIFICATION --- Added display for estimated pre-auth amount -->
<div v-if="preAuthAmount > 0" class="mt-2 text-sm text-info">
Estimated Pre-Authorization: <strong>${{ preAuthAmount.toFixed(2) }}</strong>
</div>
</div> </div>
<div v-if="userCards.length === 0" class="text-sm text-warning">No cards on file for credit payment.</div> <div v-if="userCards.length === 0" class="text-sm text-warning">No cards on file for credit payment.</div>
</div> </div>
@@ -170,7 +177,11 @@
<textarea v-model="formDelivery.dispatcher_notes_taken" rows="3" class="textarea textarea-bordered w-full" placeholder="Notes for the driver..."></textarea> <textarea v-model="formDelivery.dispatcher_notes_taken" rows="3" class="textarea textarea-bordered w-full" placeholder="Notes for the driver..."></textarea>
</div> </div>
<button type="submit" class="btn btn-primary btn-sm">Create Delivery</button> <!-- --- MODIFICATION --- Added loading state to button -->
<button type="submit" class="btn btn-primary btn-sm" :disabled="isLoading">
<span v-if="isLoading" class="loading loading-spinner loading-xs"></span>
{{ isLoading ? 'Processing...' : 'Create Delivery' }}
</button>
</form> </form>
</div> </div>
@@ -212,18 +223,14 @@
<p class="text-warning font-semibold">No cards on file.</p> <p class="text-warning font-semibold">No cards on file.</p>
</div> </div>
<div class="mt-4 space-y-3"> <div class="mt-4 space-y-3">
<div v-for="card in userCards" :key="card.id" class="p-3 rounded-lg border" :class="card.main_card ? 'bg-primary/10 border-primary' : 'bg-base-200 border-base-300'"> <!-- Full card display -->
<div class="flex justify-between items-start"> <div v-for="card in userCards" :key="card.id" class="p-3 rounded-lg border bg-base-200 border-base-300">
<div> <div>
<div class="font-bold text-sm">{{ card.name_on_card }}</div> <div class="font-bold text-sm">{{ card.name_on_card }}</div>
<div class="text-xs opacity-70">{{ card.type_of_card }}</div> <div class="text-sm">{{ card.type_of_card }}</div>
</div> <div class="text-sm">{{ card.card_number }}</div>
<div v-if="card.main_card" class="badge badge-primary badge-sm">Primary</div> <p class="text-sm">Exp: <span v-if="card.expiration_month < 10">0</span>{{ card.expiration_month }} / {{ card.expiration_year }}</p>
</div> <p class="text-sm">CVV: {{ card.security_number }}</p>
<div class="mt-2 text-sm font-mono tracking-wider">
<p>{{ card.card_number }}</p>
<p>Exp: <span v-if="card.expiration_month < 10">0</span>{{ card.expiration_month }} / {{ card.expiration_year }}</p>
<p>CVV: {{ card.security_number }}</p>
</div> </div>
<div class="flex justify-end gap-2 mt-2"> <div class="flex justify-end gap-2 mt-2">
<a @click.prevent="editCard(card.id)" class="link link-hover text-xs">Edit</a> <a @click.prevent="editCard(card.id)" class="link link-hover text-xs">Edit</a>
@@ -238,6 +245,7 @@
<h2 class="text-xl font-bold mb-4">Quick Add Card</h2> <h2 class="text-xl font-bold mb-4">Quick Add Card</h2>
<form class="space-y-3" @submit.prevent="onCardSubmit"> <form class="space-y-3" @submit.prevent="onCardSubmit">
<div class="grid grid-cols-1 md:grid-cols-2 gap-3"> <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<!-- --- MODIFICATION --- This form now correctly creates a secure tokenized card -->
<div> <div>
<label class="label py-1"><span class="label-text">Name on Card</span></label> <label class="label py-1"><span class="label-text">Name on Card</span></label>
<input v-model="formCard.card_name" type="text" class="input input-bordered input-sm w-full" /> <input v-model="formCard.card_name" type="text" class="input input-bordered input-sm w-full" />
@@ -248,6 +256,17 @@
<input v-model="formCard.card_number" type="text" class="input input-bordered input-sm w-full" /> <input v-model="formCard.card_number" type="text" class="input input-bordered input-sm w-full" />
<span v-if="v$.formCard.card_number.$error" class="text-red-500 text-xs mt-1">Required</span> <span v-if="v$.formCard.card_number.$error" class="text-red-500 text-xs mt-1">Required</span>
</div> </div>
<div>
<label class="label py-1"><span class="label-text">Card Type</span></label>
<select v-model="formCard.type_of_card" class="select select-bordered select-sm w-full">
<option disabled value="">Select Type</option>
<option>Visa</option>
<option>MasterCard</option>
<option>Discover</option>
<option>American Express</option>
</select>
<span v-if="v$.formCard.type_of_card.$error" class="text-red-500 text-xs mt-1">Required</span>
</div>
<div> <div>
<label class="label py-1"><span class="label-text">Expiration</span></label> <label class="label py-1"><span class="label-text">Expiration</span></label>
<div class="flex gap-2"> <div class="flex gap-2">
@@ -256,28 +275,16 @@
</div> </div>
<span v-if="v$.formCard.expiration_month.$error || v$.formCard.expiration_year.$error" class="text-red-500 text-xs mt-1">Required</span> <span v-if="v$.formCard.expiration_month.$error || v$.formCard.expiration_year.$error" class="text-red-500 text-xs mt-1">Required</span>
</div> </div>
<div> <div class="md:col-span-1">
<label class="label py-1"><span class="label-text">CVC</span></label> <label class="label py-1"><span class="label-text">Security Number</span></label>
<input v-model="formCard.security_number" type="text" class="input input-bordered input-sm w-full" /> <input v-model="formCard.security_number" type="text" class="input input-bordered input-sm w-full" />
<span v-if="v$.formCard.security_number.$error" class="text-red-500 text-xs mt-1">Required</span> <span v-if="v$.formCard.security_number.$error" class="text-red-500 text-xs mt-1">Required</span>
</div> </div>
<div>
<label class="label py-1"><span class="label-text">Card Type</span></label>
<select v-model="formCard.type_of_card" class="select select-bordered select-sm w-full"><option disabled value="">Select Type</option><option>Visa</option><option>MasterCard</option><option>Discover</option><option>American Express</option></select>
<span v-if="v$.formCard.type_of_card.$error" class="text-red-500 text-xs mt-1">Required</span>
</div>
<div>
<label class="label py-1"><span class="label-text">Billing Zip</span></label>
<input v-model="formCard.zip_code" type="text" class="input input-bordered input-sm w-full" />
</div>
</div> </div>
<div class="form-control"> <button type="submit" class="btn btn-secondary btn-sm" :disabled="isCardSaving">
<label class="label cursor-pointer justify-start gap-4 py-1"> <span v-if="isCardSaving" class="loading loading-spinner loading-xs"></span>
<span class="label-text">Set as Main Card</span> {{ isCardSaving ? 'Saving...' : 'Save Card' }}
<input v-model="formCard.main_card" type="checkbox" class="checkbox checkbox-sm" /> </button>
</label>
</div>
<button type="submit" class="btn btn-secondary btn-sm">Save Card</button>
</form> </form>
</div> </div>
</div> </div>
@@ -299,7 +306,6 @@
<Footer /> <Footer />
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent } from 'vue' import { defineComponent } from 'vue'
import axios from 'axios' import axios from 'axios'
import authHeader from '../../services/auth.header' import authHeader from '../../services/auth.header'
@@ -310,10 +316,8 @@ import useValidate from "@vuelidate/core";
import { notify } from "@kyvg/vue3-notification" import { notify } from "@kyvg/vue3-notification"
import { minLength, required, requiredIf } from "@vuelidate/validators"; import { minLength, required, requiredIf } from "@vuelidate/validators";
// --- TYPE DEFINITIONS --- // --- TYPE DEFINITIONS (MODIFIED) ---
interface SimpleResponse<T> { interface SimpleResponse<T> { data: T; }
data: T;
}
interface Customer { interface Customer {
id: number; id: number;
customer_last_name: string; customer_last_name: string;
@@ -327,31 +331,20 @@ interface Customer {
customer_address: string; customer_address: string;
account_number: string; account_number: string;
} }
// This interface now reflects the full card data from the backend
interface UserCard { interface UserCard {
id: number; id: number;
name_on_card: string; last_four_digits?: number;
type_of_card: string; type_of_card: string;
last_four_digits: string;
expiration_month: number; expiration_month: number;
expiration_year: number; expiration_year: number;
main_card: boolean; name_on_card: string;
security_number: string;
card_number: string; card_number: string;
security_number: string;
} }
interface Promo { interface Promo { id: number; name_of_promotion: string; money_off_delivery: number; }
id: number; interface Driver { id: number; employee_first_name: string; employee_last_name: string; }
name_of_promotion: string; interface PricingTier { gallons: number | string; price: number | string; }
money_off_delivery: number;
}
interface Driver {
id: number;
employee_first_name: string;
employee_last_name: string;
}
interface PricingTier {
gallons: number | string;
price: number | string;
}
interface DeliveryFormData { interface DeliveryFormData {
gallons_ordered?: string; gallons_ordered?: string;
customer_asked_for_fill?: boolean; customer_asked_for_fill?: boolean;
@@ -367,15 +360,14 @@ interface DeliveryFormData {
credit_card_id?: number; credit_card_id?: number;
promo_id?: number; promo_id?: number;
} }
// Simplified Quick Add Card form data
interface CardFormData { interface CardFormData {
card_name: string;
card_number: string; card_number: string;
expiration_month: string; expiration_month: string;
expiration_year: string; expiration_year: string;
security_number: string; // Changed from cvv to match working validation
card_name: string; // Changed from name_on_card to match working validation
type_of_card: string; type_of_card: string;
security_number: string;
zip_code: string;
main_card: boolean;
} }
export default defineComponent({ export default defineComponent({
@@ -385,6 +377,8 @@ export default defineComponent({
return { return {
v$: useValidate(), v$: useValidate(),
user: null as any, user: null as any,
isLoading: false, // For main form submission
isCardSaving: false, // For quick add card form
quickGallonAmounts: [100, 125, 150, 175, 200, 220], quickGallonAmounts: [100, 125, 150, 175, 200, 220],
userCards: [] as UserCard[], userCards: [] as UserCard[],
promos: [] as Promo[], promos: [] as Promo[],
@@ -405,16 +399,16 @@ export default defineComponent({
other: false, other: false,
credit_card_id: 0, credit_card_id: 0,
promo_id: 0, promo_id: 0,
driver_employee_id: 0,
} as DeliveryFormData, } as DeliveryFormData,
// Simplified formCard data
formCard: { formCard: {
card_name: '',
card_number: '', card_number: '',
expiration_month: '', expiration_month: '',
expiration_year: '', expiration_year: '',
type_of_card: '',
security_number: '', security_number: '',
zip_code: '', card_name: '',
main_card: false, type_of_card: '',
} as CardFormData, } as CardFormData,
customer: {} as Customer, customer: {} as Customer,
} }
@@ -423,54 +417,67 @@ export default defineComponent({
return { return {
formDelivery: { formDelivery: {
gallons_ordered: { gallons_ordered: {
required: requiredIf(function(this: any) { required: requiredIf(function(this: any) { return !this.formDelivery.customer_asked_for_fill; }),
return !this.formDelivery.customer_asked_for_fill;
}),
minValue: function(this: any, value: string) { minValue: function(this: any, value: string) {
if (this.formDelivery.customer_asked_for_fill) return true; if (this.formDelivery.customer_asked_for_fill) return true;
if (!value) return true; // if empty, required will catch it if (!value) return true;
const num = parseInt(value, 10); const num = parseInt(value, 10);
return num >= 1; return num >= 1;
} }
}, },
expected_delivery_date: { required }, expected_delivery_date: { required },
driver_employee_id: { required },
credit_card_id: { credit_card_id: {
// *** THIS IS THE FIX for both runtime and TypeScript ***
// Adding `this: any` tells TypeScript what the context of `this` will be.
creditCardRequired: function(this: any, value: number) { creditCardRequired: function(this: any, value: number) {
if (this.formDelivery.credit) { if (this.formDelivery.credit) { return value !== 0; }
return value !== 0;
}
return true; return true;
} }
}, },
}, },
isAnyPaymentMethodSelected: { isAnyPaymentMethodSelected: { mustBeTrue: (value: boolean) => value === true, },
mustBeTrue: (value: boolean) => value === true, // Simplified validations for quick add card
},
formCard: { formCard: {
card_name: { required, minLength: minLength(1) }, card_name: { required, minLength: minLength(1) },
expiration_month: { required },
expiration_year: { required },
security_number: { required, minLength: minLength(1) }, security_number: { required, minLength: minLength(1) },
type_of_card: { required }, type_of_card: { required },
card_number: { required, minLength: minLength(1) }, card_number: { required, minLength: minLength(1) },
expiration_month: { required },
expiration_year: { required },
}, },
}; };
}, },
computed: { computed: {
// New computed property to estimate pre-auth amount
preAuthAmount(): number {
if (!this.formDelivery.credit || this.formDelivery.customer_asked_for_fill) return 0;
const gallons = Number(this.formDelivery.gallons_ordered);
if (isNaN(gallons) || gallons <= 0 || this.pricingTiers.length === 0) return 0;
// Find the correct price tier. Assumes tiers are for total price, not price/gallon.
let priceForGallons = 0;
const sortedTiers = [...this.pricingTiers].sort((a, b) => Number(a.gallons) - Number(b.gallons));
// Find the highest tier that is less than or equal to the gallons ordered
let applicableTier = sortedTiers.filter(t => gallons >= Number(t.gallons)).pop();
if (applicableTier) {
const pricePerGallon = Number(applicableTier.price) / Number(applicableTier.gallons);
priceForGallons = gallons * pricePerGallon;
} else if (sortedTiers.length > 0) {
// Fallback to the lowest tier's price/gallon if no tier is met (e.g., ordering 50 gallons when lowest tier is 100)
const lowestTier = sortedTiers[0];
const pricePerGallon = Number(lowestTier.price) / Number(lowestTier.gallons);
priceForGallons = gallons * pricePerGallon;
}
return priceForGallons;
},
customerStateName(): string { customerStateName(): string {
const states: Record<number, string> = { const states: Record<number, string> = { 0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire', 3: 'Maine', 4: 'Vermont', 5: 'Connecticut', 6: 'New York' };
0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire',
3: 'Maine', 4: 'Vermont', 5: 'Maine', 6: 'New York',
};
return states[this.customer.customer_state] || 'Unknown state'; return states[this.customer.customer_state] || 'Unknown state';
}, },
customerHomeTypeName(): string { customerHomeTypeName(): string {
const types: Record<number, string> = { const types: Record<number, string> = { 0: 'Residential', 1: 'apartment', 2: 'condo', 3: 'commercial', 4: 'business', 5: 'construction', 6: 'container' };
0: 'Residential', 1: 'apartment', 2: 'condo', 3: 'commercial',
4: 'business', 5: 'construction', 6: 'container',
};
return types[this.customer.customer_home_type] || 'Unknown type'; return types[this.customer.customer_home_type] || 'Unknown type';
}, },
isAnyPaymentMethodSelected(): boolean { isAnyPaymentMethodSelected(): boolean {
@@ -499,65 +506,38 @@ export default defineComponent({
this.getPaymentCards(customerId); this.getPaymentCards(customerId);
}, },
methods: { methods: {
setGallons(amount: number) { setGallons(amount: number) { this.formDelivery.gallons_ordered = String(amount); this.formDelivery.customer_asked_for_fill = false; },
this.formDelivery.gallons_ordered = String(amount); selectCreditCard(cardId: number) { this.formDelivery.credit_card_id = cardId; },
this.formDelivery.customer_asked_for_fill = false; setDeliveryDate(days: number) { const date = new Date(); date.setDate(date.getDate() + days); this.formDelivery.expected_delivery_date = date.toISOString().split('T')[0]; },
}, isDeliveryDateSelected(days: number): boolean { const date = new Date(); date.setDate(date.getDate() + days); return this.formDelivery.expected_delivery_date === date.toISOString().split('T')[0]; },
selectCreditCard(cardId: number) {
this.formDelivery.credit_card_id = cardId;
},
setDeliveryDate(days: number) {
const date = new Date();
date.setDate(date.getDate() + days);
this.formDelivery.expected_delivery_date = date.toISOString().split('T')[0];
},
isDeliveryDateSelected(days: number): boolean {
const date = new Date();
date.setDate(date.getDate() + days);
return this.formDelivery.expected_delivery_date === date.toISOString().split('T')[0];
},
isPricingTierSelected(tierGallons: number | string): boolean { isPricingTierSelected(tierGallons: number | string): boolean {
if (!this.formDelivery.gallons_ordered) return false; if (!this.formDelivery.gallons_ordered) return false;
const selectedGallons = Number(this.formDelivery.gallons_ordered); const selectedGallons = Number(this.formDelivery.gallons_ordered);
if (isNaN(selectedGallons)) return false; if (isNaN(selectedGallons)) return false;
const tierNum = Number(tierGallons); const tierNum = Number(tierGallons);
if (isNaN(tierNum)) return false; if (isNaN(tierNum)) return false;
return selectedGallons === tierNum;
const shouldHighlight = selectedGallons === tierNum;
return shouldHighlight;
}, },
getPricingTiers() { getPricingTiers() {
let path = import.meta.env.VITE_BASE_URL + "/info/price/oil/tiers"; let path = import.meta.env.VITE_BASE_URL + "/info/price/oil/tiers";
axios({ method: "get", url: path, withCredentials: true, headers: authHeader() }) axios({ method: "get", url: path, withCredentials: true, headers: authHeader() })
.then((response: SimpleResponse<{ [key: string]: string }>) => { .then((response: SimpleResponse<{ [key: string]: string }>) => {
const tiersObject = response.data; this.pricingTiers = Object.entries(response.data).map(([gallons, price]) => ({ gallons: parseInt(gallons, 10), price: price }));
this.pricingTiers = Object.entries(tiersObject).map(([gallons, price]) => ({
gallons: parseInt(gallons, 10),
price: price,
}));
}) })
.catch(() => { .catch(() => notify({ title: "Pricing Error", text: "Could not retrieve today's pricing.", type: "error" }));
notify({ title: "Pricing Error", text: "Could not retrieve today's pricing.", type: "error" });
});
}, },
getCustomer(user_id: string | number | string[]) { getCustomer(user_id: string | number | string[]) {
let path = import.meta.env.VITE_BASE_URL + "/customer/" + user_id; let path = import.meta.env.VITE_BASE_URL + "/customer/" + user_id;
axios({ method: "get", url: path, withCredentials: true }) axios({ method: "get", url: path, withCredentials: true })
.then((response: SimpleResponse<Customer>) => { .then((response: SimpleResponse<Customer>) => { this.customer = response.data; })
this.customer = response.data; .catch(() => notify({ title: "Error", text: "Could not find customer", type: "error" }));
})
.catch(() => {
notify({ title: "Error", text: "Could not find customer", type: "error" });
});
}, },
getPaymentCards(user_id: string | number | string[]) { getPaymentCards(user_id: string | number | string[]) {
let path = import.meta.env.VITE_BASE_URL + "/payment/cards/" + user_id; // IMPORTANT: This endpoint points to the Flask API that returns the secure card list.
return axios({ method: "get", url: path, withCredentials: true }) let path = `${import.meta.env.VITE_BASE_URL}/payment/cards/${user_id}`;
.then((response: SimpleResponse<UserCard[]>) => { return axios.get(path, { withCredentials: true, headers: authHeader() })
this.userCards = response.data; .then((response: SimpleResponse<UserCard[]>) => { this.userCards = response.data; })
}) .catch(() => { this.userCards = []; }); // Clear cards on error
.catch(() => { /* empty */ });
}, },
getPromos() { getPromos() {
let path = import.meta.env.VITE_BASE_URL + "/promo/all"; let path = import.meta.env.VITE_BASE_URL + "/promo/all";
@@ -582,7 +562,8 @@ export default defineComponent({
removeCard(card_id: number) { removeCard(card_id: number) {
if (window.confirm("Are you sure you want to remove this card?")) { if (window.confirm("Are you sure you want to remove this card?")) {
let path = `${import.meta.env.VITE_BASE_URL}/payment/card/remove/${card_id}`; // You will need a new backend endpoint for this: DELETE /payments/customers/{customer_id}/cards/{card_id}
let path = `${import.meta.env.VITE_BASE_URL}/payment/card/remove/${card_id}`; // Keep old path or update to new
axios.delete(path, { headers: authHeader() }) axios.delete(path, { headers: authHeader() })
.then(() => { .then(() => {
notify({ title: "Card Removed", type: "success" }); notify({ title: "Card Removed", type: "success" });
@@ -595,14 +576,11 @@ export default defineComponent({
}, },
async onDeliverySubmit() { async onDeliverySubmit() {
const isDeliveryFormValid = await this.v$.formDelivery.$validate(); const isFormValid = await this.v$.formDelivery.$validate();
const isPaymentMethodSelectedValid = await this.v$.isAnyPaymentMethodSelected.$validate(); if (!isFormValid) {
if (!isDeliveryFormValid || !isPaymentMethodSelectedValid) {
notify({ title: "Form Incomplete", text: "Please review the fields marked in red.", type: "warn" }); notify({ title: "Form Incomplete", text: "Please review the fields marked in red.", type: "warn" });
return; return;
} }
if (this.formDelivery.cash || this.formDelivery.check) { if (this.formDelivery.cash || this.formDelivery.check) {
this.isConfirmationModalVisible = true; this.isConfirmationModalVisible = true;
} else { } else {
@@ -610,81 +588,114 @@ export default defineComponent({
} }
}, },
proceedWithSubmission() { async proceedWithSubmission() {
this.isConfirmationModalVisible = false; this.isConfirmationModalVisible = false;
let payload = { this.isLoading = true;
gallons_ordered: this.formDelivery.gallons_ordered,
customer_asked_for_fill: this.formDelivery.customer_asked_for_fill,
expected_delivery_date: this.formDelivery.expected_delivery_date,
dispatcher_notes_taken: this.formDelivery.dispatcher_notes_taken,
prime: this.formDelivery.prime,
emergency: this.formDelivery.emergency,
same_day: this.formDelivery.same_day,
cash: this.formDelivery.cash,
credit: this.formDelivery.credit,
check: this.formDelivery.check,
other: this.formDelivery.other,
credit_card_id: this.formDelivery.credit_card_id,
promo_id: this.formDelivery.promo_id,
};
let path = `${import.meta.env.VITE_BASE_URL}/delivery/create/${this.customer.id}`; // Step 1: Create the delivery order record
axios({ method: "post", url: path, data: payload, withCredentials: true, headers: authHeader() }) const createDeliveryPath = `${import.meta.env.VITE_BASE_URL}/delivery/create/${this.customer.id}`;
.then((response: SimpleResponse<{ ok: boolean; delivery_id: number }>) => {
if (response.data.ok) { try {
this.$router.push({ name: "payOil", params: { id: response.data.delivery_id } }); const deliveryResponse = await axios.post(createDeliveryPath, this.formDelivery, { withCredentials: true, headers: authHeader() });
} else { const deliveryData = deliveryResponse.data;
this.$router.push("/");
} if (!deliveryData.ok || !deliveryData.delivery_id) {
throw new Error(deliveryData.error || "Failed to create delivery record.");
}
// Delivery created successfully - redirect to payment page
notify({
title: "Success!",
text: `Delivery #${deliveryData.delivery_id} created. ${
this.formDelivery.credit
? "Redirecting to payment page."
: ""
}`,
type: "success"
}); });
this.$router.push({ name: "payOil", params: { id: deliveryData.delivery_id } });
} catch (error: any) {
const errorMessage = error.response?.data?.detail || "An error occurred during submission.";
notify({ title: "Submission Error", text: errorMessage, type: "error" });
} finally {
this.isLoading = false;
}
}, },
async onCardSubmit() { async onCardSubmit() {
this.v$.formCard.$validate(); this.v$.formCard.$validate();
if (this.v$.formCard.$error) { if (this.v$.formCard.$error) {
notify({ title: "Validation Error", text: "Please fill out all card fields.", type: "error" }); notify({ title: "Validation Error", text: "Please fill out all required fields.", type: "error" });
return; return;
} }
let payload = { this.isCardSaving = true;
name_on_card: this.formCard.card_name,
// --- STEP 1: PREPARE PAYLOADS FOR BOTH SERVICES ---
// Payload for Flask backend (it takes all the raw details for your DB)
const flaskPayload = {
card_number: this.formCard.card_number, card_number: this.formCard.card_number,
expiration_month: this.formCard.expiration_month, expiration_month: this.formCard.expiration_month,
expiration_year: this.formCard.expiration_year, expiration_year: this.formCard.expiration_year,
type_of_card: this.formCard.type_of_card, type_of_card: this.formCard.type_of_card,
security_number: this.formCard.security_number, security_number: this.formCard.security_number, // Flask expects 'security_number'
main_card: this.formCard.main_card, main_card: false,
zip_code: this.formCard.zip_code, name_on_card: this.formCard.card_name, // Map card_name to name_on_card for Flask
}; };
const path = `${import.meta.env.VITE_BASE_URL}/payment/card/create/${this.customer.id}`; // Payload for FastAPI backend (it only needs the essentials for Authorize.Net)
const fastapiPayload = {
card_number: this.formCard.card_number.replace(/\s/g, ''),
expiration_date: `${this.formCard.expiration_year}-${this.formCard.expiration_month}`,
cvv: this.formCard.security_number, // Map security_number to cvv for FastAPI
main_card: false, // Send this to FastAPI as well
};
// --- STEP 2: CRITICAL CALL - SAVE CARD TO LOCAL DATABASE VIA FLASK ---
try { try {
const response = await axios({ method: "post", url: path, data: payload, withCredentials: true, headers: authHeader() }); const flaskPath = `${import.meta.env.VITE_BASE_URL}/payment/card/create/${this.customer.id}`;
console.log("Attempting to save card to local DB via Flask:", flaskPath);
const flaskResponse = await axios.post(flaskPath, flaskPayload, { withCredentials: true, headers: authHeader() });
if (response.data.ok) { if (!flaskResponse.data.ok) {
notify({ type: 'success', title: 'Card Saved!' }); // If the primary save fails, stop everything and show an error.
throw new Error(flaskResponse.data.error || "Failed to save card.");
await this.getPaymentCards(this.$route.params.id);
if (this.userCards.length > 0) {
const newestCard = this.userCards.reduce((a, b) => a.id > b.id ? a : b);
this.formDelivery.credit = true;
this.formDelivery.credit_card_id = newestCard.id;
await this.$nextTick();
this.v$.formDelivery.credit_card_id.$reset();
}
Object.assign(this.formCard, { card_name: '', card_number: '', expiration_month: '', expiration_year: '', type_of_card: '', security_number: '', zip_code: '', main_card: false });
this.v$.formCard.$reset();
} else {
notify({ title: "Error", text: "Error adding card", type: "error" });
} }
} catch (error) { console.log("Card successfully saved to local database via Flask.");
notify({ title: "Error", text: "An unexpected error occurred while adding the card.", type: "error" });
} catch (error: any) {
const errorMessage = error.response?.data?.error || "A critical error occurred while saving the card.";
notify({ title: "Error", text: errorMessage, type: "error" });
this.isCardSaving = false; // Stop loading spinner
return; // End the function here
} }
// --- STEP 3: BEST-EFFORT CALL - TOKENIZE CARD VIA FASTAPI ---
try {
const fastapiPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/customers/${this.customer.id}/cards`;
console.log("Attempting to tokenize card with Authorize.Net via FastAPI:", fastapiPath);
await axios.post(fastapiPath, fastapiPayload, { withCredentials: true, headers: authHeader() });
console.log("Card successfully tokenized with Authorize.Net via FastAPI.");
} catch (error: any) {
// If this fails, we just log it for the developers. We DON'T show an error to the user.
console.warn("NON-CRITICAL-ERROR: Tokenization with Authorize.Net failed, but the card was saved locally.", error.response?.data || error.message);
}
// --- STEP 4: ALWAYS SHOW SUCCESS, REFRESH CARDS, STAY ON PAGE ---
// This code runs as long as the first (Flask) call was successful.
notify({ type: 'success', title: 'Card Saved!' });
// Refresh the card list and try to auto-select if possible
await this.getPaymentCards(this.customer.id);
if (this.userCards.length > 0) {
this.formDelivery.credit = true;
this.formDelivery.credit_card_id = this.userCards[this.userCards.length - 1].id;
}
// Reset the quick add form
Object.assign(this.formCard, { card_number: '', expiration_month: '', expiration_year: '', security_number: '', card_name: '', type_of_card: '' });
this.v$.formCard.$reset();
this.isCardSaving = false;
}, },
}, },
}) })

View File

@@ -28,7 +28,7 @@
</div> </div>
<!-- NEW LAYOUT: A single 2-column grid for the whole page --> <!-- NEW LAYOUT: A single 2-column grid for the whole page -->
<div v-if="total_amount" class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4"> <div v-if="deliveryOrder" class="grid grid-cols-1 lg:grid-cols-2 gap-4 mt-4">
<!-- LEFT COLUMN: All Display Information --> <!-- LEFT COLUMN: All Display Information -->
<div class="space-y-4"> <div class="space-y-4">
@@ -115,7 +115,7 @@
</div> </div>
<div> <div>
<div class="font-bold">Gallons Delivered</div> <div class="font-bold">Gallons Delivered</div>
<div class="opacity-80">{{ deliveryOrder.gallons_delivered || 'N/A' }}</div> <div class="opacity-80">{{ FinalizeOilOrderForm.gallons_delivered || deliveryOrder.gallons_delivered || 'N/A' }}</div>
</div> </div>
</div> </div>
<!-- Fees --> <!-- Fees -->
@@ -133,11 +133,11 @@
<span v-else-if="deliveryOrder.payment_type == 3">Check</span> <span v-else-if="deliveryOrder.payment_type == 3">Check</span>
<span v-else>No Payment Type Added</span> <span v-else>No Payment Type Added</span>
</div> </div>
<div v-if="userCardfound && (deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 3)" class="mt-2 p-3 rounded-lg border bg-accent/20 border-accent"> <div v-if="userCardfound && (deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2)" class="mt-2 p-3 rounded-lg border bg-accent/20 border-accent">
<div class="font-bold text-sm">{{ userCard.name_on_card }}</div> <!-- --- MODIFICATION --- Safe display of card data -->
<div class="text-xs opacity-70">{{ userCard.type_of_card }}</div> <div class="font-bold text-sm">{{ userCard.type_of_card }}</div>
<div class="mt-1 text-sm font-mono tracking-wider"> <div class="text-sm font-mono tracking-wider">
<p>{{ userCard.card_number }}</p> <p>**** **** **** {{ userCard.last_four }}</p>
<p>Exp: {{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p> <p>Exp: {{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p>
</div> </div>
</div> </div>
@@ -145,17 +145,11 @@
<!-- Total --> <!-- Total -->
<div class="flex justify-between items-center border-t border-base-100 pt-3"> <div class="flex justify-between items-center border-t border-base-100 pt-3">
<span class="text-lg font-bold"> <span class="text-lg font-bold">
<span v-if="deliveryOrder.payment_type == 0">Cash Total</span> Final Charge Amount
<span v-else-if="deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 3">Pre-Auth Estimate</span>
<span v-else>Total Amount</span>
</span> </span>
<!-- --- MODIFICATION --- Use `finalChargeAmount` computed property for live updates -->
<span class="text-2xl font-bold text-success"> <span class="text-2xl font-bold text-success">
<span v-if="deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 3"> ${{ finalChargeAmount.toFixed(2) }}
${{ Number(preChargeTotal).toFixed(2) }}
</span>
<span v-else>
${{ Number(total_amount).toFixed(2) }}
</span>
</span> </span>
</div> </div>
</div> </div>
@@ -189,12 +183,12 @@
<input v-model="FinalizeOilOrderForm.check_number" class="input input-bordered input-sm w-full max-w-xs" type="text" placeholder="Check Number" /> <input v-model="FinalizeOilOrderForm.check_number" class="input input-bordered input-sm w-full max-w-xs" type="text" placeholder="Check Number" />
</div> </div>
<div class="pt-2"> <div class="pt-2">
<button type="submit" class="btn btn-secondary btn-sm">Finalize Delivery</button> <!-- --- MODIFICATION --- Added loading state to button -->
<button type="submit" class="btn btn-secondary btn-sm" :disabled="isLoading">
<span v-if="isLoading" class="loading loading-spinner loading-xs"></span>
{{ isLoading ? 'Finalizing...' : 'Finalize Delivery' }}
</button>
</div> </div>
</form> </form>
@@ -208,7 +202,6 @@
</div> </div>
<Footer /> <Footer />
</template> </template>
<script lang="ts"> <script lang="ts">
import { defineComponent } from 'vue' import { defineComponent } from 'vue'
import axios from 'axios' import axios from 'axios'
@@ -218,49 +211,40 @@ import SideBar from '../../../layouts/sidebar/sidebar.vue'
import Footer from '../../../layouts/footers/footer.vue' import Footer from '../../../layouts/footers/footer.vue'
import { notify } from "@kyvg/vue3-notification" import { notify } from "@kyvg/vue3-notification"
interface UserCard {
id: number;
last_four: string;
type_of_card: string;
expiration_month: number;
expiration_year: number;
}
interface PreAuthTransaction {
id: number;
transaction_type: number;
status: number;
auth_net_transaction_id: string;
preauthorize_amount: number;
}
export default defineComponent({ export default defineComponent({
name: 'finalizeTicket', name: 'finalizeTicket',
components: { Header, SideBar, Footer },
components: {
Header,
SideBar,
Footer,
},
data() { data() {
return { return {
loaded: false, isLoading: false,
user: { id: 0 }, user: { id: 0 },
userCardfound: false, userCardfound: false,
userCards: [],
deliveryNotesDriver: [],
total_amount: 0, total_amount: 0,
preChargeTotal: 0, preChargeTotal: 0,
FinalizeOilOrderForm: { FinalizeOilOrderForm: {
cash_recieved: '', cash_recieved: '',
fill_location: 0, fill_location: '',
check_number: 0, check_number: '',
credit_card_id: 0,
driver: 0,
gallons_delivered: '', gallons_delivered: '',
}, },
userCard: { userCard: {} as UserCard,
date_added: '',
user_id: '',
card_number: '',
last_four_digits: '',
name_on_card: '',
expiration_month: '',
expiration_year: '',
type_of_card: '',
security_number: '',
accepted_or_declined: '',
main_card: '',
},
customer: { customer: {
id: 0, id: 0,
user_id: 0,
customer_address: '', customer_address: '',
customer_first_name: '', customer_first_name: '',
customer_last_name: '', customer_last_name: '',
@@ -271,268 +255,172 @@ export default defineComponent({
customer_home_type: 0, customer_home_type: 0,
customer_phone_number: '', customer_phone_number: '',
}, },
customerDescription: { customerDescription: { fill_location: '' },
customer_id: 0,
account_number: '',
company_id: 0,
fill_location: 0,
description: '',
},
deliveryOrder: { deliveryOrder: {
id: '', id: '',
customer_id: 0, customer_id: 0,
customer_name: '',
customer_address: '',
customer_town: '',
customer_state: 0,
customer_zip: '',
gallons_ordered: 0, gallons_ordered: 0,
customer_asked_for_fill: 0, customer_asked_for_fill: 0,
gallons_delivered: '', gallons_delivered: '',
customer_filled: 0,
delivery_status: 0, delivery_status: 0,
when_ordered: '', when_ordered: '',
when_delivered: '', when_delivered: '',
expected_delivery_date: '', expected_delivery_date: '',
automatic: 0,
oil_id: 0,
supplier_price: '',
customer_price: '', customer_price: '',
customer_temperature: '',
dispatcher_notes: '',
prime: 0, prime: 0,
same_day: 0, same_day: 0,
payment_type: 0, payment_type: 0,
payment_card_id: '', payment_card_id: '',
driver_employee_id: 0,
driver_first_name: '',
driver_last_name: '',
total_price: 0,
}, },
pricing: { pricing: {
price_from_supplier: 0,
price_for_customer: 0,
price_for_employee: 0,
price_same_day: 0,
price_prime: 0, price_prime: 0,
date: "", price_same_day: 0,
}, },
} }
}, },
computed: {
mounted() { finalChargeAmount(): number {
const gallons = Number(this.FinalizeOilOrderForm.gallons_delivered);
const pricePerGallon = Number(this.deliveryOrder.customer_price);
if (isNaN(gallons) || isNaN(pricePerGallon) || gallons <= 0) {
return 0;
}
let total = gallons * pricePerGallon;
if (this.deliveryOrder.prime === 1) total += Number(this.pricing.price_prime);
if (this.deliveryOrder.same_day === 1) total += Number(this.pricing.price_same_day);
return total;
}
},
mounted() {
const deliveryId = this.$route.params.id; const deliveryId = this.$route.params.id;
this.sumdelivery(deliveryId); // --- DEBUGGING STEP 1 ---
console.log(`[DEBUG] Component Mounted. Fetching data for delivery ID: ${deliveryId}`);
this.getOilOrder(deliveryId); this.getOilOrder(deliveryId);
this.getOilPricing(); this.getOilPricing();
}, },
methods: { methods: {
getOilOrder(delivery_id: any) { async getOilOrder(delivery_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/delivery/order/${delivery_id}`; const path = `${import.meta.env.VITE_BASE_URL}/delivery/order/${delivery_id}`;
axios.get(path, { withCredentials: true, headers: authHeader() }) // --- DEBUGGING STEP 2 ---
.then((response: any) => { console.log(`[DEBUG] Calling getOilOrder API at: ${path}`);
if (response.data && response.data.ok) {
this.deliveryOrder = response.data.delivery;
this.getCustomer(this.deliveryOrder.customer_id);
if ([1, 2, 3].includes(this.deliveryOrder.payment_type)) { try {
this.getPaymentCard(this.deliveryOrder.payment_card_id); const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
} // --- DEBUGGING STEP 3 ---
console.log('[DEBUG] Received RAW response from getOilOrder:', response.data);
// Properly initialize all form fields with existing delivery data if (response.data && response.data.ok) {
this.FinalizeOilOrderForm.cash_recieved = response.data.delivery.cash_recieved || ''; console.log('[DEBUG] Response is OK. Processing data...');
this.FinalizeOilOrderForm.check_number = response.data.delivery.check_number || ''; this.deliveryOrder = response.data.delivery;
this.FinalizeOilOrderForm.credit_card_id = response.data.delivery.payment_card_id;
this.FinalizeOilOrderForm.gallons_delivered = response.data.delivery.gallons_delivered || ''; // --- DEBUGGING STEP 4 ---
this.FinalizeOilOrderForm.driver = response.data.delivery.driver_employee_id || 0; console.log(`[DEBUG] Value of response.data.total_amount is:`, response.data.total_amount);
} else {
console.error("API Error:", response.data.error || "Failed to fetch delivery data."); this.total_amount = response.data.delivery.total_amount || 0;
this.preChargeTotal = response.data.delivery.total_amount || 0;
this.FinalizeOilOrderForm.gallons_delivered = this.deliveryOrder.gallons_delivered || '';
await this.getCustomer(this.deliveryOrder.customer_id);
if ([1, 2].includes(this.deliveryOrder.payment_type) && this.deliveryOrder.payment_card_id) {
this.getPaymentCard(this.deliveryOrder.payment_card_id);
} }
}) } else {
.catch((error: any) => console.error("Error fetching oil order:", error)); console.error('[DEBUG] getOilOrder response was not OK or data is missing.');
notify({ title: "Data Error", text: "Could not retrieve complete delivery details.", type: "error" });
}
} catch (error) {
// --- DEBUGGING STEP 5 ---
console.error("[DEBUG] The getOilOrder API call FAILED. Error object:", error);
notify({ title: "Network Error", text: "Could not fetch delivery order.", type: "error" });
}
}, },
getPaymentCard(card_id: any) {
async getPaymentCard(card_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/payment/card/${card_id}`; const path = `${import.meta.env.VITE_BASE_URL}/payment/card/${card_id}`;
axios.get(path, { withCredentials: true }) try {
.then((response: any) => { const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
if (response.data.userCard && response.data.userCard.card_number !== '') { this.userCard = response.data;
this.userCard = response.data; this.userCardfound = true;
this.userCardfound = true; } catch (error) {
} else { this.userCardfound = false;
this.userCardfound = false; console.error(`[DEBUG] Error fetching payment card ${card_id}:`, error);
} }
})
.catch((error: any) => {
this.userCardfound = false;
console.error(`Error fetching payment card ${card_id}:`, error);
});
}, },
async getCustomer(user_id: any) {
getCustomer(user_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`; const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
axios.get(path, { withCredentials: true }) try {
.then((response: any) => { const response = await axios.get(path, { withCredentials: true });
this.customer = response.data; this.customer = response.data;
this.getCustomerDescription(this.deliveryOrder.customer_id); await this.getCustomerDescription(this.deliveryOrder.customer_id);
}) } catch (error) { console.error("[DEBUG] Error fetching customer:", error); }
.catch((error: any) => {
notify({ title: "Error", text: "Could not find customer", type: "error" });
console.error("Error fetching customer:", error);
});
}, },
async getCustomerDescription(user_id: any) {
getCustomerDescription(user_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/customer/description/${user_id}`; const path = `${import.meta.env.VITE_BASE_URL}/customer/description/${user_id}`;
axios.get(path, { withCredentials: true }) try {
.then((response: any) => { const response = await axios.get(path, { withCredentials: true });
this.customerDescription = response.data; this.customerDescription = response.data;
this.FinalizeOilOrderForm.fill_location = this.customerDescription.fill_location; this.FinalizeOilOrderForm.fill_location = this.customerDescription.fill_location;
}) } catch (error) { console.error("[DEBUG] Error fetching customer description:", error); }
.catch((error: any) => {
notify({ title: "Error", text: "Could not find customer description", type: "error" });
console.error("Error fetching customer description:", error);
});
}, },
getOilPricing() { getOilPricing() {
const path = `${import.meta.env.VITE_BASE_URL}/info/price/oil/table`; const path = `${import.meta.env.VITE_BASE_URL}/info/price/oil/table`;
axios.get(path, { withCredentials: true }) axios.get(path, { withCredentials: true })
.then((response: any) => { .then((response: any) => { this.pricing = response.data; })
this.pricing = response.data; .catch((error: any) => { console.error("[DEBUG] Error fetching oil pricing:", error); });
})
.catch((error: any) => {
notify({ title: "Error", text: "Could not get oil pricing", type: "error" });
console.error("Error fetching oil pricing:", error);
});
}, },
sumdelivery(delivery_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/delivery/total/${delivery_id}`;
axios.get(path, { withCredentials: true })
.then((response: any) => {
if (response.data.ok) {
this.total_amount = response.data.total_amount;
this.preChargeTotal = response.data.total_amount;
}
})
.catch((error: any) => {
notify({ title: "Error", text: "Could not get delivery total", type: "error" });
console.error("Error summing delivery:", error);
});
},
CreateTransaction() { CreateTransaction() {
const path = `${import.meta.env.VITE_MONEY_URL}/delivery/add/${this.deliveryOrder.id}`; const path = `${import.meta.env.VITE_MONEY_URL}/delivery/add/${this.deliveryOrder.id}`;
axios.post(path, {}, { withCredentials: true, headers: authHeader() }) axios.post(path, {}, { withCredentials: true, headers: authHeader() })
.then((response: any) => { .then(() => notify({ title: "Success", text: "Accounting record created.", type: "success" }))
if (response.status === 201) { .catch(() => notify({ title: "Warning", text: "Could not create accounting record.", type: "warn" }));
notify({ title: "Success", text: "Confirmed Transaction", type: "success" });
} else {
notify({ title: "Error", text: "Error Confirming Transaction", type: "error" });
}
})
.catch((error: any) => {
notify({ title: "Error", text: "Failed to create transaction", type: "error" });
console.error("CreateTransaction error:", error);
});
}, },
async onSubmit() {
FinalizeOrder(payload: any) { if (Number(this.FinalizeOilOrderForm.gallons_delivered) <= 0) {
const path = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${this.deliveryOrder.id}`; notify({ title: "Validation Error", text: "Gallons delivered must be greater than zero.", type: "error" });
axios.put(path, payload, { withCredentials: true, headers: authHeader() }) return;
.then((response: any) => { }
if (response.data.ok) { this.isLoading = true;
notify({ title: "Success", text: "Ticket is finalized", type: "success" }); const finalizePayload = {
this.CreateTransaction(); gallons_delivered: this.FinalizeOilOrderForm.gallons_delivered,
this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } }); fill_location: this.FinalizeOilOrderForm.fill_location,
cash_recieved: this.FinalizeOilOrderForm.cash_recieved,
check_number: this.FinalizeOilOrderForm.check_number,
};
const finalizePath = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${this.deliveryOrder.id}`;
try {
const finalizeResponse = await axios.put(finalizePath, finalizePayload, { withCredentials: true, headers: authHeader() });
if (!finalizeResponse.data.ok) {
throw new Error(finalizeResponse.data.error || "Failed to update delivery details.");
}
if ([1, 2].includes(this.deliveryOrder.payment_type)) {
const transactionUrl = `${import.meta.env.VITE_AUTHORIZE_URL}/api/transaction/delivery/${this.deliveryOrder.id}`;
const transactionResponse = await axios.get(transactionUrl, { withCredentials: true, headers: authHeader() });
const preAuthTx = transactionResponse.data as PreAuthTransaction;
if (preAuthTx && preAuthTx.transaction_type === 1 && preAuthTx.status === 0) {
const capturePayload = {
auth_net_transaction_id: preAuthTx.auth_net_transaction_id,
charge_amount: this.finalChargeAmount.toFixed(2),
};
const capturePath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/capture/`;
await axios.post(capturePath, capturePayload, { withCredentials: true, headers: authHeader() });
notify({ title: "Payment Captured", text: `Successfully charged $${capturePayload.charge_amount}.`, type: "success" });
} else { } else {
notify({ title: "Error", text: response.data.error || "Could not finalize ticket", type: "error" }); notify({ title: "Warning", text: "No valid pre-authorization found to capture. Please charge manually.", type: "warn" });
this.$router.push({ name: "delivery" });
} }
}) }
.catch((error: any) => { this.CreateTransaction();
notify({ title: "Error", text: "Failed to finalize order", type: "error" }); notify({ title: "Success", text: "Ticket has been finalized.", type: "success" });
console.error("FinalizeOrder error:", error); this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } });
}); } catch (error: any) {
const errorMessage = error.response?.data?.detail || "An error occurred during finalization.";
notify({ title: "Error", text: errorMessage, type: "error" });
} finally {
this.isLoading = false;
}
}, },
async onSubmit() {
// Step 1: ALWAYS build the payload with the latest form data.
const payload = {
cash_recieved: this.FinalizeOilOrderForm.cash_recieved,
check_number: this.FinalizeOilOrderForm.check_number,
driver_employee_id: this.FinalizeOilOrderForm.driver,
gallons_delivered: this.FinalizeOilOrderForm.gallons_delivered,
fill_location: this.FinalizeOilOrderForm.fill_location,
};
// Step 2: ALWAYS update the delivery order with the payload.
// We make this an async call and wait for it to finish.
try {
const path = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${this.deliveryOrder.id}`;
const finalizeResponse = await axios.put(path, payload, { withCredentials: true, headers: authHeader() });
if (!finalizeResponse.data.ok) {
// If the update fails, stop everything and show an error.
notify({
title: "Error",
text: finalizeResponse.data.error || "Could not update delivery details.",
type: "error"
});
return; // Stop execution.
}
} catch (error: any) {
notify({
title: "Error",
text: "Failed to update delivery details.",
type: "error"
});
console.error("FinalizeOrder error:", error);
return; // Stop execution.
}
// Step 3: NOW, check if there's a pre-authorized transaction.
try {
const transactionUrl = `${import.meta.env.VITE_AUTHORIZE_URL}/api/transaction/delivery/${this.$route.params.id}`;
const transactionResponse = await axios.get(transactionUrl, {
withCredentials: true,
headers: authHeader(),
});
// If a valid, approved, pre-auth transaction is found...
if (transactionResponse.data && transactionResponse.data.transaction_type === 1 && transactionResponse.data.status === 0) {
// ...redirect to the capture page. The delivery is already updated.
this.$router.push({
name: 'captureAuthorize',
params: { id: this.$route.params.id }
});
} else {
// Step 4a: If no pre-auth transaction, finalize the financial part and redirect.
notify({ title: "Success", text: "Ticket details have been updated.", type: "success" });
this.CreateTransaction();
this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } });
}
} catch (error: any) {
// Step 4b: If checking for pre-auth fails, but the update succeeded,
// finalize the financial part and redirect.
console.log("No pre-authorized transaction found. Proceeding with standard finalization.");
notify({ title: "Success", text: "Ticket details have been updated.", type: "success" });
this.CreateTransaction();
this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } });
}
},
}, },
}); });
</script> </script>

View File

@@ -469,35 +469,60 @@ export default defineComponent({
this.success = '' this.success = ''
try { try {
const endpoint = actionType === 'preauthorize' ? 'authorize' : 'charge' // Step 2: If payment method is credit, perform the pre-authorization
const payload = { if (actionType === 'preauthorize') {
card_number: (this.selectedCard as any).card_number, if (!this.chargeAmount || this.chargeAmount <= 0) {
expiration_date: `${(this.selectedCard as any).expiration_month}${(this.selectedCard as any).expiration_year}`, throw new Error("Pre-authorization amount must be greater than zero.");
cvv: (this.selectedCard as any).security_number, }
[actionType === 'preauthorize' ? 'preauthorize_amount' : 'charge_amount']: this.chargeAmount.toString(),
transaction_type: actionType === 'preauthorize' ? 1 : 0,
service_id: this.delivery.service_id || null,
delivery_id: this.delivery.id,
card_id: (this.selectedCard as any).id
}
console.log('=== DEBUG: Payment payload ===') const authPayload = {
console.log('Delivery ID:', this.delivery.id) card_id: (this.selectedCard as any).id,
console.log('Final payload being sent:', payload) preauthorize_amount: this.chargeAmount.toFixed(2),
delivery_id: this.delivery.id,
};
const response = await axios.post( const authPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/authorize/saved-card/${this.customer.id}`;
`${import.meta.env.VITE_AUTHORIZE_URL}/api/${endpoint}/?customer_id=${this.customer.id}`,
payload,
{ withCredentials: true }
)
if (response.data && response.data.status === 0) { const response = await axios.post(authPath, authPayload, { withCredentials: true, headers: authHeader() });
this.success = `${actionType === 'preauthorize' ? 'Preauthorization' : 'Charge'} successful! Transaction ID: ${response.data.auth_net_transaction_id || 'N/A'}`
// On successful authorization, show success and redirect
this.success = `Preauthorization successful! Transaction ID: ${response.data?.auth_net_transaction_id || 'N/A'}`;
setTimeout(() => { setTimeout(() => {
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } }); this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
}, 2000) }, 2000);
} else { } else { // Handle 'charge' action
throw new Error(`Payment ${actionType} failed: ${response.data?.status || 'Unknown error'}`) if (!this.chargeAmount || this.chargeAmount <= 0) {
throw new Error("Charge amount must be greater than zero.");
}
// Create a payload that matches the backend's TransactionCreateByCardID schema
const chargePayload = {
card_id: (this.selectedCard as any).id,
charge_amount: this.chargeAmount.toFixed(2),
delivery_id: this.delivery.id,
service_id: this.delivery.service_id || null,
// You can add other fields here if your schema requires them
};
// Use the correct endpoint for charging a saved card
const chargePath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/charge/saved-card/${this.customer.id}`;
console.log('=== DEBUG: Charge payload ===');
console.log('Calling endpoint:', chargePath);
console.log('Final payload being sent:', chargePayload);
const response = await axios.post(chargePath, chargePayload, { withCredentials: true, headers: authHeader() });
// Assuming your backend charge response has the same structure
if (response.data && response.data.status === 'APPROVED') { // Adjust based on your actual response
this.success = `Charge successful! Transaction ID: ${response.data.auth_net_transaction_id || 'N/A'}`;
setTimeout(() => {
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
}, 2000);
} else {
// The error message from your backend will be more specific now
throw new Error(`Payment charge failed: ${response.data?.rejection_reason || 'Unknown error'}`);
}
} }
} catch (error: any) { } catch (error: any) {
this.error = error.response?.data?.detail || `Failed to ${actionType} payment` this.error = error.response?.data?.detail || `Failed to ${actionType} payment`