from .. import controller from odoo import http from odoo.http import request class Voucher(controller.Controller): prefix = '/api/v1/' @http.route(prefix + 'user//voucher', auth='public', methods=['GET', 'OPTIONS']) @controller.Controller.must_authorized(private=True, private_key='user_id') def get_vouchers(self, **kw): cart = request.env['website.user.cart'] code = kw.get('code') user_id = kw.get('user_id') source = kw.get('source') visibility = ['public'] parameter = [] if code: visibility.append('private') parameter += [('code', '=', code)] user_pricelist = request.env.user_pricelist if user_pricelist: parameter += [('excl_pricelist_ids', 'not in', [user_pricelist.id])] parameter += [('visibility', 'in', visibility)] vouchers = request.env['voucher'].get_active_voucher(parameter) checkout = cart.get_user_checkout(user_id, source=source) products = checkout['products'] order_line = [] for product in products: order_line.append({ 'product_id': request.env['product.product'].browse(product['id']), 'price': product['price']['price'], 'discount': product['price']['discount_percentage'], 'qty': product['quantity'], 'subtotal': product['subtotal'] }) results = [] for voucher in vouchers: if not voucher.can_used: continue voucher_info = voucher.apply(order_line) voucher_tnc = voucher.terms_conditions or voucher.generate_tnc() voucher_discount = voucher_info['discount']['all'] valid_order = voucher_info['valid_order'] can_apply = True if valid_order and voucher_discount > 0 else False voucher_res = voucher.format() voucher_res['can_apply'] = can_apply voucher_res['discount_voucher'] = voucher_discount voucher_res['terms_conditions'] = voucher_tnc results.append(voucher_res) sorted_results = sorted(results, key=lambda x: x['can_apply'], reverse=True) return self.response(sorted_results)