I have this code in a .jsw File:
import { coupons } from 'wix-marketing-backend';
import { checkout } from 'wix-pricing-plans-backend';
export async function createAndApplyCoupon(currentOrder, activeOrder) {
const today = new Date();
const endDate = new Date(activeOrder.currentCycle.startedDate);
endDate.setFullYear(today.getFullYear() + 1);
const timeDifference = endDate.getTime() - today.getTime();
const daysUntilEnd = Math.ceil(timeDifference / (1000 * 3600 * 24));
const total = activeOrder.priceDetails.total;
const daysInCycle = activeOrder.pricing.prices[0].duration.cycleFrom === 1 ? 365 : 30;
const pricePerDay = total / daysInCycle;
const amountOff = Math.ceil(pricePerDay * daysUntilEnd);
try {
const uniqueCode = "UPGRADE" + Date.now();
await createCoupon(amountOff, uniqueCode);
await new Promise(resolve => setTimeout(resolve, 2000));
const discountedOrder = await applyCoupon(currentOrder._id, uniqueCode);
console.log('Coupon applied to current order successfully', discountedOrder);
} catch (error) {
console.error('Error in createAndApplyCoupon:', error);
}
}
async function applyCoupon(orderId, couponCode) {
return checkout.applyCoupon(orderId, couponCode)
.then((discountedOrder) => {
return discountedOrder;
})
.catch((error) => {
console.error('Error applying coupon:', error);
throw new Error('Failed to apply coupon');
});
}
export function createCoupon(amountOff, couponCode) {
let couponInfo = {
"name": "Gutschrift",
"code": couponCode,
"startTime": new Date(),
"expirationTime": new Date(2025, 12, 31),
"usageLimit": 1,
"limitedToOneItem": true,
"limitPerCustomer": 1,
"active": true,
"scope": {
"namespace": "pricingPlans"
},
"moneyOffAmount": 10 //should actually be "amountOff", but changed it for testing
};
console.log("Creating Coupon: " + couponInfo)
return coupons.createCoupon(couponInfo);
}
And this code in the frontend Pricing page:
import wixLocation from 'wix-location';
import { orders } from 'wix-pricing-plans-frontend';
import { createAndApplyCoupon } from 'backend/upgradeLogic.jsw';
$w.onReady(function () {
// Funktion zum Finden des ersten Auftrags mit einem bestimmten Status
function findFirstOrderWithStatus(status) {
const filters = {
orderStatuses: [status]
};
return orders.listCurrentMemberOrders(filters)
.then((ordersList) => {
return ordersList.length > 0 ? ordersList[0] : null;
})
.catch((error) => {
console.error('Error fetching orders:', error);
return null;
});
}
// Zuerst den aktiven Auftrag finden
findFirstOrderWithStatus('ACTIVE').then(activeOrder => {
if (activeOrder) {
// Dann den Entwurfsauftrag finden
findFirstOrderWithStatus('DRAFT').then(draftOrder => {
if (draftOrder) {
console.log('Current Active Order:', activeOrder);
console.log('Current Draft Order:', draftOrder);
createAndApplyCoupon(draftOrder, activeOrder);
} else {
console.log("No Current Draft order");
}
});
} else {
console.log("No Current Active order");
}
});
let queryParams = wixLocation.query;
if ("appSectionParams" in queryParams) {
wixLocation.to("/preise?NoPlanRedirect=true");
} else {
$w('#section1').expand();
}
});
Iām trying to automatically apply a Coupon the the current order, which the user has opened. The coupon getās successfully applied (as I can see in the backend events) but the coupon field on the standard checkout page stays empty (doesnāt get updated), even though itās applied in the backend.
@CODE-NINJA ? Any thoughts?
Can anyone help?