1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
|
from odoo import models, fields, api
from datetime import datetime, timedelta
from odoo.exceptions import ValidationError
class Voucher(models.Model):
_name = 'voucher'
_rec_name = 'display_name'
display_name = fields.Char(string='Display Name', compute='_compute_display_name')
name = fields.Char(string='Name')
image = fields.Binary(string='Image')
code = fields.Char(string='Code', help='Kode voucher yang akan berlaku untuk pengguna')
description = fields.Text(string='Description')
discount_amount = fields.Integer(string='Discount Amount')
discount_type = fields.Selection(string='Discount Type',
selection=[
('percentage', 'Percentage'),
('fixed_price', 'Fixed Price'),
],
help='Select the type of discount:\n'
'- Percentage: Persentase dari total harga.\n'
'- Fixed Price: Jumlah tetap yang dikurangi dari harga total.'
)
visibility = fields.Selection(string='Visibility',
selection=[
('public', 'Public'),
('private', 'Private')
],
help='Select the visibility:\n'
'- Public: Ditampilkan kepada seluruh pengguna.\n'
'- Private: Tidak ditampilkan kepada seluruh pengguna.'
)
start_time = fields.Datetime(string='Start Time')
end_time = fields.Datetime(string='End Time')
min_purchase_amount = fields.Integer(string='Min. Purchase Amount', help='Nominal minimum untuk dapat menggunakan voucher. Isi 0 jika tidak ada minimum purchase amount')
max_discount_amount = fields.Integer(string='Max. Discount Amount', help='Max nominal terhadap persentase diskon')
order_ids = fields.One2many('sale.order', 'voucher_id', string='Order')
limit = fields.Integer(string='Limit', help='Voucher limit by sale order. Masukan 0 untuk tanpa limit')
manufacture_ids = fields.Many2many('x_manufactures', string='Brands', help='Voucher appplied only for brand')
excl_pricelist_ids = fields.Many2many('product.pricelist', string='Excluded Pricelists', help='Hide voucher from selected exclude pricelist')
voucher_line = fields.One2many('voucher.line', 'voucher_id', 'Voucher Line')
apply_type = fields.Selection(string='Apply Type', default="all", selection=[
('all', "All product"),
('brand', "Selected product brand"),
])
@api.constrains('description')
def _check_description_length(self):
for record in self:
if record.description and len(record.description) > 120:
raise ValidationError('Description cannot exceed 120 characters')
def _compute_display_name(self):
for voucher in self:
voucher.display_name = f'{voucher.name} ({voucher.code})'
def res_format(self):
datas = [voucher.format() for voucher in self]
return datas
def format(self):
ir_attachment = self.env['ir.attachment']
discount_type = self.discount_type
max_discount_amount = self.max_discount_amount if discount_type == 'percentage' else 0
data = {
'id': self.id,
'image': ir_attachment.api_image('voucher', 'image', self.id),
'name': self.name,
'code': self.code,
'description': self.description,
'discount_amount': self.discount_amount,
'discount_type': discount_type,
'remaining_time': self._res_remaining_time(),
'min_purchase_amount': self.min_purchase_amount,
'max_discount_amount': max_discount_amount,
'manufacture_names': ", ".join([x.x_name for x in self.manufacture_ids]),
'manufacture_ids': [x.id for x in self.manufacture_ids],
'excl_pricelist_ids': [x.id for x in self.excl_pricelist_ids],
}
return data
def _res_remaining_time(self):
seconds = self._get_remaining_time()
remaining_time = timedelta(seconds=seconds)
hours = remaining_time.seconds // 3600
minutes = remaining_time.seconds // 60
if remaining_time.days > 0:
time = remaining_time.days
unit = 'hari'
elif hours > 0:
time = hours
unit = 'jam'
else:
time = minutes
unit = 'menit'
return f'{time} {unit}'
def _get_remaining_time(self):
calculate_time = self.end_time - datetime.now()
return round(calculate_time.total_seconds())
def filter_order_line(self, order_line):
if self.apply_type == 'all':
return order_line
voucher_manufacture_ids = self.collect_manufacture_ids()
results = []
for line in order_line:
manufacture_id = line['product_id'].x_manufacture.id or None
if manufacture_id not in voucher_manufacture_ids:
continue
product_flashsale = line['product_id']._get_active_flash_sale()
if len(product_flashsale) > 0:
continue
results.append(line)
return results
def calc_total_order_line(self, order_line):
result = { 'all': 0, 'brand': {} }
for line in order_line:
manufacture_id = line['product_id'].x_manufacture.id or None
manufacture_total = result['brand'].get(manufacture_id, 0)
result['brand'][manufacture_id] = manufacture_total + line['subtotal']
result['all'] += line['subtotal']
return result
def calc_discount_amount(self, total):
result = { 'all': 0, 'brand': {} }
if self.apply_type == 'all':
if total['all'] < self.min_purchase_amount:
return result
if self.discount_type == 'percentage':
decimal_discount = self.discount_amount / 100
discount_all = total['all'] * decimal_discount
result['all'] = min(discount_all, self.max_discount_amount) if self.max_discount_amount > 0 else discount_all
else:
result['all'] = self.discount_amount
return result
for line in self.voucher_line:
manufacture_id = line.manufacture_id.id
total_brand = total['brand'].get(manufacture_id, 0)
discount_brand = 0
if total_brand < line.min_purchase_amount:
discount_brand = 0
elif line.discount_type == 'percentage':
decimal_discount = line.discount_amount / 100
discount_brand = total_brand * decimal_discount
discount_brand = min(discount_brand, line.max_discount_amount) if line.max_discount_amount > 0 else discount_brand
else:
discount_brand = line.discount_amount
result['brand'][manufacture_id] = discount_brand
result['all'] += discount_brand
return result
def apply(self, order_line):
order_line = self.filter_order_line(order_line)
amount_total = self.calc_total_order_line(order_line)
discount = self.calc_discount_amount(amount_total)
return {
'discount': discount,
'total': amount_total,
'type': self.apply_type,
'valid_order': order_line
}
def collect_manufacture_ids(self):
return [x.manufacture_id.id for x in self.voucher_line]
def calculate_discount(self, price):
if price < self.min_purchase_amount:
return 0
if self.discount_type == 'fixed_price':
return self.discount_amount
if self.discount_type == 'percentage':
discount = price * self.discount_amount / 100
max_disc = self.max_discount_amount
return discount if max_disc == 0 else min(discount, max_disc)
return 0
def get_active_voucher(self, domain):
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
domain += [
('start_time', '<=', current_time),
('end_time', '>=', current_time),
]
vouchers = self.search(domain, order='min_purchase_amount ASC')
return vouchers
|