major claude changes
This commit is contained in:
@@ -252,8 +252,9 @@
|
||||
</div>
|
||||
<Footer />
|
||||
</template>
|
||||
<script lang="ts">
|
||||
import { defineComponent } from 'vue'
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import axios from 'axios'
|
||||
import authHeader from '../../../services/auth.header'
|
||||
import Header from '../../../layouts/headers/headerauth.vue'
|
||||
@@ -272,389 +273,395 @@ interface UserCard {
|
||||
security_number: string;
|
||||
}
|
||||
|
||||
// Route and router
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
export default defineComponent({
|
||||
name: 'finalizeTicket',
|
||||
components: { Header, SideBar, Footer },
|
||||
data() {
|
||||
return {
|
||||
isLoading: false,
|
||||
user: { id: 0 },
|
||||
userCardfound: false,
|
||||
preChargeTotal: 0,
|
||||
FinalizeOilOrderForm: {
|
||||
cash_recieved: '',
|
||||
fill_location: '',
|
||||
check_number: '',
|
||||
gallons_delivered: '',
|
||||
},
|
||||
userCard: {} as UserCard,
|
||||
customer: {
|
||||
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: '',
|
||||
},
|
||||
customerDescription: { fill_location: '' },
|
||||
deliveryOrder: {
|
||||
id: '',
|
||||
customer_id: 0,
|
||||
gallons_ordered: 0,
|
||||
customer_asked_for_fill: 0,
|
||||
gallons_delivered: '',
|
||||
delivery_status: 0,
|
||||
when_ordered: '',
|
||||
when_delivered: '',
|
||||
expected_delivery_date: '',
|
||||
customer_price: '',
|
||||
prime: 0,
|
||||
same_day: 0,
|
||||
payment_type: 0,
|
||||
payment_card_id: '',
|
||||
promo_id: null,
|
||||
},
|
||||
pricing: {
|
||||
price_prime: 0,
|
||||
price_same_day: 0,
|
||||
},
|
||||
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,
|
||||
transaction: null as any,
|
||||
// Reactive data
|
||||
const isLoading = ref(false)
|
||||
const user = ref({ id: 0 })
|
||||
const userCardfound = ref(false)
|
||||
const preChargeTotal = ref(0)
|
||||
const FinalizeOilOrderForm = ref({
|
||||
cash_recieved: '',
|
||||
fill_location: '',
|
||||
check_number: '',
|
||||
gallons_delivered: '',
|
||||
})
|
||||
const userCard = ref({} as UserCard)
|
||||
const customer = ref({
|
||||
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: '',
|
||||
})
|
||||
const customerDescription = ref({ fill_location: '' })
|
||||
const deliveryOrder = ref({
|
||||
id: '',
|
||||
customer_id: 0,
|
||||
gallons_ordered: 0,
|
||||
customer_asked_for_fill: 0,
|
||||
gallons_delivered: '',
|
||||
delivery_status: 0,
|
||||
when_ordered: '',
|
||||
when_delivered: '',
|
||||
expected_delivery_date: '',
|
||||
customer_price: '',
|
||||
prime: 0,
|
||||
same_day: 0,
|
||||
payment_type: 0,
|
||||
payment_card_id: '',
|
||||
promo_id: null,
|
||||
})
|
||||
const pricing = ref({
|
||||
price_prime: 0,
|
||||
price_same_day: 0,
|
||||
})
|
||||
const promo_active = ref(false)
|
||||
const promo = ref({
|
||||
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)
|
||||
const transaction = ref(null as any)
|
||||
|
||||
// Computed properties
|
||||
const finalChargeAmount = computed((): number => {
|
||||
// If promo is active, use server-calculated totals with fees added
|
||||
if (promo_active.value && total_amount_after_discount.value > 0) {
|
||||
let total = total_amount_after_discount.value;
|
||||
if (deliveryOrder.value.prime === 1) total += Number(pricing.value.price_prime);
|
||||
if (deliveryOrder.value.same_day === 1) total += Number(pricing.value.price_same_day);
|
||||
return total;
|
||||
}
|
||||
|
||||
// Otherwise, calculate locally
|
||||
const gallons = Number(FinalizeOilOrderForm.value.gallons_delivered);
|
||||
const pricePerGallon = Number(deliveryOrder.value.customer_price);
|
||||
if (isNaN(gallons) || isNaN(pricePerGallon) || gallons <= 0) {
|
||||
return 0;
|
||||
}
|
||||
let total = gallons * pricePerGallon;
|
||||
if (deliveryOrder.value.prime === 1) total += Number(pricing.value.price_prime);
|
||||
if (deliveryOrder.value.same_day === 1) total += Number(pricing.value.price_same_day);
|
||||
return total;
|
||||
})
|
||||
|
||||
// Lifecycle
|
||||
onMounted(() => {
|
||||
const deliveryId = route.params.id;
|
||||
// --- DEBUGGING STEP 1 ---
|
||||
console.log(`[DEBUG] Component Mounted. Fetching data for delivery ID: ${deliveryId}`);
|
||||
getOilOrder(deliveryId);
|
||||
getOilPricing();
|
||||
})
|
||||
|
||||
// Functions
|
||||
const getOilOrder = async (delivery_id: any) => {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/delivery/order/${delivery_id}`;
|
||||
// --- DEBUGGING STEP 2 ---
|
||||
console.log(`[DEBUG] Calling getOilOrder API at: ${path}`);
|
||||
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
|
||||
// --- DEBUGGING STEP 3 ---
|
||||
console.log('[DEBUG] Received RAW response from getOilOrder:', response.data);
|
||||
|
||||
if (response.data && response.data.ok) {
|
||||
console.log('[DEBUG] Response is OK. Processing data...');
|
||||
deliveryOrder.value = response.data.delivery;
|
||||
|
||||
// --- DEBUGGING STEP 4 ---
|
||||
console.log(`[DEBUG] Value of response.data.total_amount is:`, response.data.total_amount);
|
||||
|
||||
total_amount.value = response.data.delivery.total_amount || 0;
|
||||
preChargeTotal.value = response.data.delivery.total_amount || 0;
|
||||
|
||||
|
||||
await getCustomer(deliveryOrder.value.customer_id);
|
||||
|
||||
if ([1, 2, 11].includes(deliveryOrder.value.payment_type) && deliveryOrder.value.payment_card_id) {
|
||||
getPaymentCard(deliveryOrder.value.payment_card_id);
|
||||
}
|
||||
|
||||
if (deliveryOrder.value.promo_id != null) {
|
||||
getPromo(deliveryOrder.value.promo_id);
|
||||
}
|
||||
|
||||
// Fetch calculated totals including discounts
|
||||
sumdelivery(delivery_id);
|
||||
|
||||
// Call transaction fetch after customer is loaded
|
||||
setTimeout(() => getTransaction(delivery_id), 500);
|
||||
} else {
|
||||
console.error('[DEBUG] getOilOrder response was not OK or data is missing.');
|
||||
notify({ title: "Data Error", text: "Could not retrieve complete delivery details.", type: "error" });
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
finalChargeAmount(): number {
|
||||
// If promo is active, use server-calculated totals with fees added
|
||||
if (this.promo_active && this.total_amount_after_discount > 0) {
|
||||
let total = this.total_amount_after_discount;
|
||||
if (this.deliveryOrder.prime === 1) total += Number(this.pricing.price_prime);
|
||||
if (this.deliveryOrder.same_day === 1) total += Number(this.pricing.price_same_day);
|
||||
return total;
|
||||
} catch (error) {
|
||||
// --- DEBUGGING STEP 5 ---
|
||||
console.error("[DEBUG] The getOilOrder API call FAILED. Error object:", error);
|
||||
notify({ title: "Network Error", text: "Could not fetch delivery order.", type: "error" });
|
||||
}
|
||||
}
|
||||
|
||||
const getPaymentCard = async (card_id: any) => {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/payment/card/${card_id}`;
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
|
||||
userCard.value = response.data;
|
||||
userCardfound.value = true;
|
||||
} catch (error) {
|
||||
userCardfound.value = false;
|
||||
console.error(`[DEBUG] Error fetching payment card ${card_id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const getCustomer = async (user_id: any) => {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true });
|
||||
customer.value = response.data;
|
||||
await getCustomerDescription(deliveryOrder.value.customer_id);
|
||||
} catch (error) { console.error("[DEBUG] Error fetching customer:", error); }
|
||||
}
|
||||
|
||||
const getCustomerDescription = async (user_id: any) => {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/customer/description/${user_id}`;
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true });
|
||||
customerDescription.value = response.data;
|
||||
FinalizeOilOrderForm.value.fill_location = customerDescription.value.fill_location;
|
||||
} catch (error) { console.error("[DEBUG] Error fetching customer description:", error); }
|
||||
}
|
||||
|
||||
const getOilPricing = () => {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/info/price/oil/table`;
|
||||
axios.get(path, { withCredentials: true })
|
||||
.then((response: any) => { pricing.value = response.data; })
|
||||
.catch((error: any) => { console.error("[DEBUG] Error fetching oil pricing:", error); });
|
||||
}
|
||||
|
||||
const 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) {
|
||||
promo.value = response.data
|
||||
promo_active.value = true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Otherwise, calculate locally
|
||||
const gallons = Number(this.FinalizeOilOrderForm.gallons_delivered);
|
||||
const pricePerGallon = Number(this.deliveryOrder.customer_price);
|
||||
if (isNaN(gallons) || isNaN(pricePerGallon) || gallons <= 0) {
|
||||
return 0;
|
||||
const 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) {
|
||||
total_amount.value = parseFloat(response.data.total_amount) || 0;
|
||||
discount.value = parseFloat(response.data.discount) || 0;
|
||||
total_amount_after_discount.value = parseFloat(response.data.total_amount_after_discount) || 0;
|
||||
}
|
||||
let total = gallons * pricePerGallon;
|
||||
if (this.deliveryOrder.prime === 1) total += Number(this.pricing.price_prime);
|
||||
if (this.deliveryOrder.same_day === 1) total += Number(this.pricing.price_same_day);
|
||||
return total;
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
const deliveryId = this.$route.params.id;
|
||||
// --- DEBUGGING STEP 1 ---
|
||||
console.log(`[DEBUG] Component Mounted. Fetching data for delivery ID: ${deliveryId}`);
|
||||
this.getOilOrder(deliveryId);
|
||||
this.getOilPricing();
|
||||
},
|
||||
methods: {
|
||||
async getOilOrder(delivery_id: any) {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/delivery/order/${delivery_id}`;
|
||||
// --- DEBUGGING STEP 2 ---
|
||||
console.log(`[DEBUG] Calling getOilOrder API at: ${path}`);
|
||||
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
|
||||
// --- DEBUGGING STEP 3 ---
|
||||
console.log('[DEBUG] Received RAW response from getOilOrder:', response.data);
|
||||
|
||||
if (response.data && response.data.ok) {
|
||||
console.log('[DEBUG] Response is OK. Processing data...');
|
||||
this.deliveryOrder = response.data.delivery;
|
||||
|
||||
// --- DEBUGGING STEP 4 ---
|
||||
console.log(`[DEBUG] Value of response.data.total_amount is:`, response.data.total_amount);
|
||||
|
||||
this.total_amount = response.data.delivery.total_amount || 0;
|
||||
this.preChargeTotal = response.data.delivery.total_amount || 0;
|
||||
|
||||
|
||||
await this.getCustomer(this.deliveryOrder.customer_id);
|
||||
|
||||
if ([1, 2, 11].includes(this.deliveryOrder.payment_type) && this.deliveryOrder.payment_card_id) {
|
||||
this.getPaymentCard(this.deliveryOrder.payment_card_id);
|
||||
}
|
||||
|
||||
if (this.deliveryOrder.promo_id != null) {
|
||||
this.getPromo(this.deliveryOrder.promo_id);
|
||||
}
|
||||
|
||||
// Fetch calculated totals including discounts
|
||||
this.sumdelivery(delivery_id);
|
||||
|
||||
// Call transaction fetch after customer is loaded
|
||||
setTimeout(() => this.getTransaction(delivery_id), 500);
|
||||
} else {
|
||||
console.error('[DEBUG] getOilOrder response was not OK or data is missing.');
|
||||
notify({ title: "Data Error", text: "Could not retrieve complete delivery details.", type: "error" });
|
||||
}
|
||||
} catch (error) {
|
||||
// --- DEBUGGING STEP 5 ---
|
||||
console.error("[DEBUG] The getOilOrder API call FAILED. Error object:", error);
|
||||
notify({ title: "Network Error", text: "Could not fetch delivery order.", type: "error" });
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
async getPaymentCard(card_id: any) {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/payment/card/${card_id}`;
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true, headers: authHeader() });
|
||||
this.userCard = response.data;
|
||||
this.userCardfound = true;
|
||||
} catch (error) {
|
||||
this.userCardfound = false;
|
||||
console.error(`[DEBUG] Error fetching payment card ${card_id}:`, error);
|
||||
}
|
||||
},
|
||||
async getCustomer(user_id: any) {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/customer/${user_id}`;
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true });
|
||||
this.customer = response.data;
|
||||
await this.getCustomerDescription(this.deliveryOrder.customer_id);
|
||||
} catch (error) { console.error("[DEBUG] Error fetching customer:", error); }
|
||||
},
|
||||
async getCustomerDescription(user_id: any) {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/customer/description/${user_id}`;
|
||||
try {
|
||||
const response = await axios.get(path, { withCredentials: true });
|
||||
this.customerDescription = response.data;
|
||||
this.FinalizeOilOrderForm.fill_location = this.customerDescription.fill_location;
|
||||
} catch (error) { console.error("[DEBUG] Error fetching customer description:", error); }
|
||||
},
|
||||
getOilPricing() {
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/info/price/oil/table`;
|
||||
axios.get(path, { withCredentials: true })
|
||||
.then((response: any) => { this.pricing = response.data; })
|
||||
.catch((error: any) => { console.error("[DEBUG] Error fetching oil pricing:", 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
|
||||
}
|
||||
})
|
||||
},
|
||||
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;
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get oil pricing",
|
||||
type: "error",
|
||||
});
|
||||
});
|
||||
},
|
||||
getTransaction(delivery_id: any) {
|
||||
// Add guard to prevent undefined customer ID API calls
|
||||
if (!delivery_id || !this.customer || !this.customer.id) {
|
||||
console.log("Skipping transaction fetch - delivery or customer data not available");
|
||||
return;
|
||||
}
|
||||
|
||||
// Consistent with delivery/view.vue - use customer transaction endpoint
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/payment/transactions/customer/${this.customer.id}/1`;
|
||||
axios.get(path, { withCredentials: true, headers: authHeader() })
|
||||
.then((response: any) => {
|
||||
console.log("Transaction API response:", response.data);
|
||||
// Handle both single transaction object and array responses
|
||||
if (response.data && Array.isArray(response.data) && response.data.length > 0) {
|
||||
// Find the transaction for this specific delivery
|
||||
const deliveryTransaction = response.data.find((txn: any) =>
|
||||
txn.delivery_id === parseInt(delivery_id) ||
|
||||
txn.transaction_id === delivery_id ||
|
||||
txn.delivery_number === delivery_id
|
||||
);
|
||||
this.transaction = deliveryTransaction || null;
|
||||
} else if (response.data && !Array.isArray(response.data)) {
|
||||
// If single transaction, check if it's for this delivery
|
||||
const txn = response.data;
|
||||
if (txn.delivery_id === parseInt(delivery_id) ||
|
||||
txn.transaction_id === delivery_id ||
|
||||
txn.delivery_number === delivery_id) {
|
||||
this.transaction = txn;
|
||||
} else {
|
||||
this.transaction = null;
|
||||
}
|
||||
} else {
|
||||
this.transaction = null;
|
||||
}
|
||||
|
||||
if (!this.transaction) {
|
||||
console.log(`No transaction found for delivery ${delivery_id} among customer transactions`);
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
// Handle various error responses gracefully
|
||||
if (error.response && error.response.status === 404) {
|
||||
console.log(`No transactions found for customer ${this.customer.id}`);
|
||||
this.transaction = null;
|
||||
} else if (error.response && error.response.status === 400) {
|
||||
console.log(`Bad request for customer transactions: ${error.response.data?.detail || error.message}`);
|
||||
this.transaction = null;
|
||||
} else {
|
||||
console.error("Error fetching transaction:", error);
|
||||
this.transaction = null;
|
||||
}
|
||||
});
|
||||
},
|
||||
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';
|
||||
}
|
||||
},
|
||||
CreateTransaction() {
|
||||
const path = `${import.meta.env.VITE_MONEY_URL}/delivery/add/${this.deliveryOrder.id}`;
|
||||
axios.post(path, {}, { withCredentials: true, headers: authHeader() })
|
||||
.then(() => notify({ title: "Success", text: "Accounting record created.", type: "success" }))
|
||||
.catch(() => notify({ title: "Warning", text: "Could not create accounting record.", type: "warn" }));
|
||||
},
|
||||
async onSubmit() {
|
||||
if (Number(this.FinalizeOilOrderForm.gallons_delivered) <= 0) {
|
||||
notify({ title: "Validation Error", text: "Gallons delivered must be greater than zero.", type: "error" });
|
||||
return;
|
||||
}
|
||||
this.isLoading = true;
|
||||
const finalizePayload = {
|
||||
gallons_delivered: this.FinalizeOilOrderForm.gallons_delivered,
|
||||
fill_location: this.FinalizeOilOrderForm.fill_location,
|
||||
cash_recieved: this.FinalizeOilOrderForm.cash_recieved,
|
||||
check_number: this.FinalizeOilOrderForm.check_number,
|
||||
};
|
||||
const finalizePath = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${this.deliveryOrder.id}`;
|
||||
try {
|
||||
const finalizeResponse = await axios.put(finalizePath, finalizePayload, { withCredentials: true, headers: authHeader() });
|
||||
if (!finalizeResponse.data.ok) {
|
||||
throw new Error(finalizeResponse.data.error || "Failed to update delivery details.");
|
||||
}
|
||||
this.CreateTransaction();
|
||||
notify({ title: "Success", text: "Ticket has been finalized.", type: "success" });
|
||||
|
||||
// FIX: Wait for customer data to be loaded before redirecting
|
||||
await this.waitForCustomerData(this.deliveryOrder.customer_id);
|
||||
|
||||
// Updated redirect logic based on your requirements
|
||||
await this.handleRedirect();
|
||||
|
||||
} catch (error: any) {
|
||||
const errorMessage = error.response?.data?.detail || "An error occurred during finalization.";
|
||||
notify({ title: "Error", text: errorMessage, type: "error" });
|
||||
} finally {
|
||||
this.isLoading = false;
|
||||
}
|
||||
},
|
||||
|
||||
// NEW: Wait for customer data to be loaded before redirecting
|
||||
async waitForCustomerData(customerId: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const checkCustomer = () => {
|
||||
if (this.customer && this.customer.id && this.customer.id === customerId) {
|
||||
resolve();
|
||||
} else {
|
||||
setTimeout(checkCustomer, 100);
|
||||
}
|
||||
};
|
||||
checkCustomer();
|
||||
})
|
||||
.catch(() => {
|
||||
notify({
|
||||
title: "Error",
|
||||
text: "Could not get oil pricing",
|
||||
type: "error",
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// NEW: Updated redirect logic based on payment type and transaction status
|
||||
async handleRedirect() {
|
||||
console.log('[DEBUG] Starting redirect logic...');
|
||||
console.log('[DEBUG] payment_type:', this.deliveryOrder.payment_type);
|
||||
console.log('[DEBUG] transaction:', this.transaction);
|
||||
console.log('[DEBUG] customer:', this.customer);
|
||||
|
||||
if (this.deliveryOrder.payment_type === 1) {
|
||||
// payment_type 1: Manual charging - already charged, just redirect to profile
|
||||
console.log('[DEBUG] payment_type 1 - redirecting to customer profile');
|
||||
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
|
||||
|
||||
} else if (this.deliveryOrder.payment_type === 11) {
|
||||
// payment_type 11: API charging - check transaction type
|
||||
console.log('[DEBUG] payment_type 11 - checking transaction type');
|
||||
|
||||
if (this.transaction) {
|
||||
console.log('[DEBUG] Transaction found, type:', this.transaction.transaction_type);
|
||||
|
||||
if (this.transaction.transaction_type === 0) {
|
||||
// Already charged (transaction_type = 0) - redirect to profile
|
||||
console.log('[DEBUG] Already charged - redirecting to customer profile');
|
||||
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
|
||||
|
||||
} else if (this.transaction.transaction_type === 1) {
|
||||
// Auth only (transaction_type = 1) - redirect to capture page
|
||||
console.log('[DEBUG] Auth only - redirecting to capture page');
|
||||
this.$router.push({ name: "captureAuthorize", params: { id: this.deliveryOrder.id } });
|
||||
|
||||
} else {
|
||||
// Unknown transaction type - default to customer profile
|
||||
console.log('[DEBUG] Unknown transaction type - redirecting to customer profile');
|
||||
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
|
||||
}
|
||||
const getTransaction = (delivery_id: any) => {
|
||||
// Add guard to prevent undefined customer ID API calls
|
||||
if (!delivery_id || !customer.value || !customer.value.id) {
|
||||
console.log("Skipping transaction fetch - delivery or customer data not available");
|
||||
return;
|
||||
}
|
||||
|
||||
// Consistent with delivery/view.vue - use customer transaction endpoint
|
||||
const path = `${import.meta.env.VITE_BASE_URL}/payment/transactions/customer/${customer.value.id}/1`;
|
||||
axios.get(path, { withCredentials: true, headers: authHeader() })
|
||||
.then((response: any) => {
|
||||
console.log("Transaction API response:", response.data);
|
||||
// Handle both single transaction object and array responses
|
||||
if (response.data && Array.isArray(response.data) && response.data.length > 0) {
|
||||
// Find the transaction for this specific delivery
|
||||
const deliveryTransaction = response.data.find((txn: any) =>
|
||||
txn.delivery_id === parseInt(delivery_id) ||
|
||||
txn.transaction_id === delivery_id ||
|
||||
txn.delivery_number === delivery_id
|
||||
);
|
||||
transaction.value = deliveryTransaction || null;
|
||||
} else if (response.data && !Array.isArray(response.data)) {
|
||||
// If single transaction, check if it's for this delivery
|
||||
const txn = response.data;
|
||||
if (txn.delivery_id === parseInt(delivery_id) ||
|
||||
txn.transaction_id === delivery_id ||
|
||||
txn.delivery_number === delivery_id) {
|
||||
transaction.value = txn;
|
||||
} else {
|
||||
// No transaction found for payment_type 11 - redirect to customer profile
|
||||
console.log('[DEBUG] No transaction found for payment_type 11 - redirecting to customer profile');
|
||||
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
|
||||
transaction.value = null;
|
||||
}
|
||||
} else {
|
||||
transaction.value = null;
|
||||
}
|
||||
|
||||
} else if ([2].includes(this.deliveryOrder.payment_type)) {
|
||||
// payment_type 2: Credit Card & Cash - go to capture page for any remaining payment
|
||||
console.log('[DEBUG] payment_type 2 - redirecting to capture page');
|
||||
this.$router.push({ name: "captureAuthorize", params: { id: this.deliveryOrder.id } });
|
||||
if (!transaction.value) {
|
||||
console.log(`No transaction found for delivery ${delivery_id} among customer transactions`);
|
||||
}
|
||||
})
|
||||
.catch((error: any) => {
|
||||
// Handle various error responses gracefully
|
||||
if (error.response && error.response.status === 404) {
|
||||
console.log(`No transactions found for customer ${customer.value.id}`);
|
||||
transaction.value = null;
|
||||
} else if (error.response && error.response.status === 400) {
|
||||
console.log(`Bad request for customer transactions: ${error.response.data?.detail || error.message}`);
|
||||
transaction.value = null;
|
||||
} else {
|
||||
console.error("Error fetching transaction:", error);
|
||||
transaction.value = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
const CreateTransaction = () => {
|
||||
const path = `${import.meta.env.VITE_MONEY_URL}/delivery/add/${deliveryOrder.value.id}`;
|
||||
axios.post(path, {}, { withCredentials: true, headers: authHeader() })
|
||||
.then(() => notify({ title: "Success", text: "Accounting record created.", type: "success" }))
|
||||
.catch(() => notify({ title: "Warning", text: "Could not create accounting record.", type: "warn" }));
|
||||
}
|
||||
|
||||
const onSubmit = async () => {
|
||||
if (Number(FinalizeOilOrderForm.value.gallons_delivered) <= 0) {
|
||||
notify({ title: "Validation Error", text: "Gallons delivered must be greater than zero.", type: "error" });
|
||||
return;
|
||||
}
|
||||
isLoading.value = true;
|
||||
const finalizePayload = {
|
||||
gallons_delivered: FinalizeOilOrderForm.value.gallons_delivered,
|
||||
fill_location: FinalizeOilOrderForm.value.fill_location,
|
||||
cash_recieved: FinalizeOilOrderForm.value.cash_recieved,
|
||||
check_number: FinalizeOilOrderForm.value.check_number,
|
||||
};
|
||||
const finalizePath = `${import.meta.env.VITE_BASE_URL}/deliverydata/finalize/${deliveryOrder.value.id}`;
|
||||
try {
|
||||
const finalizeResponse = await axios.put(finalizePath, finalizePayload, { withCredentials: true, headers: authHeader() });
|
||||
if (!finalizeResponse.data.ok) {
|
||||
throw new Error(finalizeResponse.data.error || "Failed to update delivery details.");
|
||||
}
|
||||
CreateTransaction();
|
||||
notify({ title: "Success", text: "Ticket has been finalized.", type: "success" });
|
||||
|
||||
// FIX: Wait for customer data to be loaded before redirecting
|
||||
await waitForCustomerData(deliveryOrder.value.customer_id);
|
||||
|
||||
// Updated redirect logic based on your requirements
|
||||
await handleRedirect();
|
||||
|
||||
} catch (error: any) {
|
||||
const errorMessage = error.response?.data?.detail || "An error occurred during finalization.";
|
||||
notify({ title: "Error", text: errorMessage, type: "error" });
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// NEW: Wait for customer data to be loaded before redirecting
|
||||
const waitForCustomerData = async (customerId: number): Promise<void> => {
|
||||
return new Promise((resolve) => {
|
||||
const checkCustomer = () => {
|
||||
if (customer.value && customer.value.id && customer.value.id === customerId) {
|
||||
resolve();
|
||||
} else {
|
||||
setTimeout(checkCustomer, 100);
|
||||
}
|
||||
};
|
||||
checkCustomer();
|
||||
});
|
||||
}
|
||||
|
||||
// NEW: Updated redirect logic based on payment type and transaction status
|
||||
const handleRedirect = async () => {
|
||||
console.log('[DEBUG] Starting redirect logic...');
|
||||
console.log('[DEBUG] payment_type:', deliveryOrder.value.payment_type);
|
||||
console.log('[DEBUG] transaction:', transaction.value);
|
||||
console.log('[DEBUG] customer:', customer.value);
|
||||
|
||||
if (deliveryOrder.value.payment_type === 1) {
|
||||
// payment_type 1: Manual charging - already charged, just redirect to profile
|
||||
console.log('[DEBUG] payment_type 1 - redirecting to customer profile');
|
||||
router.push({ name: "customerProfile", params: { id: customer.value.id } });
|
||||
|
||||
} else if (deliveryOrder.value.payment_type === 11) {
|
||||
// payment_type 11: API charging - check transaction type
|
||||
console.log('[DEBUG] payment_type 11 - checking transaction type');
|
||||
|
||||
if (transaction.value) {
|
||||
console.log('[DEBUG] Transaction found, type:', transaction.value.transaction_type);
|
||||
|
||||
if (transaction.value.transaction_type === 0) {
|
||||
// Already charged (transaction_type = 0) - redirect to profile
|
||||
console.log('[DEBUG] Already charged - redirecting to customer profile');
|
||||
router.push({ name: "customerProfile", params: { id: customer.value.id } });
|
||||
|
||||
} else if (transaction.value.transaction_type === 1) {
|
||||
// Auth only (transaction_type = 1) - redirect to capture page
|
||||
console.log('[DEBUG] Auth only - redirecting to capture page');
|
||||
router.push({ name: "captureAuthorize", params: { id: deliveryOrder.value.id } });
|
||||
|
||||
} else {
|
||||
// Default case (cash, check, etc.) - redirect to customer profile
|
||||
console.log('[DEBUG] Default payment type - redirecting to customer profile');
|
||||
this.$router.push({ name: "customerProfile", params: { id: this.customer.id } });
|
||||
// Unknown transaction type - default to customer profile
|
||||
console.log('[DEBUG] Unknown transaction type - redirecting to customer profile');
|
||||
router.push({ name: "customerProfile", params: { id: customer.value.id } });
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
} else {
|
||||
// No transaction found for payment_type 11 - redirect to customer profile
|
||||
console.log('[DEBUG] No transaction found for payment_type 11 - redirecting to customer profile');
|
||||
router.push({ name: "customerProfile", params: { id: customer.value.id } });
|
||||
}
|
||||
|
||||
} else if ([2].includes(deliveryOrder.value.payment_type)) {
|
||||
// payment_type 2: Credit Card & Cash - go to capture page for any remaining payment
|
||||
console.log('[DEBUG] payment_type 2 - redirecting to capture page');
|
||||
router.push({ name: "captureAuthorize", params: { id: deliveryOrder.value.id } });
|
||||
|
||||
} else {
|
||||
// Default case (cash, check, etc.) - redirect to customer profile
|
||||
console.log('[DEBUG] Default payment type - redirecting to customer profile');
|
||||
router.push({ name: "customerProfile", params: { id: customer.value.id } });
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped></style>
|
||||
|
||||
Reference in New Issue
Block a user