Files
eamco_office_frontend/src/pages/pay/oil/capture_authorize.vue
2026-01-28 21:55:14 -05:00

687 lines
26 KiB
Vue

<!-- src/pages/pay/oil/capture_authorize.vue -->
<template>
<div class="flex">
<!-- Main container with responsive horizontal padding -->
<div class="w-full px-4 md:px-6 py-4">
<div class="text-sm breadcrumbs">
<ul>
<li><router-link :to="{ name: 'home' }">Home</router-link></li>
<li><router-link :to="{ name: 'customer' }">Customers</router-link></li>
<li v-if="customer && customer.id">
<router-link :to="{ name: 'customerProfile', params: { id: customer.id } }">
{{ customer.customer_first_name }} {{ customer.customer_last_name }}
</router-link>
</li>
<li>Capture Payment #{{ deliveryOrder.id }}</li>
</ul>
</div>
<!-- Page Header -->
<div class="flex flex-wrap justify-between items-center gap-2 mt-4">
<h1 class="text-3xl font-bold">
Capture Payment #{{ deliveryOrder.id }}
</h1>
<router-link v-if="deliveryOrder.id" :to="{ name: 'finalizeTicket', params: { id: deliveryOrder.id } }">
<button class="btn btn-sm btn-secondary">Back to Finalize</button>
</router-link>
</div>
<!-- Main Content Grid -->
<div v-if="deliveryOrder.id" class="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
<!-- LEFT COLUMN: Customer and Delivery Details -->
<div class="space-y-6">
<!-- Customer Info Card -->
<div class="bg-neutral rounded-lg p-5">
<div class="text-xl font-bold mb-2">Customer</div>
<div>
<div class="font-bold">{{ customer.customer_first_name }} {{ customer.customer_last_name }}</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">Maine</span>
<span v-else-if="customer.customer_state == 6">New York</span>
<span v-else>Unknown state</span>
{{ customer.customer_zip }}
</div>
<div class="mt-2 text-sm">
{{ customer.customer_phone_number }}
(<span v-if="customer.customer_home_type == 0">Residential</span>
<span v-else-if="customer.customer_home_type == 1">apartment</span>
<span v-else-if="customer.customer_home_type == 2">condo</span>
<span v-else-if="customer.customer_home_type == 3">commercial</span>
<span v-else-if="customer.customer_home_type == 4">business</span>
<span v-else-if="customer.customer_home_type == 5">construction</span>
<span v-else-if="customer.customer_home_type == 6">container</span>)
</div>
</div>
</div>
<!-- Financial Summary Card -->
<div class="bg-neutral rounded-lg p-5">
<h3 class="text-xl font-bold mb-4">Financial Summary</h3>
<div class="space-y-2">
<div class="flex justify-between">
<span>Gallons Delivered:</span>
<span>{{ gallonsDelivered || 0 }} gallons</span>
</div>
<div class="flex justify-between">
<span>Price per Gallon:</span>
<span>${{ deliveryOrder.customer_price || 0 }}</span>
</div>
<div class="flex justify-between font-semibold">
<span>Subtotal:</span>
<span>${{ calculateSubtotal() }}</span>
</div>
<div v-if="deliveryOrder.prime == 1" class="flex justify-between text-sm">
<span>Prime Fee:</span>
<span>+ ${{ pricing.price_prime || 0 }}</span>
</div>
<div v-if="deliveryOrder.same_day == 1" class="flex justify-between text-sm">
<span>Same Day Fee:</span>
<span>+ ${{ pricing.price_same_day || 0 }}</span>
</div>
<div v-if="deliveryOrder.emergency == 1" class="flex justify-between text-sm">
<span>Emergency Fee:</span>
<span>+ ${{ pricing.price_emergency || 0 }}</span>
</div>
<div v-if="promo_active" class="flex justify-between text-success">
<span>{{ promo.name_of_promotion }}:</span>
<span>- ${{ discount }}</span>
</div>
<hr class="my-3">
<div class="flex justify-between font-bold text-lg">
<span>Total:</span>
<span>${{ calculateTotalAmount() }}</span>
</div>
</div>
</div>
<!-- Delivery Details Card -->
<div class="bg-neutral rounded-lg p-5">
<h3 class="text-xl font-bold mb-4">Delivery Details</h3>
<div class="grid grid-cols-2 gap-x-4 gap-y-3 text-sm">
<div>
<div class="font-bold">Status</div>
<div class="opacity-80">
<span v-if="deliveryOrder.delivery_status == 0">waiting</span>
<span v-else-if="deliveryOrder.delivery_status == 1">delivered</span>
<span v-else-if="deliveryOrder.delivery_status == 2">Today</span>
<span v-else-if="deliveryOrder.delivery_status == 3">Tomorrow</span>
<span v-else-if="deliveryOrder.delivery_status == 4">Partial Delivery</span>
<span v-else-if="deliveryOrder.delivery_status == 5">misdelivery</span>
<span v-else-if="deliveryOrder.delivery_status == 6">unknown</span>
<span v-else-if="deliveryOrder.delivery_status == 10">Finalized</span>
</div>
</div>
<div>
<div class="font-bold">Scheduled Date</div>
<div class="opacity-80">{{ deliveryOrder.expected_delivery_date }}</div>
</div>
<div>
<div class="font-bold">When Ordered</div>
<div class="opacity-80">{{ deliveryOrder.when_ordered }}</div>
</div>
<div>
<div class="font-bold">When Delivered</div>
<div class="opacity-80">{{ deliveryOrder.when_delivered }}</div>
</div>
</div>
</div>
<!-- Transaction Summary -->
<div v-if="transaction && transaction.auth_net_transaction_id" class="bg-neutral rounded-lg p-5">
<h3 class="text-xl font-bold mb-4">Transaction Summary</h3>
<div class="space-y-3">
<div class="grid grid-cols-2 gap-x-4 gap-y-3 text-sm">
<div class="flex justify-between">
<span class="font-bold">Transaction ID:</span>
<span class="font-mono">{{ transaction.auth_net_transaction_id }}</span>
</div>
<div class="flex justify-between">
<span class="font-bold">Pre-Auth Amount:</span>
<span>${{ transaction.preauthorize_amount || '0.00' }}</span>
</div>
<div class="flex justify-between">
<span class="font-bold">Charge Amount:</span>
<span>${{ transaction.charge_amount || '0.00' }}</span>
</div>
<div class="flex justify-between">
<span class="font-bold">Type:</span>
<span :class="getTypeColor(transaction.transaction_type)">{{ transaction.transaction_type === 0 ? 'Charge' : transaction.transaction_type === 1 ? 'Auth' : 'Capture' }}</span>
</div>
<div class="flex justify-between">
<span class="font-bold">Date:</span>
<span>{{ transaction.created_at }}</span>
</div>
<div class="flex justify-between">
<span class="font-bold">Status:</span>
<span :class="transaction.status === 0 ? 'text-success' : 'text-error'">
{{ transaction.status === 0 ? 'Approved' : 'Declined' }}
</span>
</div>
</div>
</div>
</div>
<!-- Credit Card Details -->
<div v-if="userCardfound" class="bg-neutral rounded-lg p-5">
<h3 class="text-xl font-bold mb-4">Payment Method</h3>
<div class="p-2 rounded-lg border" :class="userCard.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">{{ userCard.name_on_card }}</div>
<div class="text-xs opacity-70">{{ userCard.type_of_card }}</div>
</div>
<div v-if="userCard.main_card" class="badge badge-primary badge-sm">Primary</div>
</div>
<div class="mt-1 text-sm font-mono tracking-wider">
<p>**** **** **** {{ userCard.last_four_digits }}</p>
<p>Exp: <span v-if="Number(userCard.expiration_month) < 10">0</span>{{ userCard.expiration_month }} / {{ userCard.expiration_year }}</p>
</div>
</div>
</div>
</div>
<!-- RIGHT COLUMN: Capture Form -->
<div class="space-y-6">
<!-- Gallons Delivered Display -->
<div class="bg-base-100 rounded-lg p-5">
<h2 class="text-2xl font-bold mb-4">Gallons Delivered</h2>
<div class="text-center">
<div class="text-4xl font-bold text-success">{{ gallonsDelivered || '0.00' }}</div>
<div class="text-sm opacity-70">gallons</div>
</div>
</div>
<!-- Capture Payment Form -->
<div class="bg-base-100 rounded-lg p-5">
<h2 class="text-2xl font-bold mb-4">Capture Payment</h2>
<div v-if="preAuthAmount > 0" class="mb-2 text-sm text-orange-600">
Max Capture amount: ${{ preAuthAmount.toFixed(2) }}
</div>
<div class="space-y-4">
<div class="form-control">
<label class="label">
<span class="label-text font-bold">Capture Amount</span>
</label>
<div v-if="captureAmount > preAuthAmount" class="text-sm text-error mb-2">
Cannot capture more than the preauthorization amount.
</div>
<input
v-model="captureAmount"
class="input input-bordered input-sm w-full"
type="number"
step="0.01"
placeholder="0.00"
/>
</div>
<div class="flex gap-4">
<button
@click="capturePayment"
:class="`btn flex-1 ${captureAmount > 0 ? 'btn-success' : 'btn-error'}`"
:disabled="loading || !captureAmount || captureAmount > preAuthAmount"
>
<span v-if="loading" class="loading loading-spinner loading-sm"></span>
Capture Payment
</button>
<button
@click="cancelCapture"
class="btn btn-ghost"
:disabled="loading"
>
Cancel
</button>
</div>
</div>
</div>
</div>
</div>
<div v-else class="text-center p-10">
Loading capture details...
</div>
</div>
</div>
<!-- Payment Capture Success Modal -->
<div class="modal" :class="{ 'modal-open': showPaymentModal }">
<div class="modal-box">
<h3 class="font-bold text-lg">Payment Captured Successfully</h3>
<div class="py-4">
<div v-if="modalStep === 0" class="text-center">
<span class="text-lg mb-3">Transaction ID: {{ transaction?.auth_net_transaction_id }}</span>
<div class="loading loading-spinner loading-lg text-success mb-3"></div>
<p class="text-sm text-gray-600">Processing payment capture...</p>
</div>
<div v-else-if="modalStep === 1" class="text-center">
<span class="text-lg mb-3">Transaction ID: {{ transaction?.auth_net_transaction_id }}</span>
<p class="text-lg">Captured Amount: ${{ modalCapturedAmount }}</p>
</div>
</div>
</div>
</div>
<Footer />
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios, { AxiosResponse, AxiosError } from 'axios'
import authHeader from '../../../services/auth.header'
import Header from '../../../layouts/headers/headerauth.vue'
import SideBar from '../../../layouts/sidebar/sidebar.vue'
import Footer from '../../../layouts/footers/footer.vue'
import { notify } from "@kyvg/vue3-notification"
import type {
CustomerFormData,
CreditCardFormData,
PricingData,
PromoData,
DeliveryOrderResponse,
DeliveryTotalResponse,
OilPricingResponse,
PromoResponse,
PaymentCardResponse,
AuthorizeNetTransactionResponse
} from '../../../types/models'
const route = useRoute()
const router = useRouter()
// Reactive data
const loading = ref(false)
const userCardfound = ref(false)
const gallonsDelivered = ref('')
const captureAmount = ref(0)
const preAuthAmount = ref(0)
const transaction = ref<AuthorizeNetTransactionResponse | null>(null)
const showPaymentModal = ref(false)
const modalStep = ref(0)
const modalCapturedAmount = ref(0)
const userCard = ref<CreditCardFormData>({
id: 0,
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: false,
})
const customer = ref<CustomerFormData>({
id: 0,
user_id: 0,
customer_address: '',
customer_first_name: '',
customer_last_name: '',
customer_town: '',
customer_state: 0,
customer_zip: '',
customer_apt: '',
customer_home_type: 0,
customer_phone_number: '',
account_number: '',
})
const deliveryOrder = ref({
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,
emergency: 0,
promo_id: 0,
payment_type: 0,
payment_card_id: '',
driver_employee_id: 0,
driver_first_name: '',
driver_last_name: '',
total_price: 0,
})
const pricing = ref<PricingData>({
price_from_supplier: 0,
price_for_customer: 0,
price_for_employee: 0,
price_same_day: 0,
price_prime: 0,
price_emergency: 0,
date: "",
})
const promo_active = ref(false)
const promo = ref<PromoData>({
name_of_promotion: '',
description: '',
money_off_delivery: 0,
text_on_ticket: ''
})
const total_amount = ref(0)
const discount = ref(0)
const total_amount_after_discount = ref(0)
// Lifecycle
onMounted(() => {
getOilOrder(route.params.id)
getOilPricing()
getTransaction()
})
// Functions
const sumdelivery = (delivery_id: number | string) => {
let path = import.meta.env.VITE_BASE_URL + "/delivery/total/" + delivery_id;
axios({
method: "get",
url: path,
withCredentials: true,
})
.then((response: AxiosResponse<DeliveryTotalResponse>) => {
if (response.data.ok) {
total_amount.value = parseFloat(String(response.data.total_amount)) || 0;
discount.value = parseFloat(String(response.data.discount)) || 0;
total_amount_after_discount.value = parseFloat(String(response.data.total_amount_after_discount)) || 0;
// Set capture amount to the calculated total including fees and discount
captureAmount.value = calculateTotalAsNumber();
}
})
.catch(() => {
notify({
title: "Error",
text: "Could not get totals",
type: "error",
});
});
}
const getPromo = (promo_id: number) => {
let path = import.meta.env.VITE_BASE_URL + "/promo/" + promo_id;
axios({
method: "get",
url: path,
withCredentials: true,
headers: authHeader(),
})
.then((response: AxiosResponse<PromoResponse>) => {
if (response.data) {
promo.value = response.data
promo_active.value = true
}
})
}
const getOilOrder = (delivery_id: number | string) => {
const path = `${import.meta.env.VITE_BASE_URL}/delivery/order/${delivery_id}`;
axios.get<DeliveryOrderResponse>(path, { withCredentials: true, headers: authHeader() })
.then((response) => {
if (response.data && response.data.ok) {
deliveryOrder.value = response.data.delivery as typeof deliveryOrder.value;
gallonsDelivered.value = deliveryOrder.value.gallons_delivered;
getCustomer(deliveryOrder.value.customer_id);
sumdelivery(delivery_id);
if ([1, 2, 3].includes(deliveryOrder.value.payment_type)) {
getPaymentCard(deliveryOrder.value.payment_card_id);
}
if (deliveryOrder.value.promo_id != null) {
getPromo(deliveryOrder.value.promo_id);
promo_active.value = true;
}
} else {
console.error("API Error:", response.data.error || "Failed to fetch delivery data.");
}
})
.catch((error: Error) => console.error("Error fetching oil order:", error));
}
const getPaymentCard = (card_id: number | string) => {
const path = `${import.meta.env.VITE_BASE_URL}/payment/card/${card_id}`;
axios.get<PaymentCardResponse>(path, { withCredentials: true })
.then((response) => {
if (response.data.userCard && response.data.userCard.card_number !== '') {
userCard.value = response.data.userCard as CreditCardFormData;
userCardfound.value = true;
}
})
.catch((error: Error) => {
userCardfound.value = false;
console.error("Error fetching payment card:", error);
});
}
const getCustomer = (user_id: number) => {
const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
axios.get<CustomerFormData>(path, { withCredentials: true })
.then((response) => {
customer.value = response.data;
})
.catch((error: Error) => {
notify({ title: "Error", text: "Could not find customer", type: "error" });
console.error("Error fetching customer:", error);
});
}
const getOilPricing = () => {
const path = `${import.meta.env.VITE_BASE_URL}/info/price/oil/table`;
axios.get<OilPricingResponse>(path, { withCredentials: true })
.then((response) => {
pricing.value = response.data;
// Calculate capture amount if delivery order is already loaded
calculateCaptureAmount();
})
.catch((error: Error) => {
notify({ title: "Error", text: "Could not get oil pricing", type: "error" });
console.error("Error fetching oil pricing:", error);
});
}
const getTransaction = () => {
const path = `${import.meta.env.VITE_AUTHORIZE_URL}/api/transaction/delivery/${route.params.id}`;
axios.get<AuthorizeNetTransactionResponse>(path, { withCredentials: true, headers: authHeader() })
.then((response) => {
transaction.value = response.data;
preAuthAmount.value = parseFloat(String(response.data.preauthorize_amount) || '0');
if (response.data.status !== 0) { // Not approved
preAuthAmount.value = 0;
}
})
.catch((error: AxiosError) => {
if (error.response && error.response.status === 404) {
notify({ title: "Info", text: "No pre-authorization found. Redirecting to customer profile to update payment method.", type: "info" });
console.log("No transaction found for delivery - redirecting to customer profile");
router.push({ name: 'customerProfile', params: { id: customer.value.id } });
} else {
notify({ title: "Error", text: "No pre-authorized transaction found", type: "error" });
router.push({ name: 'finalizeTicket', params: { id: route.params.id } });
}
});
}
const capturePayment = async () => {
if (!transaction.value || !captureAmount.value) {
notify({ title: "Error", text: "Invalid capture amount or transaction data", type: "error" });
return;
}
loading.value = true;
try {
const payload = {
charge_amount: captureAmount.value, // FastAPI handles string/number conversion
auth_net_transaction_id: transaction.value.auth_net_transaction_id
};
// ✅ FIX: Cleaned up URL, removing the unnecessary customer_id query parameter.
const url = `${import.meta.env.VITE_AUTHORIZE_URL}/api/capture/`;
const response = await axios.post(
url,
payload,
{ withCredentials: true, headers: authHeader() }
);
// ✅ FIX: Improved logic to handle both success and declines properly.
if (response.data && response.data.status === 0) {
// This is the APPROVED case
modalCapturedAmount.value = captureAmount.value;
showPaymentModal.value = true;
setTimeout(() => { modalStep.value = 1 }, 2000);
setTimeout(() => { showPaymentModal.value = false; router.push({ name: 'deliveryOrder', params: { id: route.params.id } }) }, 4000);
} else if (response.data && response.data.status === 1) {
// This is the DECLINED case
const reason = response.data.rejection_reason || "The payment was declined by the gateway.";
notify({
title: "Payment Declined",
text: reason,
type: "warn", // Use 'warn' for declines instead of 'error'
});
} else {
// This handles unexpected responses from the backend.
throw new Error("Invalid response from server during capture.");
}
} catch (err: unknown) {
// This 'catch' block now only handles network errors or server crashes (500 errors).
const error = err as AxiosError<{ detail?: string }>;
const detail = error.response?.data?.detail || "Failed to capture payment due to a server error.";
notify({
title: "Error",
text: detail,
type: "error",
});
console.error("Capture Payment Error:", error);
} finally {
loading.value = false;
}
}
const calculateSubtotal = () => {
const gallons = parseFloat(gallonsDelivered.value || '0') || 0;
const pricePerGallon = typeof deliveryOrder.value.customer_price === 'string' ? parseFloat(deliveryOrder.value.customer_price) : Number(deliveryOrder.value.customer_price) || 0;
return (gallons * pricePerGallon).toFixed(2);
}
const calculateTotalAmount = () => {
if (total_amount_after_discount.value == null || total_amount_after_discount.value === undefined) {
return '0.00';
}
let totalNum = Number(total_amount_after_discount.value);
if (isNaN(totalNum)) {
return '0.00';
}
if (deliveryOrder.value && deliveryOrder.value.prime == 1 && pricing.value && pricing.value.price_prime) {
totalNum += Number(pricing.value.price_prime) || 0;
}
if (deliveryOrder.value && deliveryOrder.value.same_day == 1 && pricing.value && pricing.value.price_same_day) {
totalNum += Number(pricing.value.price_same_day) || 0;
}
if (deliveryOrder.value && deliveryOrder.value.emergency == 1 && pricing.value && pricing.value.price_emergency) {
totalNum += Number(pricing.value.price_emergency) || 0;
}
return totalNum.toFixed(2);
}
const calculateTotalAsNumber = () => {
if (total_amount_after_discount.value == null || total_amount_after_discount.value === undefined) {
return 0;
}
let totalNum = Number(total_amount_after_discount.value);
if (isNaN(totalNum)) {
return 0;
}
if (deliveryOrder.value && deliveryOrder.value.prime == 1 && pricing.value && pricing.value.price_prime) {
totalNum += Number(pricing.value.price_prime) || 0;
}
if (deliveryOrder.value && deliveryOrder.value.same_day == 1 && pricing.value && pricing.value.price_same_day) {
totalNum += Number(pricing.value.price_same_day) || 0;
}
if (deliveryOrder.value && deliveryOrder.value.emergency == 1 && pricing.value && pricing.value.price_emergency) {
totalNum += Number(pricing.value.price_emergency) || 0;
}
return totalNum;
}
const calculateCaptureAmount = () => {
// Only calculate if we have both delivery order and pricing data
if (deliveryOrder.value.id && pricing.value.price_for_customer) {
const gallons = typeof gallonsDelivered.value === 'string' ? parseFloat(gallonsDelivered.value) : Number(gallonsDelivered.value) || 0;
const pricePerGallon = typeof deliveryOrder.value.customer_price === 'string' ? parseFloat(deliveryOrder.value.customer_price) : Number(deliveryOrder.value.customer_price) || 0;
let total = gallons * pricePerGallon;
// Add prime fee if applicable
if (deliveryOrder.value.prime == 1) {
const primeFee = typeof pricing.value.price_prime === 'string' ? parseFloat(pricing.value.price_prime) : Number(pricing.value.price_prime) || 0;
total += primeFee;
}
// Add same day fee if applicable
if (deliveryOrder.value.same_day === 1) {
const sameDayFee = typeof pricing.value.price_same_day === 'string' ? parseFloat(pricing.value.price_same_day) : Number(pricing.value.price_same_day) || 0;
total += sameDayFee;
}
captureAmount.value = total;
}
}
const cancelCapture = () => {
router.push({ name: 'finalizeTicket', params: { id: route.params.id } });
}
const getTypeColor = (transactionType: number) => {
switch (transactionType) {
case 1: return 'text-blue-600'; // Auth
case 0: return 'text-orange-600'; // Charge
case 2: return 'text-purple-600'; // Capture
case 3: return 'text-green-600'; // Delivery/Other
default: return 'text-gray-600';
}
}
</script>
<style scoped></style>