Best Python code snippet using autotest_python
loyalty_program.py
Source:loyalty_program.py
1# -*- coding: utf-8 -*-2# Part of Odoo. See LICENSE file for full copyright and licensing details.3from collections import defaultdict4from odoo import _, api, fields, models5from odoo.exceptions import UserError, ValidationError6from uuid import uuid47class LoyaltyProgram(models.Model):8 _name = 'loyalty.program'9 _description = 'Loyalty Program'10 _order = 'sequence'11 _rec_name = 'name'12 name = fields.Char('Program Name', required=True, translate=True)13 active = fields.Boolean(default=True)14 sequence = fields.Integer(copy=False)15 company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company)16 currency_id = fields.Many2one('res.currency', 'Currency', compute='_compute_currency_id',17 readonly=False, required=True, store=True, precompute=True)18 currency_symbol = fields.Char(related='currency_id.symbol')19 total_order_count = fields.Integer("Total Order Count", compute="_compute_total_order_count")20 rule_ids = fields.One2many('loyalty.rule', 'program_id', 'Triggers', copy=True,21 compute='_compute_from_program_type', readonly=False, store=True)22 reward_ids = fields.One2many('loyalty.reward', 'program_id', 'Rewards', copy=True,23 compute='_compute_from_program_type', readonly=False, store=True)24 communication_plan_ids = fields.One2many('loyalty.mail', 'program_id', copy=True,25 compute='_compute_from_program_type', readonly=False, store=True)26 coupon_ids = fields.One2many('loyalty.card', 'program_id')27 coupon_count = fields.Integer(compute='_compute_coupon_count')28 program_type = fields.Selection([29 ('coupons', 'Coupons'),30 ('gift_card', 'Gift Card'),31 ('loyalty', 'Loyalty Cards'),32 ('promotion', 'Promotions'),33 ('ewallet', 'eWallet')], default='promotion', required=True,34 )35 date_to = fields.Date(string='Validity')36 limit_usage = fields.Boolean(string='Limit Usage')37 max_usage = fields.Integer()38 # Dictates when the points can be used:39 # current: if the order gives enough points on that order, the reward may directly be claimed, points lost otherwise40 # future: if the order gives enough points on that order, a coupon is generated for a next order41 # both: points are accumulated on the coupon to claim rewards, the reward may directly be claimed42 applies_on = fields.Selection([43 ('current', 'Current order'),44 ('future', 'Future orders'),45 ('both', 'Current & Future orders')], default='current', required=True,46 compute='_compute_from_program_type', readonly=False, store=True,47 )48 trigger = fields.Selection([49 ('auto', 'Automatic'),50 ('with_code', 'Use a code')],51 compute='_compute_from_program_type', readonly=False, store=True,52 help="""53 Automatic: Customers will be eligible for a reward automatically in their cart.54 Use a code: Customers will be eligible for a reward if they enter a code.55 """56 )57 portal_visible = fields.Boolean(default=False,58 help="""59 Show in web portal, PoS customer ticket, eCommerce checkout, the number of points available and used by reward.60 """)61 portal_point_name = fields.Char(default='Points', translate=True,62 compute='_compute_from_program_type', readonly=False, store=True)63 is_nominative = fields.Boolean(compute='_compute_is_nominative')64 _sql_constraints = [65 ('check_max_usage', 'CHECK (limit_usage = False OR max_usage > 0)',66 'Max usage must be strictly positive if a limit is used.'),67 ]68 @api.constrains('reward_ids')69 def _constrains_reward_ids(self):70 if any(not program.reward_ids for program in self):71 raise ValidationError(_('A program must have at least one reward.'))72 def _compute_total_order_count(self):73 self.total_order_count = 074 @api.depends('company_id')75 def _compute_currency_id(self):76 for program in self:77 program.currency_id = program.company_id.currency_id or program.currency_id78 @api.depends('coupon_ids')79 def _compute_coupon_count(self):80 read_group_data = self.env['loyalty.card']._read_group([('program_id', 'in', self.ids)], ['program_id'], ['program_id'])81 count_per_program = {r['program_id'][0]: r['program_id_count'] for r in read_group_data}82 for program in self:83 program.coupon_count = count_per_program.get(program.id, 0)84 @api.depends('program_type', 'applies_on')85 def _compute_is_nominative(self):86 for program in self:87 program.is_nominative = program.applies_on == 'both' or\88 (program.program_type == 'ewallet' and program.applies_on == 'future')89 @api.model90 def _program_type_default_values(self):91 # All values to change when program_type changes92 # NOTE: any field used in `rule_ids`, `reward_ids` and `communication_plan_ids` MUST be present in the kanban view for it to work properly.93 return {94 'coupons': {95 'applies_on': 'current',96 'trigger': 'with_code',97 'portal_visible': False,98 'portal_point_name': _('Points'),99 # Coupons don't use rules by default100 'rule_ids': [(5, 0, 0)],101 'reward_ids': [(5, 0, 0), (0, 0, {102 'required_points': 1,103 'discount': 10,104 })],105 'communication_plan_ids': [(5, 0, 0), (0, 0, {106 'trigger': 'create',107 'mail_template_id': (self.env.ref('loyalty.mail_template_loyalty_card', raise_if_not_found=False) or self.env['mail.template']).id,108 })],109 },110 'promotion': {111 'applies_on': 'current',112 'trigger': 'auto',113 'portal_visible': False,114 'portal_point_name': _('Points'),115 'rule_ids': [(5, 0, 0), (0, 0, {116 'reward_point_amount': 1,117 'reward_point_mode': 'order',118 'minimum_amount': 50,119 })],120 'reward_ids': [(5, 0, 0), (0, 0, {121 'required_points': 1,122 'discount': 10,123 })],124 'communication_plan_ids': [(5, 0, 0)],125 },126 'gift_card': {127 'applies_on': 'future',128 'trigger': 'auto',129 'portal_visible': True,130 'portal_point_name': self.env.company.currency_id.symbol,131 'rule_ids': [(5, 0, 0), (0, 0, {132 'reward_point_amount': 1,133 'reward_point_mode': 'money',134 'reward_point_split': True,135 'product_ids': self.env.ref('loyalty.gift_card_product_50', raise_if_not_found=False),136 })],137 'reward_ids': [(5, 0, 0), (0, 0, {138 'reward_type': 'discount',139 'discount_mode': 'per_point',140 'discount': 1,141 'discount_applicability': 'order',142 'required_points': 1,143 'description': _('Pay With Gift Card'),144 })],145 'communication_plan_ids': [(5, 0, 0), (0, 0, {146 'trigger': 'create',147 'mail_template_id': (self.env.ref('loyalty.mail_template_gift_card', raise_if_not_found=False) or self.env['mail.template']).id,148 })],149 },150 'loyalty': {151 'applies_on': 'both',152 'trigger': 'auto',153 'portal_visible': True,154 'portal_point_name': _('Loyalty Points'),155 'rule_ids': [(5, 0, 0), (0, 0, {156 'reward_point_mode': 'money',157 })],158 'reward_ids': [(5, 0, 0), (0, 0, {159 'discount': 5,160 'required_points': 200,161 })],162 'communication_plan_ids': [(5, 0, 0)],163 },164 'ewallet': {165 'applies_on': 'future',166 'trigger': 'auto',167 'portal_visible': True,168 'portal_point_name': self.env.company.currency_id.symbol,169 'rule_ids': [(5, 0, 0), (0, 0, {170 'reward_point_amount': '1',171 'reward_point_mode': 'money',172 'product_ids': self.env.ref('loyalty.ewallet_product_50'),173 })],174 'reward_ids': [(5, 0, 0), (0, 0, {175 'reward_type': 'discount',176 'discount_mode': 'per_point',177 'discount': 1,178 'discount_applicability': 'order',179 'required_points': 1,180 })],181 'communication_plan_ids': [(5, 0, 0)],182 },183 }184 @api.depends('program_type')185 def _compute_from_program_type(self):186 program_type_defaults = self._program_type_default_values()187 grouped_programs = defaultdict(lambda: self.env['loyalty.program'])188 for program in self:189 grouped_programs[program.program_type] |= program190 for program_type, programs in grouped_programs.items():191 if program_type in program_type_defaults:192 programs.write(program_type_defaults[program_type])193 def _get_valid_products(self, products):194 '''195 Returns a dict containing the products that match per rule of the program196 '''197 rule_products = dict()198 for rule in self.rule_ids:199 domain = rule._get_valid_product_domain()200 if domain:201 rule_products[rule] = products.filtered_domain(domain)202 else:203 rule_products[rule] = products204 return rule_products205 @api.ondelete(at_uninstall=False)206 def _unlink_except_active(self):207 if any(program.active for program in self):208 raise UserError(_('You can not delete a program in an active state'))209 def toggle_active(self):210 super().toggle_active()211 # Propagate active state to children212 for program in self:213 program.rule_ids.active = program.active214 program.reward_ids.active = program.active215 program.communication_plan_ids.active = program.active216 program.reward_ids.discount_line_product_id.active = program.active217 @api.model218 def get_program_templates(self):219 '''220 Returns the templates to be used for promotional programs.221 '''222 return {223 'promo_code': {224 'title': _('Promo Code'),225 'description': _('Get a code to receive 10% discount on specific products'),226 'icon': 'promo_code',227 },228 'gift_card': {229 'title': _('Gift Card'),230 'description': _('Sell Gift Cards, that can be used to purchase products'),231 'icon': 'gift_card',232 },233 'loyalty': {234 'title': _('Loyalty Cards'),235 'description': _('Win points with each purchases, and use points to get gifts'),236 'icon': 'loyalty_cards',237 },238 'fidelity': {239 'title': _('Fidelity Cards'),240 'description': _('Buy 10 products, and get 10$ discount on the 11th one'),241 'icon': 'fidelity_cards',242 },243 'promotion': {244 'title': _('Promotional Program'),245 'description': _('Automatic promotion: 10% discount on orders higher than $50'),246 'icon': 'promotional_program',247 },248 'coupons': {249 'title': _('Coupons'),250 'description': _('Send unique coupons that give access to rewards'),251 'icon': 'coupons',252 },253 'buy_two_get_one': {254 'title': _('2+1 Free'),255 'description': _('Buy 2 products and get a third one for free'),256 'icon': '2_plus_1',257 },258 'ewallet': {259 'title': _('eWallet'),260 'description': _('Fill in your eWallet, and use it to pay future orders'),261 'icon': 'ewallet',262 },263 }264 @api.model265 def create_from_template(self, template_id):266 '''267 Creates the program from the template id defined in `get_program_templates`.268 Returns an action leading to that new record.269 '''270 template_values = self._get_template_values()271 if template_id not in template_values:272 return False273 program = self.create(template_values[template_id])274 action = self.env['ir.actions.act_window']._for_xml_id('loyalty.loyalty_program_action')275 action['view_type'] = 'form'276 action['res_id'] = program.id277 return action278 @api.model279 def _get_template_values(self):280 '''281 Returns the values to create a program using the template keys defined above.282 '''283 program_type_defaults = self._program_type_default_values()284 # For programs that require a product get the first sellable.285 product = self.env['product.product'].search([('sale_ok', '=', True)], limit=1)286 return {287 'gift_card': {288 'name': _('Gift Card'),289 'program_type': 'gift_card',290 **program_type_defaults['gift_card']291 },292 'ewallet': {293 'name': _('eWallet'),294 'program_type': 'ewallet',295 **program_type_defaults['ewallet'],296 },297 'loyalty': {298 'name': _('Loyalty Cards'),299 'program_type': 'loyalty',300 **program_type_defaults['loyalty'],301 },302 'coupons': {303 'name': _('Coupons'),304 'program_type': 'coupons',305 **program_type_defaults['coupons'],306 },307 'promotion': {308 'name': _('Promotional Program'),309 'program_type': 'promotion',310 **program_type_defaults['promotion'],311 },312 'promo_code': {313 'name': _('Promo Code'),314 'program_type': 'promotion',315 'applies_on': 'current',316 'trigger': 'with_code',317 'rule_ids': [(0, 0, {318 'mode': 'with_code',319 'code': '10PERCENT_' + str(uuid4())[:4], # Require a random code in case a user creates multiple program using this template320 })],321 'reward_ids': [(0, 0, {322 'discount_applicability': 'specific',323 'discount_product_ids': product,324 'discount_mode': 'percent',325 'discount': 10,326 })]327 },328 'fidelity': {329 'name': _('Fidelity Cards'),330 'program_type': 'loyalty',331 'applies_on': 'both',332 'trigger': 'auto',333 'rule_ids': [(0, 0, {334 'reward_point_mode': 'unit',335 'product_ids': product,336 })],337 'reward_ids': [(0, 0, {338 'discount_mode': 'per_order',339 'required_points': 11,340 'discount_applicability': 'specific',341 'discount_product_ids': product,342 'discount': 10,343 })]344 },345 'buy_two_get_one': {346 'name': _('2+1 Free'),347 'program_type': 'promotion',348 'applies_on': 'current',349 'trigger': 'auto',350 'rule_ids': [(0, 0, {351 'reward_point_mode': 'unit',352 'product_ids': product,353 })],354 'reward_ids': [(0, 0, {355 'reward_type': 'product',356 'reward_product_id': product and product.id or False,357 'required_points': 2,358 })]359 },...
iscsi.py
Source:iscsi.py
...119 login = False120 if self.target in map(lambda x: x[1], sessions):121 login = True122 return login123 def portal_visible(self):124 """125 Check if the portal can be found or not.126 """127 return bool(re.findall("%s$" % self.target,128 iscsi_discover(self.portal_ip), re.M))129 def login(self):130 """131 Login session for both real iscsi device and emulated iscsi. Include132 env check and setup.133 """134 login_flag = False135 if self.portal_visible():136 login_flag = True137 elif self.initiator:138 logging.debug("Try to update iscsi initiatorname")139 cmd = "mv /etc/iscsi/initiatorname.iscsi "140 cmd += "/etc/iscsi/initiatorname.iscsi-%s" % self.id141 utils.system(cmd)142 fd = open("/etc/iscsi/initiatorname.iscsi", 'w')143 fd.write("InitiatorName=%s" % self.initiator)144 fd.close()145 utils.system("service iscsid restart")146 if self.portal_visible():147 login_flag = True148 elif self.emulated_image:149 self.export_target()150 utils.system("service iscsid restart")151 if self.portal_visible():152 login_flag = True153 if login_flag:154 iscsi_login(self.target)155 def get_device_name(self):156 """157 Get device name from the target name.158 """159 cmd = "iscsiadm -m session -P 3"160 device_name = ""161 if self.logged_in():162 output = utils.system_output(cmd)163 pattern = r"Target:\s+%s.*?disk\s(\w+)\s+\S+\srunning" % self.target164 device_name = re.findall(pattern, output, re.S)165 try:...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!