Updated charge close to working

This commit is contained in:
2025-09-09 18:26:21 -04:00
parent fd11c9e794
commit 98fe855e65
19 changed files with 1785 additions and 372 deletions

View File

@@ -0,0 +1,492 @@
<!-- src/pages/pay/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-3">
<!-- Pricing & Gallons -->
<div class="grid grid-cols-2 gap-3 text-sm">
<div>
<div class="font-bold">Price / Gallon</div>
<div class="opacity-80">${{ Number(deliveryOrder.customer_price).toFixed(2) }}</div>
</div>
<div>
<div class="font-bold">Gallons Delivered</div>
<div class="opacity-80">{{ gallonsDelivered || '0.00' }}</div>
</div>
</div>
<!-- Fees -->
<div class="text-sm space-y-1 border-t border-base-100 pt-3">
<div v-if="deliveryOrder.prime == 1" class="flex justify-between">
<span>Prime Fee</span>
<span>${{ Number(pricing.price_prime).toFixed(2) }}</span>
</div>
<div v-if="deliveryOrder.same_day === 1" class="flex justify-between">
<span>Same Day Fee</span>
<span>${{ Number(pricing.price_same_day).toFixed(2) }}</span>
</div>
</div>
<!-- Total -->
<div class="flex justify-between items-center border-t border-base-100 pt-3">
<span class="text-lg font-bold">Total Amount</span>
<span class="text-2xl font-bold text-success">${{ Number(captureAmount).toFixed(2) }}</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>
<!-- 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-primary">{{ 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 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>
<Footer />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios 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"
export default defineComponent({
name: 'captureAuthorize',
components: {
Header,
SideBar,
Footer,
},
data() {
return {
loading: false,
userCardfound: false,
gallonsDelivered: '',
captureAmount: 0,
preAuthAmount: 0,
transaction: null as any,
userCard: {
date_added: '',
user_id: '',
card_number: '',
last_four_digits: '',
name_on_card: '',
expiration_month: '',
expiration_year: '',
type_of_card: '',
security_number: '',
accepted_or_declined: '',
main_card: '',
},
customer: {
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: '',
},
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: "",
},
}
},
mounted() {
this.getOilOrder(this.$route.params.id)
this.getOilPricing()
this.getTransaction()
},
methods: {
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.gallonsDelivered = this.deliveryOrder.gallons_delivered;
this.getCustomer(this.deliveryOrder.customer_id);
if ([1, 2, 3].includes(this.deliveryOrder.payment_type)) {
this.getPaymentCard(this.deliveryOrder.payment_card_id);
}
// Calculate capture amount if pricing is already loaded
this.calculateCaptureAmount();
} else {
console.error("API Error:", response.data.error || "Failed to fetch delivery data.");
}
})
.catch((error: any) => console.error("Error fetching oil order:", error));
},
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;
}
})
.catch((error: any) => {
this.userCardfound = false;
console.error("Error fetching payment card:", error);
});
},
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;
})
.catch((error: any) => {
notify({ title: "Error", text: "Could not find customer", type: "error" });
console.error("Error fetching customer:", 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;
// Calculate capture amount if delivery order is already loaded
this.calculateCaptureAmount();
})
.catch((error: any) => {
notify({ title: "Error", text: "Could not get oil pricing", type: "error" });
console.error("Error fetching oil pricing:", error);
});
},
getTransaction() {
const path = `${import.meta.env.VITE_AUTHORIZE_URL}/api/transaction/delivery/${this.$route.params.id}`;
axios.get(path, { withCredentials: true, headers: authHeader() })
.then((response: any) => {
this.transaction = response.data;
this.preAuthAmount = parseFloat(response.data.preauthorize_amount || 0);
if (response.data.status !== 0) { // Not approved
this.preAuthAmount = 0;
}
})
.catch((error: any) => {
notify({ title: "Error", text: "No pre-authorized transaction found", type: "error" });
console.error("Error fetching transaction:", error);
this.$router.push({ name: 'finalizeTicket', params: { id: this.$route.params.id } });
});
},
async capturePayment() {
if (!this.transaction || !this.captureAmount) {
notify({ title: "Error", text: "Invalid capture amount or transaction data", type: "error" });
return;
}
this.loading = true;
try {
const payload = {
charge_amount: this.captureAmount, // FastAPI handles string/number conversion
auth_net_transaction_id: this.transaction.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
notify({
title: "Success",
text: "Payment captured successfully!",
type: "success",
});
this.$router.push({ name: 'deliveryOrder', params: { id: this.$route.params.id } });
} 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 (error: any) {
// This 'catch' block now only handles network errors or server crashes (500 errors).
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 {
this.loading = false;
}
},
calculateCaptureAmount() {
// Only calculate if we have both delivery order and pricing data
if (this.deliveryOrder.id && this.pricing.price_for_customer) {
const gallons = typeof this.gallonsDelivered === 'string' ? parseFloat(this.gallonsDelivered) : Number(this.gallonsDelivered) || 0;
const pricePerGallon = typeof this.deliveryOrder.customer_price === 'string' ? parseFloat(this.deliveryOrder.customer_price) : Number(this.deliveryOrder.customer_price) || 0;
let total = gallons * pricePerGallon;
// Add prime fee if applicable
if (this.deliveryOrder.prime == 1) {
const primeFee = typeof this.pricing.price_prime === 'string' ? parseFloat(this.pricing.price_prime) : Number(this.pricing.price_prime) || 0;
total += primeFee;
}
// Add same day fee if applicable
if (this.deliveryOrder.same_day === 1) {
const sameDayFee = typeof this.pricing.price_same_day === 'string' ? parseFloat(this.pricing.price_same_day) : Number(this.pricing.price_same_day) || 0;
total += sameDayFee;
}
this.captureAmount = total;
}
},
cancelCapture() {
this.$router.push({ name: 'finalizeTicket', params: { id: this.$route.params.id } });
},
},
})
</script>
<style scoped></style>