major claude changes

This commit is contained in:
2026-01-28 21:55:14 -05:00
parent f9d0e4c0fd
commit f9b5364c53
81 changed files with 11155 additions and 10086 deletions

View File

@@ -278,403 +278,409 @@
<Footer />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
<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'
export default defineComponent({
name: 'captureAuthorize',
const route = useRoute()
const router = useRouter()
components: {
Header,
SideBar,
Footer,
},
// 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)
data() {
return {
loading: false,
userCardfound: false,
gallonsDelivered: '',
captureAmount: 0,
preAuthAmount: 0,
transaction: null as any,
showPaymentModal: false,
modalStep: 0,
modalCapturedAmount: 0,
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,
emergency: 0,
promo_id: 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,
price_emergency: 0,
date: "",
},
promo_active: false,
promo: {
name_of_promotion: '',
description: '',
money_off_delivery: 0,
text_on_ticket: ''
},
total_amount: 0,
discount: 0,
total_amount_after_discount: 0,
}
},
mounted() {
this.getOilOrder(this.$route.params.id)
this.getOilPricing()
this.getTransaction()
},
methods: {
sumdelivery(delivery_id: any) {
let path = import.meta.env.VITE_BASE_URL + "/delivery/total/" + delivery_id;
axios({
method: "get",
url: path,
withCredentials: true,
})
.then((response: any) => {
if (response.data.ok) {
this.total_amount = parseFloat(response.data.total_amount) || 0;
this.discount = parseFloat(response.data.discount) || 0;
this.total_amount_after_discount = parseFloat(response.data.total_amount_after_discount) || 0;
// Set capture amount to the calculated total including fees and discount
this.captureAmount = this.calculateTotalAsNumber();
}
})
.catch(() => {
notify({
title: "Error",
text: "Could not get totals",
type: "error",
});
});
},
getPromo(promo_id: any) {
let path = import.meta.env.VITE_BASE_URL + "/promo/" + promo_id;
axios({
method: "get",
url: path,
withCredentials: true,
headers: authHeader(),
})
.then((response: any) => {
if (response.data) {
this.promo = response.data
this.promo_active = true
}
})
},
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);
this.sumdelivery(delivery_id);
if ([1, 2, 3].includes(this.deliveryOrder.payment_type)) {
this.getPaymentCard(this.deliveryOrder.payment_card_id);
}
if (this.deliveryOrder.promo_id != null) {
this.getPromo(this.deliveryOrder.promo_id);
this.promo_active = true;
}
} 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) => {
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");
this.$router.push({ name: 'customerProfile', params: { id: this.customer.id } });
} else {
notify({ title: "Error", text: "No pre-authorized transaction found", type: "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
this.modalCapturedAmount = this.captureAmount;
this.showPaymentModal = true;
setTimeout(() => { this.modalStep = 1 }, 2000);
setTimeout(() => { this.showPaymentModal = false; this.$router.push({ name: 'deliveryOrder', params: { id: this.$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 (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;
}
},
calculateSubtotal() {
const gallons = parseFloat(this.gallonsDelivered || '0') || 0;
const pricePerGallon = typeof this.deliveryOrder.customer_price === 'string' ? parseFloat(this.deliveryOrder.customer_price) : Number(this.deliveryOrder.customer_price) || 0;
return (gallons * pricePerGallon).toFixed(2);
},
calculateTotalAmount() {
if (this.total_amount_after_discount == null || this.total_amount_after_discount === undefined) {
return '0.00';
}
let totalNum = Number(this.total_amount_after_discount);
if (isNaN(totalNum)) {
return '0.00';
}
if (this.deliveryOrder && this.deliveryOrder.prime == 1 && this.pricing && this.pricing.price_prime) {
totalNum += Number(this.pricing.price_prime) || 0;
}
if (this.deliveryOrder && this.deliveryOrder.same_day == 1 && this.pricing && this.pricing.price_same_day) {
totalNum += Number(this.pricing.price_same_day) || 0;
}
if (this.deliveryOrder && this.deliveryOrder.emergency == 1 && this.pricing && this.pricing.price_emergency) {
totalNum += Number(this.pricing.price_emergency) || 0;
}
return totalNum.toFixed(2);
},
calculateTotalAsNumber() {
if (this.total_amount_after_discount == null || this.total_amount_after_discount === undefined) {
return 0;
}
let totalNum = Number(this.total_amount_after_discount);
if (isNaN(totalNum)) {
return 0;
}
if (this.deliveryOrder && this.deliveryOrder.prime == 1 && this.pricing && this.pricing.price_prime) {
totalNum += Number(this.pricing.price_prime) || 0;
}
if (this.deliveryOrder && this.deliveryOrder.same_day == 1 && this.pricing && this.pricing.price_same_day) {
totalNum += Number(this.pricing.price_same_day) || 0;
}
if (this.deliveryOrder && this.deliveryOrder.emergency == 1 && this.pricing && this.pricing.price_emergency) {
totalNum += Number(this.pricing.price_emergency) || 0;
}
return totalNum;
},
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 } });
},
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';
}
},
},
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>