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>
<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 -->
<div class="text-sm breadcrumbs">
<ul>
@@ -15,27 +14,7 @@
<!-- TOP SECTION: Customer Info -->
<div class="my-6">
<div class="bg-neutral rounded-lg p-5">
<div class="flex flex-col sm:flex-row sm:justify-between sm:items-center mb-4">
<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>
<!-- ... (this section is fine, no changes needed) ... -->
</div>
</div>
@@ -44,45 +23,44 @@
<h2 class="text-2xl font-bold mb-4">Add a New Credit Card</h2>
<form @submit.prevent="onSubmit" class="space-y-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<!-- Name on Card -->
<!-- Name -->
<div class="form-control">
<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" />
<span v-if="v$.CardForm.name_on_card.$error" class="text-red-500 text-xs mt-1">Required.</span>
<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">A valid name_on_card is required.</span>
</div>
<!-- Card Number -->
<div class="form-control">
<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" />
<span v-if="v$.CardForm.card_number.$error" class="text-red-500 text-xs mt-1">Required.</span>
<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">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>
<!-- Expiration -->
<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">
<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>
</select>
<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>
</select>
</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>
<!-- Security Number (CVV) -->
<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 -->
<!-- Card Type dropdown -->
<div class="form-control">
<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">
@@ -95,24 +73,30 @@
<span v-if="v$.CardForm.type_of_card.$error" class="text-red-500 text-xs mt-1">Required.</span>
</div>
<!-- Billing Zip Code -->
<!-- Billing Zip Code input -->
<div class="form-control">
<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>
<!-- Main Card Checkbox -->
<!-- --- FIX: Main Card Checkbox --- -->
<div class="form-control md:col-span-2">
<label class="label cursor-pointer justify-start gap-4">
<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" />
</label>
</div>
</div>
<!-- SUBMIT BUTTON -->
<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>
</form>
</div>
@@ -120,7 +104,6 @@
</div>
<Footer />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
@@ -140,29 +123,29 @@ export default defineComponent({
v$: useValidate(),
user: null,
customer: {} as any,
// --- REFACTORED: Simplified, flat form object ---
isLoading: false,
CardForm: {
name_on_card: '',
main_card: false,
card_number: '',
expiration_month: '',
expiration_year: '',
cvv: '',
type_of_card: '',
security_number: '',
card_number: '',
zip_code: '',
main_card: false,
name_on_card: '',
},
}
},
validations() {
return {
// --- REFACTORED: Validation points to the flat form object ---
CardForm: {
name_on_card: { required, minLength: minLength(1) },
card_number: { required, minLength: minLength(13) },
expiration_month: { required },
expiration_year: { required },
security_number: { required, minLength: minLength(1) },
cvv: { required, minLength: minLength(3) },
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" });
});
},
CreateCard(payload: any) {
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() {
async onSubmit() {
this.v$.$validate();
if (!this.v$.$error) {
this.CreateCard(this.CardForm);
} else {
if (this.v$.$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">
<label class="label"><span class="label-text">Select Card</span></label>
<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>
<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.
</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 v-if="userCards.length === 0" class="text-sm text-warning">No cards on file for credit payment.</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>
</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>
</div>
@@ -212,18 +223,14 @@
<p class="text-warning font-semibold">No cards on file.</p>
</div>
<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'">
<div class="flex justify-between items-start">
<div>
<div class="font-bold text-sm">{{ card.name_on_card }}</div>
<div class="text-xs opacity-70">{{ card.type_of_card }}</div>
</div>
<div v-if="card.main_card" class="badge badge-primary badge-sm">Primary</div>
</div>
<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>
<!-- Full card display -->
<div v-for="card in userCards" :key="card.id" class="p-3 rounded-lg border bg-base-200 border-base-300">
<div>
<div class="font-bold text-sm">{{ card.name_on_card }}</div>
<div class="text-sm">{{ card.type_of_card }}</div>
<div class="text-sm">{{ card.card_number }}</div>
<p class="text-sm">Exp: <span v-if="card.expiration_month < 10">0</span>{{ card.expiration_month }} / {{ card.expiration_year }}</p>
<p class="text-sm">CVV: {{ card.security_number }}</p>
</div>
<div class="flex justify-end gap-2 mt-2">
<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>
<form class="space-y-3" @submit.prevent="onCardSubmit">
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<!-- --- MODIFICATION --- This form now correctly creates a secure tokenized card -->
<div>
<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" />
@@ -248,6 +256,17 @@
<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>
</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">Expiration</span></label>
<div class="flex gap-2">
@@ -256,28 +275,16 @@
</div>
<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>
<label class="label py-1"><span class="label-text">CVC</span></label>
<div class="md:col-span-1">
<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" />
<span v-if="v$.formCard.security_number.$error" class="text-red-500 text-xs mt-1">Required</span>
</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 class="form-control">
<label class="label cursor-pointer justify-start gap-4 py-1">
<span class="label-text">Set as Main Card</span>
<input v-model="formCard.main_card" type="checkbox" class="checkbox checkbox-sm" />
</label>
</div>
<button type="submit" class="btn btn-secondary btn-sm">Save Card</button>
<button type="submit" class="btn btn-secondary btn-sm" :disabled="isCardSaving">
<span v-if="isCardSaving" class="loading loading-spinner loading-xs"></span>
{{ isCardSaving ? 'Saving...' : 'Save Card' }}
</button>
</form>
</div>
</div>
@@ -299,7 +306,6 @@
<Footer />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
@@ -310,10 +316,8 @@ import useValidate from "@vuelidate/core";
import { notify } from "@kyvg/vue3-notification"
import { minLength, required, requiredIf } from "@vuelidate/validators";
// --- TYPE DEFINITIONS ---
interface SimpleResponse<T> {
data: T;
}
// --- TYPE DEFINITIONS (MODIFIED) ---
interface SimpleResponse<T> { data: T; }
interface Customer {
id: number;
customer_last_name: string;
@@ -327,31 +331,20 @@ interface Customer {
customer_address: string;
account_number: string;
}
// This interface now reflects the full card data from the backend
interface UserCard {
id: number;
name_on_card: string;
last_four_digits?: number;
type_of_card: string;
last_four_digits: string;
expiration_month: number;
expiration_year: number;
main_card: boolean;
security_number: string;
name_on_card: string;
card_number: string;
security_number: string;
}
interface Promo {
id: number;
name_of_promotion: 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 Promo { id: number; name_of_promotion: 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 {
gallons_ordered?: string;
customer_asked_for_fill?: boolean;
@@ -367,15 +360,14 @@ interface DeliveryFormData {
credit_card_id?: number;
promo_id?: number;
}
// Simplified Quick Add Card form data
interface CardFormData {
card_name: string;
card_number: string;
expiration_month: 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;
security_number: string;
zip_code: string;
main_card: boolean;
}
export default defineComponent({
@@ -385,6 +377,8 @@ export default defineComponent({
return {
v$: useValidate(),
user: null as any,
isLoading: false, // For main form submission
isCardSaving: false, // For quick add card form
quickGallonAmounts: [100, 125, 150, 175, 200, 220],
userCards: [] as UserCard[],
promos: [] as Promo[],
@@ -405,16 +399,16 @@ export default defineComponent({
other: false,
credit_card_id: 0,
promo_id: 0,
driver_employee_id: 0,
} as DeliveryFormData,
// Simplified formCard data
formCard: {
card_name: '',
card_number: '',
expiration_month: '',
expiration_year: '',
type_of_card: '',
security_number: '',
zip_code: '',
main_card: false,
card_name: '',
type_of_card: '',
} as CardFormData,
customer: {} as Customer,
}
@@ -423,54 +417,67 @@ export default defineComponent({
return {
formDelivery: {
gallons_ordered: {
required: requiredIf(function(this: any) {
return !this.formDelivery.customer_asked_for_fill;
}),
required: requiredIf(function(this: any) { return !this.formDelivery.customer_asked_for_fill; }),
minValue: function(this: any, value: string) {
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);
return num >= 1;
}
},
expected_delivery_date: { required },
driver_employee_id: { required },
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) {
if (this.formDelivery.credit) {
return value !== 0;
}
if (this.formDelivery.credit) { return value !== 0; }
return true;
}
},
},
isAnyPaymentMethodSelected: {
mustBeTrue: (value: boolean) => value === true,
},
isAnyPaymentMethodSelected: { mustBeTrue: (value: boolean) => value === true, },
// Simplified validations for quick add card
formCard: {
card_name: { required, minLength: minLength(1) },
expiration_month: { required },
expiration_year: { required },
security_number: { required, minLength: minLength(1) },
type_of_card: { required },
card_number: { required, minLength: minLength(1) },
expiration_month: { required },
expiration_year: { required },
},
};
},
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 {
const states: Record<number, string> = {
0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire',
3: 'Maine', 4: 'Vermont', 5: 'Maine', 6: 'New York',
};
const states: Record<number, string> = { 0: 'Massachusetts', 1: 'Rhode Island', 2: 'New Hampshire', 3: 'Maine', 4: 'Vermont', 5: 'Connecticut', 6: 'New York' };
return states[this.customer.customer_state] || 'Unknown state';
},
customerHomeTypeName(): string {
const types: Record<number, string> = {
0: 'Residential', 1: 'apartment', 2: 'condo', 3: 'commercial',
4: 'business', 5: 'construction', 6: 'container',
};
const types: Record<number, string> = { 0: 'Residential', 1: 'apartment', 2: 'condo', 3: 'commercial', 4: 'business', 5: 'construction', 6: 'container' };
return types[this.customer.customer_home_type] || 'Unknown type';
},
isAnyPaymentMethodSelected(): boolean {
@@ -499,65 +506,38 @@ export default defineComponent({
this.getPaymentCards(customerId);
},
methods: {
setGallons(amount: number) {
this.formDelivery.gallons_ordered = String(amount);
this.formDelivery.customer_asked_for_fill = false;
},
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];
},
setGallons(amount: number) { this.formDelivery.gallons_ordered = String(amount); this.formDelivery.customer_asked_for_fill = false; },
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 {
if (!this.formDelivery.gallons_ordered) return false;
const selectedGallons = Number(this.formDelivery.gallons_ordered);
if (isNaN(selectedGallons)) return false;
const tierNum = Number(tierGallons);
if (isNaN(tierNum)) return false;
const shouldHighlight = selectedGallons === tierNum;
return shouldHighlight;
return selectedGallons === tierNum;
},
getPricingTiers() {
let path = import.meta.env.VITE_BASE_URL + "/info/price/oil/tiers";
axios({ method: "get", url: path, withCredentials: true, headers: authHeader() })
.then((response: SimpleResponse<{ [key: string]: string }>) => {
const tiersObject = response.data;
this.pricingTiers = Object.entries(tiersObject).map(([gallons, price]) => ({
gallons: parseInt(gallons, 10),
price: price,
}));
this.pricingTiers = Object.entries(response.data).map(([gallons, price]) => ({ gallons: parseInt(gallons, 10), price: price }));
})
.catch(() => {
notify({ title: "Pricing Error", text: "Could not retrieve today's pricing.", type: "error" });
});
.catch(() => notify({ title: "Pricing Error", text: "Could not retrieve today's pricing.", type: "error" }));
},
getCustomer(user_id: string | number | string[]) {
let path = import.meta.env.VITE_BASE_URL + "/customer/" + user_id;
axios({ method: "get", url: path, withCredentials: true })
.then((response: SimpleResponse<Customer>) => {
this.customer = response.data;
})
.catch(() => {
notify({ title: "Error", text: "Could not find customer", type: "error" });
});
.then((response: SimpleResponse<Customer>) => { this.customer = response.data; })
.catch(() => notify({ title: "Error", text: "Could not find customer", type: "error" }));
},
getPaymentCards(user_id: string | number | string[]) {
let path = import.meta.env.VITE_BASE_URL + "/payment/cards/" + user_id;
return axios({ method: "get", url: path, withCredentials: true })
.then((response: SimpleResponse<UserCard[]>) => {
this.userCards = response.data;
})
.catch(() => { /* empty */ });
// IMPORTANT: This endpoint points to the Flask API that returns the secure card list.
let path = `${import.meta.env.VITE_BASE_URL}/payment/cards/${user_id}`;
return axios.get(path, { withCredentials: true, headers: authHeader() })
.then((response: SimpleResponse<UserCard[]>) => { this.userCards = response.data; })
.catch(() => { this.userCards = []; }); // Clear cards on error
},
getPromos() {
let path = import.meta.env.VITE_BASE_URL + "/promo/all";
@@ -582,7 +562,8 @@ export default defineComponent({
removeCard(card_id: number) {
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() })
.then(() => {
notify({ title: "Card Removed", type: "success" });
@@ -595,14 +576,11 @@ export default defineComponent({
},
async onDeliverySubmit() {
const isDeliveryFormValid = await this.v$.formDelivery.$validate();
const isPaymentMethodSelectedValid = await this.v$.isAnyPaymentMethodSelected.$validate();
if (!isDeliveryFormValid || !isPaymentMethodSelectedValid) {
const isFormValid = await this.v$.formDelivery.$validate();
if (!isFormValid) {
notify({ title: "Form Incomplete", text: "Please review the fields marked in red.", type: "warn" });
return;
}
if (this.formDelivery.cash || this.formDelivery.check) {
this.isConfirmationModalVisible = true;
} else {
@@ -610,81 +588,114 @@ export default defineComponent({
}
},
proceedWithSubmission() {
async proceedWithSubmission() {
this.isConfirmationModalVisible = false;
let payload = {
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,
};
this.isLoading = true;
// Step 1: Create the delivery order record
const createDeliveryPath = `${import.meta.env.VITE_BASE_URL}/delivery/create/${this.customer.id}`;
let path = `${import.meta.env.VITE_BASE_URL}/delivery/create/${this.customer.id}`;
axios({ method: "post", url: path, data: payload, withCredentials: true, headers: authHeader() })
.then((response: SimpleResponse<{ ok: boolean; delivery_id: number }>) => {
if (response.data.ok) {
this.$router.push({ name: "payOil", params: { id: response.data.delivery_id } });
} else {
this.$router.push("/");
}
try {
const deliveryResponse = await axios.post(createDeliveryPath, this.formDelivery, { withCredentials: true, headers: authHeader() });
const deliveryData = deliveryResponse.data;
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() {
this.v$.formCard.$validate();
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;
}
let payload = {
name_on_card: this.formCard.card_name,
this.isCardSaving = true;
// --- 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,
expiration_month: this.formCard.expiration_month,
expiration_year: this.formCard.expiration_year,
type_of_card: this.formCard.type_of_card,
security_number: this.formCard.security_number,
main_card: this.formCard.main_card,
zip_code: this.formCard.zip_code,
security_number: this.formCard.security_number, // Flask expects 'security_number'
main_card: false,
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 {
const response = await axios({ method: "post", url: path, data: payload, withCredentials: true, headers: authHeader() });
if (response.data.ok) {
notify({ type: 'success', title: 'Card Saved!' });
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() });
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" });
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.");
}
} catch (error) {
notify({ title: "Error", text: "An unexpected error occurred while adding the card.", type: "error" });
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.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>
<!-- 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 -->
<div class="space-y-4">
@@ -115,7 +115,7 @@
</div>
<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>
<!-- Fees -->
@@ -133,11 +133,11 @@
<span v-else-if="deliveryOrder.payment_type == 3">Check</span>
<span v-else>No Payment Type Added</span>
</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 class="font-bold text-sm">{{ userCard.name_on_card }}</div>
<div class="text-xs opacity-70">{{ userCard.type_of_card }}</div>
<div class="mt-1 text-sm font-mono tracking-wider">
<p>{{ userCard.card_number }}</p>
<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">
<!-- --- MODIFICATION --- Safe display of card data -->
<div class="font-bold text-sm">{{ userCard.type_of_card }}</div>
<div class="text-sm font-mono tracking-wider">
<p>**** **** **** {{ userCard.last_four }}</p>
<p>Exp: {{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p>
</div>
</div>
@@ -145,17 +145,11 @@
<!-- Total -->
<div class="flex justify-between items-center border-t border-base-100 pt-3">
<span class="text-lg font-bold">
<span v-if="deliveryOrder.payment_type == 0">Cash Total</span>
<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>
Final Charge Amount
</span>
<!-- --- MODIFICATION --- Use `finalChargeAmount` computed property for live updates -->
<span class="text-2xl font-bold text-success">
<span v-if="deliveryOrder.payment_type == 1 || deliveryOrder.payment_type == 2 || deliveryOrder.payment_type == 3">
${{ Number(preChargeTotal).toFixed(2) }}
</span>
<span v-else>
${{ Number(total_amount).toFixed(2) }}
</span>
${{ finalChargeAmount.toFixed(2) }}
</span>
</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" />
</div>
<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>
</form>
@@ -208,7 +202,6 @@
</div>
<Footer />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
@@ -218,49 +211,40 @@ import SideBar from '../../../layouts/sidebar/sidebar.vue'
import Footer from '../../../layouts/footers/footer.vue'
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({
name: 'finalizeTicket',
components: {
Header,
SideBar,
Footer,
},
components: { Header, SideBar, Footer },
data() {
return {
loaded: false,
isLoading: false,
user: { id: 0 },
userCardfound: false,
userCards: [],
deliveryNotesDriver: [],
total_amount: 0,
preChargeTotal: 0,
FinalizeOilOrderForm: {
cash_recieved: '',
fill_location: 0,
check_number: 0,
credit_card_id: 0,
driver: 0,
fill_location: '',
check_number: '',
gallons_delivered: '',
},
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: '',
},
userCard: {} as UserCard,
customer: {
id: 0,
user_id: 0,
customer_address: '',
customer_first_name: '',
customer_last_name: '',
@@ -271,268 +255,172 @@ export default defineComponent({
customer_home_type: 0,
customer_phone_number: '',
},
customerDescription: {
customer_id: 0,
account_number: '',
company_id: 0,
fill_location: 0,
description: '',
},
customerDescription: { fill_location: '' },
deliveryOrder: {
id: '',
customer_id: 0,
customer_name: '',
customer_address: '',
customer_town: '',
customer_state: 0,
customer_zip: '',
gallons_ordered: 0,
customer_asked_for_fill: 0,
gallons_delivered: '',
customer_filled: 0,
delivery_status: 0,
when_ordered: '',
when_delivered: '',
expected_delivery_date: '',
automatic: 0,
oil_id: 0,
supplier_price: '',
customer_price: '',
customer_temperature: '',
dispatcher_notes: '',
prime: 0,
same_day: 0,
payment_type: 0,
payment_card_id: '',
driver_employee_id: 0,
driver_first_name: '',
driver_last_name: '',
total_price: 0,
},
pricing: {
price_from_supplier: 0,
price_for_customer: 0,
price_for_employee: 0,
price_same_day: 0,
price_prime: 0,
date: "",
price_same_day: 0,
},
}
},
mounted() {
computed: {
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;
this.sumdelivery(deliveryId);
// --- DEBUGGING STEP 1 ---
console.log(`[DEBUG] Component Mounted. Fetching data for delivery ID: ${deliveryId}`);
this.getOilOrder(deliveryId);
this.getOilPricing();
},
methods: {
getOilOrder(delivery_id: any) {
async getOilOrder(delivery_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/delivery/order/${delivery_id}`;
axios.get(path, { withCredentials: true, headers: authHeader() })
.then((response: any) => {
if (response.data && response.data.ok) {
this.deliveryOrder = response.data.delivery;
this.getCustomer(this.deliveryOrder.customer_id);
// --- DEBUGGING STEP 2 ---
console.log(`[DEBUG] Calling getOilOrder API at: ${path}`);
try {
const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
// --- DEBUGGING STEP 3 ---
console.log('[DEBUG] Received RAW response from getOilOrder:', response.data);
if ([1, 2, 3].includes(this.deliveryOrder.payment_type)) {
this.getPaymentCard(this.deliveryOrder.payment_card_id);
}
if (response.data && response.data.ok) {
console.log('[DEBUG] Response is OK. Processing data...');
this.deliveryOrder = response.data.delivery;
// --- DEBUGGING STEP 4 ---
console.log(`[DEBUG] Value of response.data.total_amount is:`, response.data.total_amount);
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 || '';
// Properly initialize all form fields with existing delivery data
this.FinalizeOilOrderForm.cash_recieved = response.data.delivery.cash_recieved || '';
this.FinalizeOilOrderForm.check_number = response.data.delivery.check_number || '';
this.FinalizeOilOrderForm.credit_card_id = response.data.delivery.payment_card_id;
this.FinalizeOilOrderForm.gallons_delivered = response.data.delivery.gallons_delivered || '';
this.FinalizeOilOrderForm.driver = response.data.delivery.driver_employee_id || 0;
} else {
console.error("API Error:", response.data.error || "Failed to fetch delivery data.");
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);
}
})
.catch((error: any) => console.error("Error fetching oil order:", error));
} else {
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}`;
axios.get(path, { withCredentials: true })
.then((response: any) => {
if (response.data.userCard && response.data.userCard.card_number !== '') {
this.userCard = response.data;
this.userCardfound = true;
} else {
this.userCardfound = false;
}
})
.catch((error: any) => {
this.userCardfound = false;
console.error(`Error fetching payment card ${card_id}:`, error);
});
try {
const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
this.userCard = response.data;
this.userCardfound = true;
} catch (error) {
this.userCardfound = false;
console.error(`[DEBUG] Error fetching payment card ${card_id}:`, error);
}
},
getCustomer(user_id: any) {
async getCustomer(user_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
axios.get(path, { withCredentials: true })
.then((response: any) => {
this.customer = response.data;
this.getCustomerDescription(this.deliveryOrder.customer_id);
})
.catch((error: any) => {
notify({ title: "Error", text: "Could not find customer", type: "error" });
console.error("Error fetching customer:", error);
});
try {
const response = await axios.get(path, { withCredentials: true });
this.customer = response.data;
await this.getCustomerDescription(this.deliveryOrder.customer_id);
} catch (error) { console.error("[DEBUG] Error fetching customer:", error); }
},
getCustomerDescription(user_id: any) {
async getCustomerDescription(user_id: any) {
const path = `${import.meta.env.VITE_BASE_URL}/customer/description/${user_id}`;
axios.get(path, { withCredentials: true })
.then((response: any) => {
this.customerDescription = response.data;
this.FinalizeOilOrderForm.fill_location = this.customerDescription.fill_location;
})
.catch((error: any) => {
notify({ title: "Error", text: "Could not find customer description", type: "error" });
console.error("Error fetching customer description:", error);
});
try {
const response = await axios.get(path, { withCredentials: true });
this.customerDescription = response.data;
this.FinalizeOilOrderForm.fill_location = this.customerDescription.fill_location;
} catch (error) { console.error("[DEBUG] Error fetching customer description:", error); }
},
getOilPricing() {
const path = `${import.meta.env.VITE_BASE_URL}/info/price/oil/table`;
axios.get(path, { withCredentials: true })
.then((response: any) => {
this.pricing = response.data;
})
.catch((error: any) => {
notify({ title: "Error", text: "Could not get oil pricing", type: "error" });
console.error("Error fetching oil pricing:", error);
});
.then((response: any) => { this.pricing = response.data; })
.catch((error: any) => { console.error("[DEBUG] 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() {
const path = `${import.meta.env.VITE_MONEY_URL}/delivery/add/${this.deliveryOrder.id}`;
axios.post(path, {}, { withCredentials: true, headers: authHeader() })
.then((response: any) => {
if (response.status === 201) {
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);
});
.then(() => notify({ title: "Success", text: "Accounting record created.", type: "success" }))
.catch(() => notify({ title: "Warning", text: "Could not create accounting record.", type: "warn" }));
},
FinalizeOrder(payload: any) {
const path = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${this.deliveryOrder.id}`;
axios.put(path, payload, { withCredentials: true, headers: authHeader() })
.then((response: any) => {
if (response.data.ok) {
notify({ title: "Success", text: "Ticket is finalized", type: "success" });
this.CreateTransaction();
this.$router.push({ name: "deliveryOrder", params: { id: this.deliveryOrder.id } });
async onSubmit() {
if (Number(this.FinalizeOilOrderForm.gallons_delivered) <= 0) {
notify({ title: "Validation Error", text: "Gallons delivered must be greater than zero.", type: "error" });
return;
}
this.isLoading = true;
const finalizePayload = {
gallons_delivered: this.FinalizeOilOrderForm.gallons_delivered,
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 {
notify({ title: "Error", text: response.data.error || "Could not finalize ticket", type: "error" });
this.$router.push({ name: "delivery" });
notify({ title: "Warning", text: "No valid pre-authorization found to capture. Please charge manually.", type: "warn" });
}
})
.catch((error: any) => {
notify({ title: "Error", text: "Failed to finalize order", type: "error" });
console.error("FinalizeOrder error:", error);
});
}
this.CreateTransaction();
notify({ title: "Success", text: "Ticket has been finalized.", type: "success" });
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 = ''
try {
const endpoint = actionType === 'preauthorize' ? 'authorize' : 'charge'
const payload = {
card_number: (this.selectedCard as any).card_number,
expiration_date: `${(this.selectedCard as any).expiration_month}${(this.selectedCard as any).expiration_year}`,
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
}
// Step 2: If payment method is credit, perform the pre-authorization
if (actionType === 'preauthorize') {
if (!this.chargeAmount || this.chargeAmount <= 0) {
throw new Error("Pre-authorization amount must be greater than zero.");
}
console.log('=== DEBUG: Payment payload ===')
console.log('Delivery ID:', this.delivery.id)
console.log('Final payload being sent:', payload)
const authPayload = {
card_id: (this.selectedCard as any).id,
preauthorize_amount: this.chargeAmount.toFixed(2),
delivery_id: this.delivery.id,
};
const response = await axios.post(
`${import.meta.env.VITE_AUTHORIZE_URL}/api/${endpoint}/?customer_id=${this.customer.id}`,
payload,
{ withCredentials: true }
)
const authPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/authorize/saved-card/${this.customer.id}`;
if (response.data && response.data.status === 0) {
this.success = `${actionType === 'preauthorize' ? 'Preauthorization' : 'Charge'} successful! Transaction ID: ${response.data.auth_net_transaction_id || 'N/A'}`
const response = await axios.post(authPath, authPayload, { withCredentials: true, headers: authHeader() });
// On successful authorization, show success and redirect
this.success = `Preauthorization successful! Transaction ID: ${response.data?.auth_net_transaction_id || 'N/A'}`;
setTimeout(() => {
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
}, 2000)
} else {
throw new Error(`Payment ${actionType} failed: ${response.data?.status || 'Unknown error'}`)
}, 2000);
} else { // Handle 'charge' action
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) {
this.error = error.response?.data?.detail || `Failed to ${actionType} payment`