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

@@ -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>