major claude changes
This commit is contained in:
@@ -172,501 +172,503 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts">
|
||||
import { defineComponent, watch } from 'vue'
|
||||
import axios from 'axios'
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import axios, { AxiosResponse, AxiosError } from 'axios'
|
||||
import authHeader from '../../../services/auth.header'
|
||||
import { notify } from "@kyvg/vue3-notification"
|
||||
import type {
|
||||
DeliveryFormData,
|
||||
CustomerFormData,
|
||||
CreditCardFormData,
|
||||
PricingData,
|
||||
PromoData,
|
||||
DeliveryOrderResponse,
|
||||
DeliveryTotalResponse,
|
||||
OilPricingResponse,
|
||||
PromoResponse,
|
||||
WhoAmIResponse,
|
||||
UpdateStatusResponse
|
||||
} from '../../../types/models'
|
||||
|
||||
export default defineComponent({
|
||||
name: 'AuthorizePreauthCharge',
|
||||
// Router and route
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
data() {
|
||||
return {
|
||||
deliveryId: this.$route.params.id as string,
|
||||
loaded: false,
|
||||
chargeAmount: 0,
|
||||
loading: false,
|
||||
action: '', // 'preauthorize' or 'charge'
|
||||
error: '',
|
||||
success: '',
|
||||
isChargeConfirmationModalVisible: false,
|
||||
user: {
|
||||
user_id: 0,
|
||||
},
|
||||
delivery: {
|
||||
id: 0,
|
||||
customer_id: 0,
|
||||
customer_name: '',
|
||||
customer_address: '',
|
||||
customer_town: '',
|
||||
customer_state: 0,
|
||||
customer_zip: '',
|
||||
gallons_ordered: 0,
|
||||
customer_asked_for_fill: 0,
|
||||
gallons_delivered: 0,
|
||||
customer_filled: 0,
|
||||
delivery_status: 0,
|
||||
when_ordered: '',
|
||||
when_delivered: '',
|
||||
expected_delivery_date: '',
|
||||
automatic: 0,
|
||||
oil_id: 0,
|
||||
supplier_price: 0,
|
||||
customer_price: 0,
|
||||
customer_temperature: 0,
|
||||
dispatcher_notes: '',
|
||||
prime: 0,
|
||||
promo_id: 0,
|
||||
emergency: 0,
|
||||
same_day: 0,
|
||||
payment_type: 0,
|
||||
payment_card_id: 0,
|
||||
driver_employee_id: 0,
|
||||
driver_first_name: '',
|
||||
driver_last_name: '',
|
||||
pre_charge_amount: 0,
|
||||
total_price: 0,
|
||||
service_id: null,
|
||||
},
|
||||
credit_cards: [
|
||||
{
|
||||
id: 0,
|
||||
name_on_card: '',
|
||||
main_card: false,
|
||||
card_number: '',
|
||||
expiration_month: '',
|
||||
type_of_card: '',
|
||||
last_four_digits: '',
|
||||
expiration_year: '',
|
||||
security_number: '',
|
||||
|
||||
}
|
||||
],
|
||||
customer: {
|
||||
id: 0,
|
||||
user_id: 0,
|
||||
customer_first_name: '',
|
||||
customer_last_name: '',
|
||||
customer_town: '',
|
||||
customer_address: '',
|
||||
customer_state: 0,
|
||||
customer_zip: '',
|
||||
customer_apt: '',
|
||||
customer_home_type: 0,
|
||||
customer_phone_number: '',
|
||||
account_number: '',
|
||||
},
|
||||
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,
|
||||
}
|
||||
},
|
||||
|
||||
computed: {
|
||||
selectedCard(): any {
|
||||
return this.credit_cards.find((card: any) => card.id === this.delivery.payment_card_id)
|
||||
}
|
||||
},
|
||||
|
||||
mounted() {
|
||||
this.loadData(this.deliveryId)
|
||||
},
|
||||
|
||||
created() {
|
||||
this.watchRoute()
|
||||
},
|
||||
|
||||
methods: {
|
||||
watchRoute() {
|
||||
watch(
|
||||
() => this.$route.params.id,
|
||||
(newId) => {
|
||||
if (newId !== this.deliveryId) {
|
||||
this.resetState()
|
||||
this.deliveryId = newId as string
|
||||
this.loadData(newId as string)
|
||||
}
|
||||
}
|
||||
)
|
||||
},
|
||||
|
||||
resetState() {
|
||||
this.loading = false
|
||||
this.action = ''
|
||||
this.error = ''
|
||||
this.success = ''
|
||||
this.chargeAmount = 0
|
||||
this.promo_active = false
|
||||
this.total_amount = 0
|
||||
this.discount = 0
|
||||
this.total_amount_after_discount = 0
|
||||
this.deliveryId = this.$route.params.id as string
|
||||
},
|
||||
|
||||
loadData(deliveryId: string) {
|
||||
this.userStatus()
|
||||
this.getOilOrder(deliveryId)
|
||||
this.sumdelivery(deliveryId)
|
||||
this.getOilPricing()
|
||||
this.updatestatus()
|
||||
},
|
||||
|
||||
updatestatus() {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/delivery/updatestatus';
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
headers: authHeader(),
|
||||
}).then((response: any) => {
|
||||
if (response.data.update)
|
||||
console.log("Updated Status of Deliveries")
|
||||
})
|
||||
},
|
||||
|
||||
updateChargeAmount() {
|
||||
// Only update if we have all necessary data
|
||||
if (this.total_amount_after_discount > 0 &&
|
||||
this.pricing.price_prime !== undefined &&
|
||||
this.pricing.price_same_day !== undefined &&
|
||||
this.pricing.price_emergency !== undefined) {
|
||||
this.chargeAmount = this.calculateTotalAsNumber();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
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;
|
||||
|
||||
// Try to update charge amount with complete pricing
|
||||
const updated = this.updateChargeAmount();
|
||||
|
||||
// Fallback only if pricing not loaded yet and calculation didn't run
|
||||
if (!updated) {
|
||||
if (this.promo_active) {
|
||||
this.chargeAmount = this.total_amount_after_discount;
|
||||
} else {
|
||||
this.chargeAmount = this.total_amount;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get oil pricing",
|
||||
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
|
||||
|
||||
// Trigger a charge amount update if all data is available
|
||||
this.updateChargeAmount();
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
userStatus() {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
withCredentials: true,
|
||||
headers: authHeader(),
|
||||
})
|
||||
.then((response: any) => {
|
||||
if (response.data.ok) {
|
||||
this.user = response.data.user;
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
getOilPricing() {
|
||||
let path = import.meta.env.VITE_BASE_URL + "/info/price/oil/table";
|
||||
axios({
|
||||
method: "get",
|
||||
url: path,
|
||||
withCredentials: true,
|
||||
})
|
||||
.then((response: any) => {
|
||||
this.pricing = response.data;
|
||||
// Try to update charge amount when pricing is loaded
|
||||
this.updateChargeAmount();
|
||||
})
|
||||
.catch(() => {
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get oil pricing",
|
||||
type: "error",
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
getOilOrder(delivery_id: any) {
|
||||
let path = import.meta.env.VITE_BASE_URL + "/delivery/order/" + delivery_id;
|
||||
axios({
|
||||
method: "get",
|
||||
url: path,
|
||||
withCredentials: true,
|
||||
})
|
||||
.then((response: any) => {
|
||||
if (response.data && response.data.ok) {
|
||||
this.delivery = response.data.delivery;
|
||||
this.getCustomer(this.delivery.customer_id)
|
||||
this.getCreditCards(this.delivery.customer_id)
|
||||
if (this.delivery.promo_id != null) {
|
||||
this.getPromo(this.delivery.promo_id);
|
||||
this.promo_active = true;
|
||||
}
|
||||
} else {
|
||||
console.error("API Error:", response.data.error || "Failed to fetch delivery data.");
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
console.error("API Error in getOilOrder:", error);
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get delivery",
|
||||
type: "error",
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
getCreditCards(user_id: any) {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/payment/cards/' + user_id;
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
headers: authHeader(),
|
||||
}).then((response: any) => {
|
||||
this.credit_cards = response.data
|
||||
})
|
||||
},
|
||||
|
||||
getCustomer(userid: any) {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/customer/' + userid;
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
headers: authHeader(),
|
||||
}).then((response: any) => {
|
||||
this.customer = response.data
|
||||
})
|
||||
},
|
||||
|
||||
calculateSubtotal() {
|
||||
const gallons = this.delivery.gallons_ordered || 0
|
||||
const pricePerGallon = this.delivery.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.delivery && this.delivery.prime == 1 && this.pricing && this.pricing.price_prime) {
|
||||
totalNum += Number(this.pricing.price_prime) || 0;
|
||||
}
|
||||
if (this.delivery && this.delivery.same_day == 1 && this.pricing && this.pricing.price_same_day) {
|
||||
totalNum += Number(this.pricing.price_same_day) || 0;
|
||||
}
|
||||
if (this.delivery && this.delivery.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.delivery && this.delivery.prime == 1 && this.pricing && this.pricing.price_prime) {
|
||||
totalNum += Number(this.pricing.price_prime) || 0;
|
||||
}
|
||||
if (this.delivery && this.delivery.same_day == 1 && this.pricing && this.pricing.price_same_day) {
|
||||
totalNum += Number(this.pricing.price_same_day) || 0;
|
||||
}
|
||||
if (this.delivery && this.delivery.emergency == 1 && this.pricing && this.pricing.price_emergency) {
|
||||
totalNum += Number(this.pricing.price_emergency) || 0;
|
||||
}
|
||||
|
||||
return totalNum;
|
||||
},
|
||||
|
||||
async handlePreauthorize() {
|
||||
await this.processPayment('preauthorize')
|
||||
},
|
||||
|
||||
async handleChargeNow() {
|
||||
if (!this.selectedCard) {
|
||||
this.error = 'No credit card found for this customer'
|
||||
return
|
||||
}
|
||||
if (!this.chargeAmount || this.chargeAmount <= 0) {
|
||||
this.error = 'Please enter a valid charge amount'
|
||||
return
|
||||
}
|
||||
this.isChargeConfirmationModalVisible = true
|
||||
},
|
||||
|
||||
async proceedWithCharge() {
|
||||
this.isChargeConfirmationModalVisible = false
|
||||
await this.processPayment('charge')
|
||||
},
|
||||
|
||||
cancelCharge() {
|
||||
this.isChargeConfirmationModalVisible = false
|
||||
},
|
||||
|
||||
async processPayment(actionType: string) {
|
||||
if (!this.selectedCard) {
|
||||
this.error = 'No credit card found for this customer'
|
||||
return
|
||||
}
|
||||
|
||||
this.loading = true
|
||||
this.action = actionType
|
||||
this.error = ''
|
||||
this.success = ''
|
||||
|
||||
try {
|
||||
// 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.");
|
||||
}
|
||||
|
||||
const authPayload = {
|
||||
card_id: (this.selectedCard as any).id,
|
||||
preauthorize_amount: this.chargeAmount.toFixed(2),
|
||||
delivery_id: this.delivery.id,
|
||||
};
|
||||
|
||||
const authPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/authorize/saved-card/${this.customer.id}`;
|
||||
|
||||
const response = await axios.post(authPath, authPayload, { withCredentials: true, headers: authHeader() });
|
||||
|
||||
// Update payment type to 11 after successful preauthorization
|
||||
try {
|
||||
await axios.put(`${import.meta.env.VITE_BASE_URL}/payment/authorize/${this.delivery.id}`, {}, { headers: authHeader() });
|
||||
} catch (updateError) {
|
||||
console.error('Failed to update payment type after preauthorization:', updateError);
|
||||
}
|
||||
|
||||
// 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 { // 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/payments/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() });
|
||||
|
||||
// Update payment type to 11 after successful charge
|
||||
try {
|
||||
await axios.put(`${import.meta.env.VITE_BASE_URL}/payment/authorize/${this.delivery.id}`, {}, { headers: authHeader() });
|
||||
} catch (updateError) {
|
||||
console.error('Failed to update payment type after charge:', updateError);
|
||||
}
|
||||
|
||||
// Status codes: 0 = APPROVED, 1 = DECLINED (based on backend TransactionStatus enum)
|
||||
if (response.data && response.data.status === 0) { // 0 = APPROVED
|
||||
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) {
|
||||
console.log(error)
|
||||
this.error = error.response?.data?.detail || `Failed to ${actionType} payment`
|
||||
notify({
|
||||
title: "Error",
|
||||
text: this.error,
|
||||
type: "error",
|
||||
})
|
||||
} finally {
|
||||
this.loading = false
|
||||
this.action = ''
|
||||
}
|
||||
}
|
||||
},
|
||||
// Reactive data
|
||||
const deliveryId = ref(route.params.id as string)
|
||||
const loaded = ref(false)
|
||||
const chargeAmount = ref(0)
|
||||
const loading = ref(false)
|
||||
const action = ref('') // 'preauthorize' or 'charge'
|
||||
const error = ref('')
|
||||
const success = ref('')
|
||||
const isChargeConfirmationModalVisible = ref(false)
|
||||
const user = ref({
|
||||
user_id: 0,
|
||||
})
|
||||
const delivery = ref<DeliveryFormData>({
|
||||
id: 0,
|
||||
customer_id: 0,
|
||||
customer_name: '',
|
||||
customer_address: '',
|
||||
customer_town: '',
|
||||
customer_state: 0,
|
||||
customer_zip: '',
|
||||
gallons_ordered: 0,
|
||||
customer_asked_for_fill: 0,
|
||||
gallons_delivered: 0,
|
||||
customer_filled: 0,
|
||||
delivery_status: 0,
|
||||
when_ordered: '',
|
||||
when_delivered: '',
|
||||
expected_delivery_date: '',
|
||||
automatic: 0,
|
||||
oil_id: 0,
|
||||
supplier_price: 0,
|
||||
customer_price: 0,
|
||||
customer_temperature: 0,
|
||||
dispatcher_notes: '',
|
||||
prime: 0,
|
||||
promo_id: 0,
|
||||
emergency: 0,
|
||||
same_day: 0,
|
||||
payment_type: 0,
|
||||
payment_card_id: 0,
|
||||
driver_employee_id: 0,
|
||||
driver_first_name: '',
|
||||
driver_last_name: '',
|
||||
pre_charge_amount: 0,
|
||||
total_price: 0,
|
||||
service_id: null,
|
||||
})
|
||||
const credit_cards = ref<CreditCardFormData[]>([
|
||||
{
|
||||
id: 0,
|
||||
name_on_card: '',
|
||||
main_card: false,
|
||||
card_number: '',
|
||||
expiration_month: '',
|
||||
type_of_card: '',
|
||||
last_four_digits: '',
|
||||
expiration_year: '',
|
||||
security_number: '',
|
||||
}
|
||||
])
|
||||
const customer = ref<CustomerFormData>({
|
||||
id: 0,
|
||||
user_id: 0,
|
||||
customer_first_name: '',
|
||||
customer_last_name: '',
|
||||
customer_town: '',
|
||||
customer_address: '',
|
||||
customer_state: 0,
|
||||
customer_zip: '',
|
||||
customer_apt: '',
|
||||
customer_home_type: 0,
|
||||
customer_phone_number: '',
|
||||
account_number: '',
|
||||
})
|
||||
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)
|
||||
|
||||
// Computed properties
|
||||
const selectedCard = computed(() => {
|
||||
return credit_cards.value.find((card) => card.id === delivery.value.payment_card_id)
|
||||
})
|
||||
|
||||
// Lifecycle
|
||||
onMounted(() => {
|
||||
loadData(deliveryId.value)
|
||||
})
|
||||
|
||||
// Watchers
|
||||
watch(() => route.params.id, (newId) => {
|
||||
if (newId !== deliveryId.value) {
|
||||
resetState()
|
||||
deliveryId.value = newId as string
|
||||
loadData(newId as string)
|
||||
}
|
||||
})
|
||||
|
||||
// Functions
|
||||
const resetState = () => {
|
||||
loading.value = false
|
||||
action.value = ''
|
||||
error.value = ''
|
||||
success.value = ''
|
||||
chargeAmount.value = 0
|
||||
promo_active.value = false
|
||||
total_amount.value = 0
|
||||
discount.value = 0
|
||||
total_amount_after_discount.value = 0
|
||||
deliveryId.value = route.params.id as string
|
||||
}
|
||||
|
||||
const loadData = (deliveryId: string) => {
|
||||
userStatus()
|
||||
getOilOrder(deliveryId)
|
||||
sumdelivery(deliveryId)
|
||||
getOilPricing()
|
||||
updatestatus()
|
||||
}
|
||||
|
||||
const updatestatus = () => {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/delivery/updatestatus';
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
headers: authHeader(),
|
||||
}).then((response: AxiosResponse<UpdateStatusResponse>) => {
|
||||
if (response.data.update)
|
||||
console.log("Updated Status of Deliveries")
|
||||
})
|
||||
}
|
||||
|
||||
const updateChargeAmount = () => {
|
||||
// Only update if we have all necessary data
|
||||
if (total_amount_after_discount.value > 0 &&
|
||||
pricing.value.price_prime !== undefined &&
|
||||
pricing.value.price_same_day !== undefined &&
|
||||
pricing.value.price_emergency !== undefined) {
|
||||
chargeAmount.value = calculateTotalAsNumber();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
// Try to update charge amount with complete pricing
|
||||
const updated = updateChargeAmount();
|
||||
|
||||
// Fallback only if pricing not loaded yet and calculation didn't run
|
||||
if (!updated) {
|
||||
if (promo_active.value) {
|
||||
chargeAmount.value = total_amount_after_discount.value;
|
||||
} else {
|
||||
chargeAmount.value = total_amount.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get oil pricing",
|
||||
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
|
||||
|
||||
// Trigger a charge amount update if all data is available
|
||||
updateChargeAmount();
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const userStatus = () => {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
withCredentials: true,
|
||||
headers: authHeader(),
|
||||
})
|
||||
.then((response: AxiosResponse<WhoAmIResponse>) => {
|
||||
if (response.data.ok) {
|
||||
user.value = response.data.user;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const getOilPricing = () => {
|
||||
let path = import.meta.env.VITE_BASE_URL + "/info/price/oil/table";
|
||||
axios({
|
||||
method: "get",
|
||||
url: path,
|
||||
withCredentials: true,
|
||||
})
|
||||
.then((response: AxiosResponse<OilPricingResponse>) => {
|
||||
pricing.value = response.data;
|
||||
// Try to update charge amount when pricing is loaded
|
||||
updateChargeAmount();
|
||||
})
|
||||
.catch(() => {
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get oil pricing",
|
||||
type: "error",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const getOilOrder = (delivery_id: number | string) => {
|
||||
let path = import.meta.env.VITE_BASE_URL + "/delivery/order/" + delivery_id;
|
||||
axios({
|
||||
method: "get",
|
||||
url: path,
|
||||
withCredentials: true,
|
||||
})
|
||||
.then((response: AxiosResponse<DeliveryOrderResponse>) => {
|
||||
if (response.data && response.data.ok) {
|
||||
delivery.value = response.data.delivery as DeliveryFormData;
|
||||
getCustomer(delivery.value.customer_id)
|
||||
getCreditCards(delivery.value.customer_id)
|
||||
if (delivery.value.promo_id != null) {
|
||||
getPromo(delivery.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("API Error in getOilOrder:", error);
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get delivery",
|
||||
type: "error",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const getCreditCards = (user_id: number) => {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/payment/cards/' + user_id;
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
headers: authHeader(),
|
||||
}).then((response: AxiosResponse<CreditCardFormData[]>) => {
|
||||
credit_cards.value = response.data
|
||||
})
|
||||
}
|
||||
|
||||
const getCustomer = (userid: number) => {
|
||||
let path = import.meta.env.VITE_BASE_URL + '/customer/' + userid;
|
||||
axios({
|
||||
method: 'get',
|
||||
url: path,
|
||||
headers: authHeader(),
|
||||
}).then((response: AxiosResponse<CustomerFormData>) => {
|
||||
customer.value = response.data
|
||||
})
|
||||
}
|
||||
|
||||
const calculateSubtotal = () => {
|
||||
const gallons = delivery.value.gallons_ordered || 0
|
||||
const pricePerGallon = delivery.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 (delivery.value && delivery.value.prime == 1 && pricing.value && pricing.value.price_prime) {
|
||||
totalNum += Number(pricing.value.price_prime) || 0;
|
||||
}
|
||||
if (delivery.value && delivery.value.same_day == 1 && pricing.value && pricing.value.price_same_day) {
|
||||
totalNum += Number(pricing.value.price_same_day) || 0;
|
||||
}
|
||||
if (delivery.value && delivery.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 (delivery.value && delivery.value.prime == 1 && pricing.value && pricing.value.price_prime) {
|
||||
totalNum += Number(pricing.value.price_prime) || 0;
|
||||
}
|
||||
if (delivery.value && delivery.value.same_day == 1 && pricing.value && pricing.value.price_same_day) {
|
||||
totalNum += Number(pricing.value.price_same_day) || 0;
|
||||
}
|
||||
if (delivery.value && delivery.value.emergency == 1 && pricing.value && pricing.value.price_emergency) {
|
||||
totalNum += Number(pricing.value.price_emergency) || 0;
|
||||
}
|
||||
|
||||
return totalNum;
|
||||
}
|
||||
|
||||
const handlePreauthorize = async () => {
|
||||
await processPayment('preauthorize')
|
||||
}
|
||||
|
||||
const handleChargeNow = async () => {
|
||||
if (!selectedCard.value) {
|
||||
error.value = 'No credit card found for this customer'
|
||||
return
|
||||
}
|
||||
if (!chargeAmount.value || chargeAmount.value <= 0) {
|
||||
error.value = 'Please enter a valid charge amount'
|
||||
return
|
||||
}
|
||||
isChargeConfirmationModalVisible.value = true
|
||||
}
|
||||
|
||||
const proceedWithCharge = async () => {
|
||||
isChargeConfirmationModalVisible.value = false
|
||||
await processPayment('charge')
|
||||
}
|
||||
|
||||
const cancelCharge = () => {
|
||||
isChargeConfirmationModalVisible.value = false
|
||||
}
|
||||
|
||||
const processPayment = async (actionType: string) => {
|
||||
if (!selectedCard.value) {
|
||||
error.value = 'No credit card found for this customer'
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
action.value = actionType
|
||||
error.value = ''
|
||||
success.value = ''
|
||||
|
||||
try {
|
||||
// Step 2: If payment method is credit, perform the pre-authorization
|
||||
if (actionType === 'preauthorize') {
|
||||
if (!chargeAmount.value || chargeAmount.value <= 0) {
|
||||
throw new Error("Pre-authorization amount must be greater than zero.");
|
||||
}
|
||||
|
||||
const authPayload = {
|
||||
card_id: selectedCard.value!.id,
|
||||
preauthorize_amount: chargeAmount.value.toFixed(2),
|
||||
delivery_id: delivery.value.id,
|
||||
};
|
||||
|
||||
const authPath = `${import.meta.env.VITE_AUTHORIZE_URL}/api/payments/authorize/saved-card/${customer.value.id}`;
|
||||
|
||||
const response = await axios.post(authPath, authPayload, { withCredentials: true, headers: authHeader() });
|
||||
|
||||
// Update payment type to 11 after successful preauthorization
|
||||
try {
|
||||
await axios.put(`${import.meta.env.VITE_BASE_URL}/payment/authorize/${delivery.value.id}`, {}, { headers: authHeader() });
|
||||
} catch (updateError) {
|
||||
console.error('Failed to update payment type after preauthorization:', updateError);
|
||||
}
|
||||
|
||||
// On successful authorization, show success and redirect
|
||||
success.value = `Preauthorization successful! Transaction ID: ${response.data?.auth_net_transaction_id || 'N/A'}`;
|
||||
setTimeout(() => {
|
||||
router.push({ name: "customerProfile", params: { id: customer.value.id } });
|
||||
}, 2000);
|
||||
} else { // Handle 'charge' action
|
||||
if (!chargeAmount.value || chargeAmount.value <= 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: selectedCard.value!.id,
|
||||
charge_amount: chargeAmount.value.toFixed(2),
|
||||
delivery_id: delivery.value.id,
|
||||
service_id: delivery.value.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/payments/charge/saved-card/${customer.value.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() });
|
||||
|
||||
// Update payment type to 11 after successful charge
|
||||
try {
|
||||
await axios.put(`${import.meta.env.VITE_BASE_URL}/payment/authorize/${delivery.value.id}`, {}, { headers: authHeader() });
|
||||
} catch (updateError) {
|
||||
console.error('Failed to update payment type after charge:', updateError);
|
||||
}
|
||||
|
||||
// Status codes: 0 = APPROVED, 1 = DECLINED (based on backend TransactionStatus enum)
|
||||
if (response.data && response.data.status === 0) { // 0 = APPROVED
|
||||
success.value = `Charge successful! Transaction ID: ${response.data.auth_net_transaction_id || 'N/A'}`;
|
||||
setTimeout(() => {
|
||||
router.push({ name: "customerProfile", params: { id: customer.value.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 (err: unknown) {
|
||||
const axiosErr = err as AxiosError<{ detail?: string }>;
|
||||
console.log(err)
|
||||
error.value = axiosErr.response?.data?.detail || `Failed to ${actionType} payment`
|
||||
notify({
|
||||
title: "Error",
|
||||
text: error.value,
|
||||
type: "error",
|
||||
})
|
||||
} finally {
|
||||
loading.value = false
|
||||
action.value = ''
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped></style>
|
||||
|
||||
@@ -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>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user