class PaymentIcon(models.Model): _name = 'payment.icon' _description = 'Payment Icon' name = fields.Char(string='Name') acquirer_ids = fields.Many2many( 'payment.acquirer', string="Acquirers", help="List of Acquirers supporting this payment icon.") image = fields.Binary( "Image", attachment=True, help= "This field holds the image used for this payment icon, limited to 1024x1024px" ) image_payment_form = fields.Binary("Image displayed on the payment form", attachment=True) @api.model def create(self, vals): if 'image' in vals: vals['image_payment_form'] = image_resize_image(vals['image'], size=(45, 30)) vals['image'] = image_resize_image(vals['image'], size=(64, 64)) return super(PaymentIcon, self).create(vals) @api.multi def write(self, vals): if 'image' in vals: vals['image_payment_form'] = image_resize_image(vals['image'], size=(45, 30)) vals['image'] = image_resize_image(vals['image'], size=(64, 64)) return super(PaymentIcon, self).write(vals)
class IrActionsActClient(models.Model): _name = 'ir.actions.client' _inherit = 'ir.actions.actions' _table = 'ir_act_client' _sequence = 'ir_actions_id_seq' _order = 'name' name = fields.Char(string='Action Name', translate=True) type = fields.Char(default='ir.actions.client') tag = fields.Char(string='Client action tag', required=True, help="An arbitrary string, interpreted by the client" " according to its own needs and wishes. There " "is no central tag repository across clients.") target = fields.Selection([('current', 'Current Window'), ('new', 'New Window'), ('fullscreen', 'Full Screen'), ('main', 'Main action of Current Window')], default="current", string='Target Window') res_model = fields.Char(string='Destination Model', help="Optional model, mostly used for needactions.") context = fields.Char(string='Context Value', default="{}", required=True, help="Context dictionary as Python expression, empty by default (Default: {})") params = fields.Binary(compute='_compute_params', inverse='_inverse_params', string='Supplementary arguments', help="Arguments sent to the client along with" "the view tag") params_store = fields.Binary(string='Params storage', readonly=True) @api.depends('params_store') def _compute_params(self): self_bin = self.with_context(bin_size=False, bin_size_params_store=False) for record, record_bin in pycompat.izip(self, self_bin): record.params = record_bin.params_store and safe_eval(record_bin.params_store, {'uid': self._uid}) def _inverse_params(self): for record in self: params = record.params record.params_store = repr(params) if isinstance(params, dict) else params
class FleetVehicleModelBrand(models.Model): _name = 'fleet.vehicle.model.brand' _description = 'Brand of the vehicle' _order = 'name asc' name = fields.Char('Make', required=True) image = fields.Binary( "Logo", attachment=True, help= "This field holds the image used as logo for the brand, limited to 1024x1024px." ) image_medium = fields.Binary( "Medium-sized image", attachment=True, help="Medium-sized logo of the brand. It is automatically " "resized as a 128x128px image, with aspect ratio preserved. " "Use this field in form views or some kanban views.") image_small = fields.Binary( "Small-sized image", attachment=True, help="Small-sized logo of the brand. It is automatically " "resized as a 64x64px image, with aspect ratio preserved. " "Use this field anywhere a small image is required.") @api.model def create(self, vals): tools.image_resize_images(vals) return super(FleetVehicleModelBrand, self).create(vals) @api.multi def write(self, vals): tools.image_resize_images(vals) return super(FleetVehicleModelBrand, self).write(vals)
class BinarySvg(models.Model): _name = 'test_new_api.binary_svg' _description = 'Test SVG upload' name = fields.Char(required=True) image_attachment = fields.Binary(attachment=True) image_wo_attachment = fields.Binary(attachment=False)
class ModuleBuilderDataFile(models.Model): _name = 'module.builder.data.file' _rec_name = 'path' module_id = fields.Many2one('module.builder.main', 'Module', ondelete='cascade') extension = fields.Char('Extension', compute='_compute_file_data', store=True) ctype = fields.Char('Content Type', compute='_compute_file_data', store=True) path = fields.Char(string='Path', required=True, default='/static/description/') is_image = fields.Boolean('Is Image', compute='_compute_file_data', store=True) filename = fields.Char('Filename', compute='_compute_file_data', store=True) image_small = fields.Binary('Image Thumb', compute='_compute_file_data', store=True) content = fields.Binary('Content') size = fields.Integer('Size', compute='_compute_file_data', store=True) icon = fields.Char('Icon File', store=True) @api.one @api.depends('content', 'path') def _compute_file_data(self): if self.content: self.size = len(decodebytes(self.content)) self.filename = os.path.basename(self.path) self.extension = os.path.splitext(self.path)[1] self.ctype = mimetypes.guess_type( self.filename)[0] if mimetypes.guess_type( self.filename) else False self.is_image = self.ctype in [ 'image/png', 'image/jpeg', 'image/gif', 'image/bmp' ] self.image_small = tools.image_resize_image_small( self.content, size=(100, 100)) if self.is_image else False else: self.size = False self.filename = False self.extension = False self.ctype = False self.image_small = False self.is_image = False
class PosCategory(models.Model): _name = "pos.category" _description = "PoS Category" _order = "sequence, name" @api.constrains('parent_id') def _check_category_recursion(self): if not self._check_recursion(): raise ValueError(_('Error ! You cannot create recursive categories.')) name = fields.Char(required=True, translate=True) parent_id = fields.Many2one('pos.category', string='Parent Category', index=True) child_id = fields.One2many('pos.category', 'parent_id', string='Children Categories') sequence = fields.Integer(help="Gives the sequence order when displaying a list of product categories.") # NOTE: there is no 'default image', because by default we don't show # thumbnails for categories. However if we have a thumbnail for at least one # category, then we display a default image on the other, so that the # buttons have consistent styling. image = fields.Binary(attachment=True, help="This field holds the image used as image for the cateogry, limited to 1024x1024px.") image_medium = fields.Binary(string="Medium-sized image", attachment=True, help="Medium-sized image of the category. It is automatically " "resized as a 128x128px image, with aspect ratio preserved. " "Use this field in form views or some kanban views.") image_small = fields.Binary(string="Small-sized image", attachment=True, help="Small-sized image of the category. It is automatically " "resized as a 64x64px image, with aspect ratio preserved. " "Use this field anywhere a small image is required.") @api.model def create(self, vals): tools.image_resize_images(vals) return super(PosCategory, self).create(vals) @api.multi def write(self, vals): tools.image_resize_images(vals) return super(PosCategory, self).write(vals) @api.multi def name_get(self): def get_names(cat): res = [] while cat: res.append(cat.name) cat = cat.parent_id return res return [(cat.id, " / ".join(reversed(get_names(cat)))) for cat in self]
class ProductImage(models.Model): _name = 'product.image' _description = 'Product Image' name = fields.Char(string='Name') description = fields.Text(string='Description') image_alt = fields.Text(string='Image Label') image = fields.Binary(string='Image') image_small = fields.Binary(string='Small Image') image_url = fields.Char(string='Image URL') product_tmpl_id = fields.Many2one('product.template', 'Product', copy=False) product_variant_id = fields.Many2one('product.product', 'Product Variant', copy=False)
class StaffInfo(models.Model): _name = "staff.info" _order = 'hand' @api.multi def button_done(self): for rec in self: rec.write({'state': 'done'}) @api.multi def button_cancel(self): for rec in self: rec.write({'state': 'cancel'}) @api.multi def button_draft(self): for rec in self: rec.write({'state': 'draft'}) @api.onchange("bank_staff_id") def _compute_customer(self): self.ifsc_code = self.bank_staff_id.bank_ifsc_code total_staff = fields.Integer("") name = fields.Char("Name") staff_post = fields.Char("Post") staff_pan = fields.Char("Pan no") staff_mobile = fields.Integer("Mobile No", size=12) staff_image = fields.Binary("Image") ifsc_code = fields.Char('IFSC Code') bank_staff_id = fields.Many2one("bank.info", string="Bank") state = fields.Selection([('draft', 'Draft'), ('done', 'Accept'), ('cancel', 'Reject')], default='draft') hand = fields.Integer("Sequence")
class BaseDocumentLayout(models.TransientModel): _inherit = 'base.document.layout' street = fields.Char(related='company_id.street', readonly=True) street2 = fields.Char(related='company_id.street2', readonly=True) zip = fields.Char(related='company_id.zip', readonly=True) city = fields.Char(related='company_id.city', readonly=True) company_registry = fields.Char(related='company_id.company_registry', readonly=True) bank_ids = fields.One2many(related='company_id.partner_id.bank_ids', readonly=True) l10n_de_template_data = fields.Binary( compute='_compute_l10n_de_template_data') l10n_de_document_title = fields.Char( compute='_compute_l10n_de_document_title') def _compute_l10n_de_template_data(self): self.l10n_de_template_data = [ (_("Invoice No."), 'INV/2021/12345'), (_("Invoice Date"), format_date(self.env, fields.Date.today())), (_("Due Date"), format_date(self.env, fields.Date.add(fields.Date.today(), days=7))), (_("Reference"), 'SO/2021/45678'), ] def _compute_l10n_de_document_title(self): self.l10n_de_document_title = 'Invoice'
class import_account_payment_from_xml(models.TransientModel): _name = 'import.account.payment.from.xml' import_file = fields.Binary("Importar Archivo", required=False) file_name = fields.Char("Nombre del archivo") payment_id = fields.Many2one("account.payment", 'Payment') @api.multi def import_xml_file_button(self): self.ensure_one() if not self.import_file: raise Warning("Seleccione primero el archivo.") p, ext = os.path.splitext(self.file_name) if ext[1:].lower() != 'xml': raise Warning( _("Formato no soportado \"{}\", importa solo archivos XML"). format(self.file_name)) file_content = base64.b64decode(self.import_file) tree = etree.fromstring(file_content) payment_vals = { 'cep_sello': tree.get('sello'), 'cep_numeroCertificado': tree.get('numeroCertificado', tree.get('NumeroCertificado')), 'cep_cadenaCDA': tree.get('cadenaCDA', tree.get('CadenaCDA')), 'cep_claveSPEI': tree.get('ClaveSPEI', tree.get('claveSPEI')), } self.payment_id.write(payment_vals) return True
class BaseLanguageImport(models.TransientModel): _name = "base.language.import" _description = "Language Import" name = fields.Char('Language Name', required=True) code = fields.Char('ISO Code', size=5, required=True, help="ISO Language and Country code, e.g. en_US") data = fields.Binary('File', required=True) filename = fields.Char('File Name', required=True) overwrite = fields.Boolean('Overwrite Existing Terms', help="If you enable this option, existing translations (including custom ones) " "will be overwritten and replaced by those in this file") @api.multi def import_lang(self): this = self[0] this = this.with_context(overwrite=this.overwrite) with TemporaryFile('w+') as buf: try: buf.write(base64.decodestring(this.data)) # now we determine the file format buf.seek(0) fileformat = os.path.splitext(this.filename)[-1][1:].lower() tools.trans_load_data(this._cr, buf, fileformat, this.code, lang_name=this.name, context=this._context) except Exception as e: _logger.exception('File unsuccessfully imported, due to format mismatch.') raise UserError(_('File not imported due to format mismatch or a malformed file. (Valid formats are .csv, .po, .pot)\n\nTechnical Details:\n%s') % tools.ustr(e)) return True
class MultiImages(models.Model): _name = "multi.images" image = fields.Binary('Images') description = fields.Char('Description') title = fields.Char('title') product_template_id = fields.Many2one('product.template', 'Product')
class RestaurantFloor(models.Model): _name = 'restaurant.floor' _description = 'Restaurant Floor' name = fields.Char('Floor Name', required=True, help='An internal identification of the restaurant floor') pos_config_id = fields.Many2one('pos.config', string='Point of Sale') background_image = fields.Binary('Background Image', help='A background image used to display a floor layout in the point of sale interface') background_color = fields.Char('Background Color', help='The background color of the floor layout, (must be specified in a html-compatible format)', default='rgb(210, 210, 210)') table_ids = fields.One2many('restaurant.table', 'floor_id', string='Tables', help='The list of tables in this floor') sequence = fields.Integer('Sequence', help='Used to sort Floors', default=1) active = fields.Boolean(default=True) def unlink(self): confs = self.mapped('pos_config_id').filtered(lambda c: c.is_table_management == True) opened_session = self.env['pos.session'].search([('config_id', 'in', confs.ids), ('state', '!=', 'closed')]) if opened_session: error_msg = _("You cannot remove a floor that is used in a PoS session, close the session(s) first: \n") for floor in self: for session in opened_session: if floor in session.config_id.floor_ids: error_msg += _("Floor: %s - PoS Config: %s \n") % (floor.name, session.config_id.name) if confs: raise UserError(error_msg) return super(RestaurantFloor, self).unlink() def write(self, vals): for floor in self: if floor.pos_config_id.has_active_session and (vals.get('pos_config_id') or vals.get('active')) : raise UserError( 'Please close and validate the following open PoS Session before modifying this floor.\n' 'Open session: %s' % (' '.join(floor.pos_config_id.mapped('name')),)) if vals.get('pos_config_id') and floor.pos_config_id.id and vals.get('pos_config_id') != floor.pos_config_id.id: raise UserError('The %s is already used in another Pos Config.' % floor.name) return super(RestaurantFloor, self).write(vals)
class ConverterTest(models.Model): _name = 'web_editor.converter.test' _description = 'Web Editor Converter Test' # disable translation export for those brilliant field labels and values _translate = False char = fields.Char() integer = fields.Integer() float = fields.Float() numeric = fields.Float(digits=(16, 2)) many2one = fields.Many2one('web_editor.converter.test.sub') binary = fields.Binary(attachment=False) date = fields.Date() datetime = fields.Datetime() selection_str = fields.Selection( [ ('A', "Qu'il n'est pas arrivé à Toronto"), ('B', "Qu'il était supposé arriver à Toronto"), ('C', "Qu'est-ce qu'il fout ce maudit pancake, tabernacle ?"), ('D', "La réponse D"), ], string=u"Lorsqu'un pancake prend l'avion à destination de Toronto et " u"qu'il fait une escale technique à St Claude, on dit:") html = fields.Html() text = fields.Text()
class test_model(models.Model): _name = 'test_converter.test_model' _description = 'Test Converter Model' char = fields.Char() integer = fields.Integer() float = fields.Float() numeric = fields.Float(digits=(16, 2)) many2one = fields.Many2one('test_converter.test_model.sub', group_expand='_gbf_m2o') binary = fields.Binary(attachment=False) date = fields.Date() datetime = fields.Datetime() selection_str = fields.Selection( [ ('A', u"Qu'il n'est pas arrivé à Toronto"), ('B', u"Qu'il était supposé arriver à Toronto"), ('C', u"Qu'est-ce qu'il fout ce maudit pancake, tabernacle ?"), ('D', u"La réponse D"), ], string=u"Lorsqu'un pancake prend l'avion à destination de Toronto et " u"qu'il fait une escale technique à St Claude, on dit:") html = fields.Html() text = fields.Text() # `base` module does not contains any model that implement the functionality # `group_expand`; test this feature here... @api.model def _gbf_m2o(self, subs, domain, order): sub_ids = subs._search([], order=order, access_rights_uid=SUPERUSER_ID) return subs.browse(sub_ids)
class BaseLanguageExport(models.TransientModel): _name = "base.language.export" @api.model def _get_languages(self): langs = self.env['res.lang'].search([('translatable', '=', True)]) return [(NEW_LANG_KEY, _('New Language (Empty translation template)'))] + \ [(lang.code, lang.name) for lang in langs] name = fields.Char('File Name', readonly=True) lang = fields.Selection(_get_languages, string='Language', required=True, default=NEW_LANG_KEY) format = fields.Selection([('csv', 'CSV File'), ('po', 'PO File'), ('tgz', 'TGZ Archive')], string='File Format', required=True, default='csv') modules = fields.Many2many('ir.module.module', 'rel_modules_langexport', 'wiz_id', 'module_id', string='Apps To Export', domain=[('state', '=', 'installed')]) data = fields.Binary('File', readonly=True) state = fields.Selection( [('choose', 'choose'), ('get', 'get')], # choose language or get the file default='choose') @api.multi def act_getfile(self): this = self[0] lang = this.lang if this.lang != NEW_LANG_KEY else False mods = sorted(this.mapped('modules.name')) or ['all'] with contextlib.closing(io.BytesIO()) as buf: tools.trans_export(lang, mods, buf, this.format, self._cr) out = base64.encodestring(buf.getvalue()) filename = 'new' if lang: filename = tools.get_iso_codes(lang) elif len(mods) == 1: filename = mods[0] extension = this.format if not lang and extension == 'po': extension = 'pot' name = "%s.%s" % (filename, extension) this.write({'state': 'get', 'data': out, 'name': name}) return { 'type': 'ir.actions.act_window', 'res_model': 'base.language.export', 'view_mode': 'form', 'view_type': 'form', 'res_id': this.id, 'views': [(False, 'form')], 'target': 'new', }
class DatabaseDataModel(models.Model): _name = 'muk_dms.data_database' _description = 'Database Data Model' _inherit = 'muk_dms.data' #---------------------------------------------------------- # Database #---------------------------------------------------------- data = fields.Binary(string="Content") #---------------------------------------------------------- # Abstract Implementation #---------------------------------------------------------- def type(self): return "database" def content(self): return self.data def update(self, values): if 'content' in values: self.data = values['content'] def delete(self): self.file = None
class VisitorDetails(models.Model): _name = 'fo.visitor' name = fields.Char(string="Visitor", required=True) visitor_image = fields.Binary(string='Image', attachment=True) street = fields.Char(string="Street") street2 = fields.Char(string="Street2") zip = fields.Char(change_default=True) city = fields.Char() state_id = fields.Many2one("res.country.state", string='State', ondelete='restrict') country_id = fields.Many2one('res.country', string='Country', ondelete='restrict') phone = fields.Char(string="Phone", required=True) email = fields.Char(string="Email", required=True) id_proof = fields.Many2one('id.proof', string="ID Proof") id_proof_no = fields.Char(string="ID Number", help='Id proof number') company_info = fields.Many2one('res.partner', string="Company", help='Visiting persons company details') visit_count = fields.Integer(compute='_no_visit_count', string='# Visits') _sql_constraints = [ ('field_uniq_email_and_id_proof', 'unique (email,id_proof)', "Please give the correct data !"), ] @api.multi def _no_visit_count(self): data = self.env['fo.visit'].search([('visitor', '=', self.ids), ('state', '!=', 'cancel')]).ids self.visit_count = len(data)
class plm_spareChoseLanguage(osv.osv.osv_memory): _name = "plm.sparechoselanguage" _description = "Module for extending the functionality of printing spare_bom reports in a multi language environment" @api.v8 def getInstalledLanguage(self): """ get installed language """ out = [] modobj = self.env['res.lang'] for objBrowse in modobj.search([]): out.append((objBrowse.code, objBrowse.name)) return out @api.multi def print_report(self): self.ensure_one() lang = self.lang if lang: modobj = self.env['ir.module.module'] mids = modobj.search([('state', '=', 'installed')]) if not mids: raise UserError("Language not Installed") reportName = 'plm_spare.report_product_product_spare_parts_pdf' if self.onelevel: reportName = 'plm_spare.report_product_product_spare_parts_pdf_one' productProductId = self.env.context.get('active_id') newContext = self.env.context.copy() newContext['lang'] = lang stream, fileExtention = self.env.ref(reportName).sudo( ).with_context(newContext).render_qweb_pdf(productProductId) self.datas = base64.encodestring(stream) tProductProduct = self.env['product.product'] brwProduct = tProductProduct.browse(productProductId) fileName = brwProduct.name + "_" + lang + "_manual." + fileExtention self.datas_name = fileName return { 'context': self.env.context, 'view_type': 'form', 'view_mode': 'form', 'res_model': plm_spareChoseLanguage._name, 'res_id': self.id, 'view_id': False, 'type': 'ir.actions.act_window', 'target': 'new', } UserError(_("Select a language")) lang = fields.Selection(getInstalledLanguage, 'Language', required=True) onelevel = fields.Boolean( 'One Level', help="If you check this box, the report will be made in one level") datas = fields.Binary("Download", readonly=True) datas_name = fields.Char('Download file name ', size=255, readonly=True) _defaults = {'onelevel': False}
class RestaurantFloor(models.Model): _name = 'restaurant.floor' name = fields.Char( 'Floor Name', required=True, help='An internal identification of the restaurant floor') pos_config_id = fields.Many2one('pos.config', string='Point of Sale') background_image = fields.Binary( 'Background Image', attachment=True, help= 'A background image used to display a floor layout in the point of sale interface' ) background_color = fields.Char( 'Background Color', help= 'The background color of the floor layout, (must be specified in a html-compatible format)', default='rgb(210, 210, 210)') table_ids = fields.One2many('restaurant.table', 'floor_id', string='Tables', help='The list of tables in this floor') sequence = fields.Integer('Sequence', help='Used to sort Floors', default=1)
class RepairOrder(models.Model): _inherit = 'repair.order' l10n_de_template_data = fields.Binary( compute='_compute_l10n_de_template_data') l10n_de_document_title = fields.Char( compute='_compute_l10n_de_document_title') def _compute_l10n_de_template_data(self): for record in self: record.l10n_de_template_data = data = [] if record.product_id: data.append((_("Product to Repair"), record.product_id.name)) if record.lot_id: data.append((_("Lot/Serial Number"), record.lot_id.name)) if record.guarantee_limit: data.append((_("Warranty"), format_date(self.env, record.guarantee_limit))) data.append( (_("Printing Date"), format_date(self.env, fields.Date.today()))) def _compute_l10n_de_document_title(self): for record in self: if record.state == 'draft': record.l10n_de_document_title = _("Repair Order") else: record.l10n_de_document_title = _("Repair Quotation")
class AdvancedPackView(osv.osv.osv_memory): _name = 'pack_and_go_view' @api.model def _getComponentDescription(self): for row in self: row.comp_description = row.component_id.description @api.model def _getDocumentDescription(self): for row in self: row.document_description = row.document_id.description @api.model def _getDocumentFileName(self): for row in self: row.doc_file_name = row.document_id.datas_fname component_id = fields.Many2one('product.product', _('Component')) document_id = fields.Many2one('plm.document', _('Document')) comp_rev = fields.Integer(_('Component Revision')) comp_description = fields.Char(compute='_getComponentDescription') doc_rev = fields.Integer(_('Document Revision')) document_description = fields.Char(compute='_getDocumentDescription') doc_file_name = fields.Char(compute='_getDocumentFileName') preview = fields.Binary(_('Preview Content')) # Don't change keys because are used in a lower check in this file doc_type = fields.Selection([('2d', _('2D')), ('3d', _('3D')), ('pdf', _('PDF')), ], _('Document Type')) available_types = fields.Many2one('pack_and_go_types', _('Types')) pack_and_go_id = fields.Many2one('pack.and_go', _('Pack and go id'))
class Users(models.Model): _inherit = 'res.users' print_facsimile = fields.Boolean(related='company_id.print_facsimile') facsimile = fields.Binary("Facsimile") # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
class ProductImage(models.Model): _name = 'product.image' name = fields.Char('Name') image = fields.Binary('Image', attachment=True) product_tmpl_id = fields.Many2one('product.template', 'Related Product', copy=True)
class BaseLanguageImport(models.TransientModel): _name = "base.language.import" _description = "Language Import" name = fields.Char('Language Name', required=True) code = fields.Char('ISO Code', size=6, required=True, help="ISO Language and Country code, e.g. en_US") data = fields.Binary('File', required=True, attachment=False) filename = fields.Char('File Name', required=True) overwrite = fields.Boolean( 'Overwrite Existing Terms', default=True, help= "If you enable this option, existing translations (including custom ones) " "will be overwritten and replaced by those in this file") def import_lang(self): this = self[0] with TemporaryFile('wb+') as buf: try: buf.write(base64.decodebytes(this.data)) # now we determine the file format buf.seek(0) fileformat = os.path.splitext(this.filename)[-1][1:].lower() Lang = self.env["res.lang"] lang = Lang._activate_lang(self.code) or Lang._create_lang( self.code, lang_name=self.name) tools.trans_load_data(this._cr, buf, fileformat, this.code, overwrite=self.overwrite) except ProgrammingError as e: _logger.exception( 'File unsuccessfully imported, due to a malformed file.') with closing(sql_db.db_connect( self._cr.dbname).cursor()) as cr: raise UserError( _('File %r not imported due to a malformed file.\n\n' 'This issue can be caused by duplicates entries who are referring to the same field. ' 'Please check the content of the file you are trying to import.\n\n' 'Technical Details:\n%s') % (self.filename, tools.ustr(e))) except Exception as e: _logger.exception( 'File unsuccessfully imported, due to format mismatch.') raise UserError( _('File %r not imported due to format mismatch or a malformed file.' ' (Valid formats are .csv, .po, .pot)\n\nTechnical Details:\n%s') % \ (this.filename, tools.ustr(e)) ) return True
class SlideResource(models.Model): _name = 'slide.slide.resource' _description = "Additional resource for a particular slide" slide_id = fields.Many2one('slide.slide', required=True, ondelete='cascade') name = fields.Char('Name', required=True) data = fields.Binary('Resource')
class PurchaseOrder(models.Model): _inherit = 'purchase.order' l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data') l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title') l10n_de_addresses = fields.Binary(compute='_compute_l10n_de_addresses') def _compute_l10n_de_template_data(self): for record in self: record.l10n_de_template_data = data = [] if record.state == 'draft': data.append((_("Request for Quotation No."), record.name)) elif record.state in ['sent', 'to approve', 'purchase', 'done']: data.append((_("Purchase Order No."), record.name)) elif record.state == 'cancel': data.append((_("Cancelled Purchase Order No."), record.name)) if record.user_id: data.append((_("Purchase Representative"), record.user_id.name)) if record.partner_ref: data.append((_("Order Reference"), record.partner_ref)) if record.date_order: data.append((_("Order Date"), format_date(self.env, record.date_order))) if record.incoterm_id: data.append((_("Incoterm"), record.incoterm_id.code)) def _compute_l10n_de_document_title(self): for record in self: if record.state == 'draft': record.l10n_de_document_title = _("Request for Quotation") elif record.state in ['sent', 'to approve', 'purchase', 'done']: record.l10n_de_document_title = _("Purchase Order") elif record.state == 'cancel': record.l10n_de_document_title = _("Cancelled Purchase Order") def _compute_l10n_de_addresses(self): for record in self: record.l10n_de_addresses = data = [] if record.dest_address_id: data.append((_("Shipping Address:"), record.dest_address_id)) elif 'picking_type_id' in record._fields and record.picking_type_id.warehouse_id: data.append((_("Shipping Address:"), record.picking_type_id.warehouse_id.partner_id))
class TOTPWizard(models.TransientModel): _name = 'auth_totp.wizard' _description = "Two-Factor Setup Wizard" user_id = fields.Many2one('res.users', required=True, readonly=True) secret = fields.Char(required=True, readonly=True) url = fields.Char(store=True, readonly=True, compute='_compute_qrcode') qrcode = fields.Binary( attachment=False, store=True, readonly=True, compute='_compute_qrcode', ) code = fields.Char(string="Verification Code", size=7) @api.depends('user_id.login', 'user_id.company_id.display_name', 'secret') def _compute_qrcode(self): # TODO: make "issuer" configurable through config parameter? global_issuer = request and request.httprequest.host.split(':', 1)[0] for w in self: issuer = global_issuer or w.user_id.company_id.display_name w.url = url = werkzeug.urls.url_unparse(( 'otpauth', 'totp', werkzeug.urls.url_quote(f'{issuer}:{w.user_id.login}', safe=':'), werkzeug.urls.url_encode({ 'secret': compress(w.secret), 'issuer': issuer, # apparently a lowercase hash name is anathema to google # authenticator (error) and passlib (no token) 'algorithm': ALGORITHM.upper(), 'digits': DIGITS, 'period': TIMESTEP, }), '' )) data = io.BytesIO() import qrcode qrcode.make(url.encode(), box_size=4).save(data, optimise=True, format='PNG') w.qrcode = base64.b64encode(data.getvalue()).decode() @check_identity def enable(self): try: c = int(compress(self.code)) except ValueError: raise UserError(_("The verification code should only contain numbers")) if self.user_id._totp_try_setting(self.secret, c): self.secret = '' # empty it, because why keep it until GC? return { 'type': 'ir.actions.client', 'tag': 'display_notification', 'params': { 'type': 'success', 'message': _("Two-factor authentication is now enabled."), 'next': {'type': 'ir.actions.act_window_close'}, } } raise UserError(_('Verification failed, please double-check the 6-digit code'))
class SaleOrder(models.Model): _inherit = 'sale.order' l10n_de_template_data = fields.Binary(compute='_compute_l10n_de_template_data') l10n_de_document_title = fields.Char(compute='_compute_l10n_de_document_title') l10n_de_addresses = fields.Binary(compute='_compute_l10n_de_addresses') def _compute_l10n_de_template_data(self): for record in self: record.l10n_de_template_data = data = [] if record.state in ('draft', 'sent'): if record.name: data.append((_("Quotation No."), record.name)) if record.date_order: data.append((_("Quotation Date"), format_date(self.env, record.date_order))) if record.validity_date: data.append((_("Expiration"), format_date(self.env, record.validity_date))) else: if record.name: data.append((_("Order No."), record.name)) if record.date_order: data.append((_("Order Date"), format_date(self.env, record.date_order))) if record.client_order_ref: data.append((_('Customer Reference'), record.client_order_ref)) if record.user_id: data.append((_("Salesperson"), record.user_id.name)) def _compute_l10n_de_document_title(self): for record in self: if record.state in ('draft', 'sent'): record.l10n_de_document_title = _('Quotation') else: record.l10n_de_document_title = _('Sales Order') def _compute_l10n_de_addresses(self): for record in self: record.l10n_de_addresses = data = [] if record.partner_shipping_id == record.partner_invoice_id: data.append((_("Invoicing and Shipping Address:"), record.partner_shipping_id)) else: data.append((_("Shipping Address:"), record.partner_shipping_id)) data.append((_("Invoicing Address:"), record.partner_invoice_id))
class CustomerInfo(models.Model): _name = 'customer.info' @api.multi def button_done(self): for rec in self: rec.write({'state': 'done'}) @api.multi def button_cancel(self): for rec in self: rec.write({'state': 'cancel'}) @api.multi def button_draft(self): for rec in self: rec.write({'state': 'draft'}) # _sql_constraints = [ # ('customer_info_customer_pan', 'UNIQUE (customer_pan)', 'Pan No. must be unique!'), # ('customer_info_customer_aadhar', 'UNIQUE (customer_aadhar)', 'Aadhar No. must be unique!'), # ] total_bank = fields.Char("No. Bank") name = fields.Char("Name") date = fields.Date("Date") customer_pan = fields.Char("Pan No") customer_aadhar = fields.Char("Aadhar Card No") customer_mobile = fields.Integer("Mobile No", size=12) customer_email = fields.Char("Email ID") customer_image = fields.Binary("Image") customer_bank_ids = fields.Many2many('bank.info', string="Bank Name") bank_customer_id = fields.Many2one('bank.info', string="Bank") state = fields.Selection([ ('draft', 'Draft'), ('done', 'Accept'), ('cancel', 'Reject'), ], default='draft') def compute_customer(self): for number in self: number.total_bank = len(number.customer_bank_ids) @api.multi def create_bank(self, ): return { 'name': 'Bank Info', 'view_type': 'form', 'view_mode': 'tree', 'type': 'ir.actions.act_window', 'res_model': 'bank.info', 'domain': [('name', '=', 'name')], }