def _check_employee_related_user(self): for badge_user in self: if badge_user.employee_id not in badge_user.user_id.employee_ids: raise ValidationError( _('The selected employee does not correspond to the selected user.' ))
def copy(self, values): raise UserError(_("Cannot duplicate configuration!"), "")
def get_import_templates(self): return [{ 'label': _('Import Template for Students'), 'template': '/openeagleedu_core/static/xls/op_student.xls' }]
def create(self, vals): """Overriding the create method and assigning the the sequence for the record""" if vals.get('application_no', _('New')) == _('New'): vals['application_no'] = self.env['ir.sequence'].next_by_code('eagleedu.application') or _('New') res = super(EagleeduApplication, self).create(vals) return res
def _constraint_percentage(self): for record in self: if not (0.0 < record.percentage <= 100.0): raise UserError(_("Percentage must be between 0 and 100"))
def _generate_report_content(self, workbook, report): if not report.show_move_line_details: # For each account for account in report.account_ids: # Write account title self.write_array_title(account.code + ' - ' + account.name) # Display array header for partners lines self.write_array_header() # Display partner lines for partner in account.partner_ids: self.write_line(partner.line_ids) # Display account lines self.write_account_footer(report, account, _('Total'), 'field_footer_total', self.format_header_right, self.format_header_amount, False) self.write_account_footer(report, account, _('Percents'), 'field_footer_percent', self.format_right_bold_italic, self.format_percent_bold_italic, True) # 2 lines break self.row_pos += 2 else: # For each account for account in report.account_ids: # Write account title self.write_array_title(account.code + ' - ' + account.name) # For each partner for partner in account.partner_ids: # Write partner title self.write_array_title(partner.name) # Display array header for move lines self.write_array_header() # Display account move lines for line in partner.move_line_ids: self.write_line(line) # Display ending balance line for partner self.write_ending_balance(partner.line_ids) # Line break self.row_pos += 1 # Display account lines self.write_account_footer(report, account, _('Total'), 'field_footer_total', self.format_header_right, self.format_header_amount, False) self.write_account_footer(report, account, _('Percents'), 'field_footer_percent', self.format_right_bold_italic, self.format_percent_bold_italic, True) # 2 lines break self.row_pos += 2
def _check_schedule_date(self): for scheduler in self: if scheduler.schedule_date < fields.Datetime.now(): raise ValidationError(_('Please select a date equal/or greater than the current date.'))
def _compute_dashboard_button_name(self): website_teams = self.filtered(lambda team: team.team_type == 'website' and not team.use_quotations) website_teams.update({'dashboard_button_name': _("Online Sales")}) super(CrmTeam, self - website_teams)._compute_dashboard_button_name()
def _check_allow_timesheet(self): for project in self: if project.allow_timesheets and not project.analytic_account_id: raise ValidationError( _('To allow timesheet, your project %s should have an analytic account set.' % (project.name, )))
def install_from_urls(self, urls): if not self.env.user.has_group('base.group_system'): raise AccessDenied() # One-click install is opt-in - cfr Issue #15225 ad_dir = tools.config.addons_data_dir if not os.access(ad_dir, os.W_OK): msg = (_( "Automatic install of downloaded Apps is currently disabled." ) + "\n\n" + _( "To enable it, make sure this directory exists and is writable on the server:" ) + "\n%s" % ad_dir) _logger.warning(msg) raise UserError(msg) apps_server = urls.url_parse(self.get_apps_server()) OPENERP = eagle.release.product_name.lower() tmp = tempfile.mkdtemp() _logger.debug('Install from url: %r', urls) try: # 1. Download & unzip missing modules for module_name, url in urls.items(): if not url: continue # nothing to download, local version is already the last one up = urls.url_parse(url) if up.scheme != apps_server.scheme or up.netloc != apps_server.netloc: raise AccessDenied() try: _logger.info('Downloading module `%s` from OpenERP Apps', module_name) response = requests.get(url) response.raise_for_status() content = response.content except Exception: _logger.exception('Failed to fetch module %s', module_name) raise UserError( _('The `%s` module appears to be unavailable at the moment, please try again later.' ) % module_name) else: zipfile.ZipFile(io.BytesIO(content)).extractall(tmp) assert os.path.isdir(os.path.join(tmp, module_name)) # 2a. Copy/Replace module source in addons path for module_name, url in urls.items(): if module_name == OPENERP or not url: continue # OPENERP is special case, handled below, and no URL means local module module_path = modules.get_module_path(module_name, downloaded=True, display_warning=False) bck = backup(module_path, False) _logger.info('Copy downloaded module `%s` to `%s`', module_name, module_path) shutil.move(os.path.join(tmp, module_name), module_path) if bck: shutil.rmtree(bck) # 2b. Copy/Replace server+base module source if downloaded if urls.get(OPENERP): # special case. it contains the server and the base module. # extract path is not the same base_path = os.path.dirname(modules.get_module_path('base')) # copy all modules in the SERVER/eagle/addons directory to the new "eagle" module (except base itself) for d in os.listdir(base_path): if d != 'base' and os.path.isdir(os.path.join( base_path, d)): destdir = os.path.join(tmp, OPENERP, 'addons', d) # XXX 'eagle' subdirectory ? shutil.copytree(os.path.join(base_path, d), destdir) # then replace the server by the new "base" module server_dir = tools.config['root_path'] # XXX or dirname() bck = backup(server_dir) _logger.info('Copy downloaded module `eagle` to `%s`', server_dir) shutil.move(os.path.join(tmp, OPENERP), server_dir) #if bck: # shutil.rmtree(bck) self.update_list() with_urls = [ module_name for module_name, url in urls.items() if url ] downloaded = self.search([('name', 'in', with_urls)]) installed = self.search([('id', 'in', downloaded.ids), ('state', '=', 'installed')]) to_install = self.search([('name', 'in', list(urls)), ('state', '=', 'uninstalled')]) post_install_action = to_install.button_immediate_install() if installed or to_install: # in this case, force server restart to reload python code... self._cr.commit() eagle.service.server.restart() return { 'type': 'ir.actions.client', 'tag': 'home', 'params': { 'wait': True }, } return post_install_action finally: shutil.rmtree(tmp)
def _check_regex_url(self): try: if self.regex_url: re.compile(self.regex_url) except Exception: raise ValidationError(_('Enter Valid Regex.'))
def button_uninstall(self): if 'base' in self.mapped('name'): raise UserError(_("The `base` module cannot be uninstalled")) deps = self.downstream_dependencies() (self + deps).write({'state': 'to remove'}) return dict(ACTION_DICT, name=_('Uninstall'))
def button_install(self): # domain to select auto-installable (but not yet installed) modules auto_domain = [('state', '=', 'uninstalled'), ('auto_install', '=', True)] # determine whether an auto-install module must be installed: # - all its dependencies are installed or to be installed, # - at least one dependency is 'to install' install_states = frozenset(('installed', 'to install', 'to upgrade')) def must_install(module): states = set(dep.state for dep in module.dependencies_id) return states <= install_states and 'to install' in states modules = self while modules: # Mark the given modules and their dependencies to be installed. modules._state_update('to install', ['uninstalled']) # Determine which auto-installable modules must be installed. modules = self.search(auto_domain).filtered(must_install) # the modules that are installed/to install/to upgrade install_mods = self.search([('state', 'in', list(install_states))]) # check individual exclusions install_names = {module.name for module in install_mods} for module in install_mods: for exclusion in module.exclusion_ids: if exclusion.name in install_names: msg = _('Modules "%s" and "%s" are incompatible.') raise UserError( msg % (module.shortdesc, exclusion.exclusion_id.shortdesc)) # check category exclusions def closure(module): todo = result = module while todo: result |= todo todo = todo.mapped('dependencies_id.depend_id') return result exclusives = self.env['ir.module.category'].search([('exclusive', '=', True)]) for category in exclusives: # retrieve installed modules in category and sub-categories categories = category.search([('id', 'child_of', category.ids)]) modules = install_mods.filtered( lambda mod: mod.category_id in categories) # the installation is valid if all installed modules in categories # belong to the transitive dependencies of one of them if modules and not any(modules <= closure(module) for module in modules): msg = _( 'You are trying to install incompatible modules in category "%s":' ) labels = dict(self.fields_get(['state'])['state']['selection']) raise UserError("\n".join([msg % category.name] + [ "- %s (%s)" % (module.shortdesc, labels[module.state]) for module in modules ])) return dict(ACTION_DICT, name=_('Install'))
def _default_content(self): return ''' <p class="o_default_snippet_text">''' + _( "Start writing here...") + '''</p>
def _get_report_name(self, report): report_name = _('Aged Partner Balance') return self._get_report_complete_name(report, report_name)
def _check_user_impersonification(self, user_id=None): if (user_id and request.env.uid != user_id and not request.env.user.has_group('lunch.group_lunch_manager')): raise AccessError(_('You are trying to impersonate another user, but this can only be done by a lunch manager'))
def _get_report_columns(self, report): if not report.show_move_line_details: return { 0: { 'header': _('Partner'), 'field': 'partner', 'width': 70 }, 1: { 'header': _('Residual'), 'field': 'amount_residual', 'field_footer_total': 'cumul_amount_residual', 'type': 'amount', 'width': 14 }, 2: { 'header': _('Current'), 'field': 'current', 'field_footer_total': 'cumul_current', 'field_footer_percent': 'percent_current', 'type': 'amount', 'width': 14 }, 3: { 'header': _(u'Age ≤ 30 d.'), 'field': 'age_30_days', 'field_footer_total': 'cumul_age_30_days', 'field_footer_percent': 'percent_age_30_days', 'type': 'amount', 'width': 14 }, 4: { 'header': _(u'Age ≤ 60 d.'), 'field': 'age_60_days', 'field_footer_total': 'cumul_age_60_days', 'field_footer_percent': 'percent_age_60_days', 'type': 'amount', 'width': 14 }, 5: { 'header': _(u'Age ≤ 90 d.'), 'field': 'age_90_days', 'field_footer_total': 'cumul_age_90_days', 'field_footer_percent': 'percent_age_90_days', 'type': 'amount', 'width': 14 }, 6: { 'header': _(u'Age ≤ 120 d.'), 'field': 'age_120_days', 'field_footer_total': 'cumul_age_120_days', 'field_footer_percent': 'percent_age_120_days', 'type': 'amount', 'width': 14 }, 7: { 'header': _('Older'), 'field': 'older', 'field_footer_total': 'cumul_older', 'field_footer_percent': 'percent_older', 'type': 'amount', 'width': 14 }, } return { 0: { 'header': _('Date'), 'field': 'date', 'width': 11 }, 1: { 'header': _('Entry'), 'field': 'entry', 'width': 18 }, 2: { 'header': _('Journal'), 'field': 'journal', 'width': 8 }, 3: { 'header': _('Account'), 'field': 'account', 'width': 9 }, 4: { 'header': _('Partner'), 'field': 'partner', 'width': 25 }, 5: { 'header': _('Ref - Label'), 'field': 'label', 'width': 40 }, 6: { 'header': _('Due date'), 'field': 'date_due', 'width': 11 }, 7: { 'header': _('Residual'), 'field': 'amount_residual', 'field_footer_total': 'cumul_amount_residual', 'field_final_balance': 'amount_residual', 'type': 'amount', 'width': 14 }, 8: { 'header': _('Current'), 'field': 'current', 'field_footer_total': 'cumul_current', 'field_footer_percent': 'percent_current', 'field_final_balance': 'current', 'type': 'amount', 'width': 14 }, 9: { 'header': _(u'Age ≤ 30 d.'), 'field': 'age_30_days', 'field_footer_total': 'cumul_age_30_days', 'field_footer_percent': 'percent_age_30_days', 'field_final_balance': 'age_30_days', 'type': 'amount', 'width': 14 }, 10: { 'header': _(u'Age ≤ 60 d.'), 'field': 'age_60_days', 'field_footer_total': 'cumul_age_60_days', 'field_footer_percent': 'percent_age_60_days', 'field_final_balance': 'age_60_days', 'type': 'amount', 'width': 14 }, 11: { 'header': _(u'Age ≤ 90 d.'), 'field': 'age_90_days', 'field_footer_total': 'cumul_age_90_days', 'field_footer_percent': 'percent_age_90_days', 'field_final_balance': 'age_90_days', 'type': 'amount', 'width': 14 }, 12: { 'header': _(u'Age ≤ 120 d.'), 'field': 'age_120_days', 'field_footer_total': 'cumul_age_120_days', 'field_footer_percent': 'percent_age_120_days', 'field_final_balance': 'age_120_days', 'type': 'amount', 'width': 14 }, 13: { 'header': _('Older'), 'field': 'older', 'field_footer_total': 'cumul_older', 'field_footer_percent': 'percent_older', 'field_final_balance': 'older', 'type': 'amount', 'width': 14 }, }
def unlink(self): """Return warning if the Record is in done state""" for rec in self: if rec.state == 'done': raise ValidationError(_("Cannot delete Record in Done state"))
class EagleeduHuman(models.Model): _name = 'eagleedu.student' # _inherit = 'res.partner' # _inherits = {'res.partner': 'image_1920'} _inherits = {'res.partner': 'partner_id'} _inherit = 'image.mixin' _description = 'This the application for Human' _order = 'id desc' _rec_name = 'name' @api.model def name_search(self, name, args=None, operator='ilike', limit=100): if name: recs = self.search([('name', operator, name)] + (args or []), limit=limit) if not recs: recs = self.search([('adm_no', operator, name)] + (args or []), limit=limit) if not recs: recs = self.search([('application_no', operator, name)] + (args or []), limit=limit) return recs.name_get() return super(EagleeduHuman, self).name_search(name, args=args, operator=operator, limit=limit) @api.model def create(self, vals): """Over riding the create method to assign sequence for the newly creating the record""" vals['adm_no'] = self.env['ir.sequence'].next_by_code( 'eagleedu.student') res = super(EagleeduHuman, self).create(vals) return res # @api.model # def create_partener(self, partner): # if partner.get('image_1920'): # partner['image_1920'] = partner['image_1920'] # partner_id = partner.pop('id', False) # if partner_id: # Modifying existing partner # self.browse(partner_id).write(partner) # else: # partner['lang'] = self.env.user.lang # partner_id = self.create(partner).id # return partner_id partner_id = fields.Many2one('res.partner', string='Partner', ondelete="cascade") adm_no = fields.Char(string="Admission No.", readonly=True) image_1920 = fields.Image(string='Image', help="Provide the image of the Human") application_no = fields.Char(string='Application No', required=True, copy=False, readonly=True, index=True, default=lambda self: _('New')) company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.user.company_id) academic_year = fields.Many2one('eagleedu.academic.year', string="Year Information", help="Select Year") st_name_b = fields.Char(string='Human Bangla Name') date_of_birth = fields.Date(string="Date Of birth") st_gender = fields.Selection([('male', 'Male'), ('female', 'Female'), ('other', 'Other')], string='Gender', required=False, track_visibility='onchange') st_blood_group = fields.Selection([('a+', 'A+'), ('a-', 'A-'), ('b+', 'B+'), ('o+', 'O+'), ('o-', 'O-'), ('ab-', 'AB-'), ('ab+', 'AB+')], string='Blood Group', track_visibility='onchange') st_passport_no = fields.Char(string="Passport No.", help="Proud to say my father is", required=False) application_no = fields.Char(string='Registration No', required=True, copy=False, readonly=True, index=True, default=lambda self: _('New')) registration_date = fields.Datetime( 'Registration Date', default=lambda self: fields.datetime.now( )) # , default=fields.Datetime.now, required=True st_father_name = fields.Char(string="Father's Name", help="Proud to say my father is", required=False) st_father_name_b = fields.Char(string="বাবার নাম", help="Proud to say my father is") st_father_occupation = fields.Char(string="Father's Occupation", help="father Occupation") st_father_email = fields.Char(string="Father's Email", help="father Occupation") father_mobile = fields.Char(string="Father's Mobile No", help="Father's Mobile No") st_mother_name = fields.Char(string="Mother's Name", help="Proud to say my mother is", required=False) st_mother_name_b = fields.Char(string="মা এর নাম", help="Proud to say my mother is") st_mother_occupation = fields.Char(string="Mother Occupation", help="Proud to say my mother is") st_mother_email = fields.Char(string="Mother Email", help="Proud to say my mother is") mother_mobile = fields.Char(string="Mother's Mobile No", help="mother's Mobile No") house_no = fields.Char(string='House No.', help="Enter the House No.") road_no = fields.Char(string='Area/Road No.', help="Enter the Area or Road No.") post_office = fields.Char(string='Post Office', help="Enter the Post Office Name") city = fields.Char(string='City', help="Enter the City name") bd_division_id = fields.Many2one('eagleedu.bddivision', string='Division') country_id = fields.Many2one('res.country', string='Country', ondelete='restrict', default=19) if_same_address = fields.Boolean(string="Permanent Address same as above", default=True) per_village = fields.Char(string='Village Name', help="Enter the Village Name") per_po = fields.Char(string='Post Office Name', help="Enter the Post office Name ") per_ps = fields.Char(string='Police Station', help="Enter the Police Station Name") per_dist_id = fields.Many2one('eagleedu.bddistrict', string='District', help="Enter the City of District name") per_bd_division_id = fields.Many2one('eagleedu.bddivision', string='Division/Province', help="Enter the Division name") per_country_id = fields.Many2one('res.country', string='Country', ondelete='restrict', default=19) guardian_name = fields.Char(string="Guardian's Name", help="Proud to say my guardian is") guardian_mobile = fields.Char(string="Guardian's Mobile") religious_id = fields.Many2one('eagleedu.religious', string="Religious", help="My Religion is ") student_id = fields.Char('Human Id') email = fields.Char(string="Email", help="Enter E-mail id for contact purpose") phone = fields.Char(string="Phone", help="Enter Phone no. for contact purpose") mobile = fields.Char(string="Mobile", help="Enter Mobile num for contact purpose") nationality = fields.Many2one('res.country', string='Nationality', ondelete='restrict', default=19, help="Select the Nationality") state = fields.Selection([('draft', 'Draft'), ('approve', 'Approve'), ('done', 'Done')], string='Status', required=True, default='draft', track_visibility='onchange') description_sale = fields.Text(string="Description", help="Enter description purpose") def send_to_publish(self): """Return the state to done if the documents are perfect""" for rec in self: rec.write({'state': 'approve'}) def create_human(self): """Create student from the application and data and return the student""" for rec in self: values = { 'name': rec.name, 'image_1920': rec.image_1920, 'application_no': rec.id, 'st_father_name': rec.st_father_name, 'st_mother_name': rec.st_mother_name, 'mobile': rec.mobile, 'email': rec.email, 'st_gender': rec.st_gender, 'date_of_birth': rec.date_of_birth, 'st_blood_group': rec.st_blood_group, 'nationality': rec.nationality.id, 'house_no': rec.house_no, 'road_no': rec.road_no, 'post_office': rec.post_office, 'city': rec.city, 'bd_division_id': rec.bd_division_id.id, 'country_id': rec.country_id.id, 'per_village': rec.per_village, 'per_po': rec.per_po, 'per_ps': rec.per_ps, 'per_dist_id': rec.per_dist_id.id, 'per_bd_division_id': rec.per_bd_division_id.id, 'per_country_id': rec.per_country_id.id, 'religious_id': rec.religious_id.id, 'application_no': rec.application_no, 'description_sale': rec.description_sale, } student = self.env['product.template'].create(values) rec.write({ 'state': 'done', }) return { 'name': _('Human'), 'view_type': 'form', 'view_mode': 'form', 'res_model': 'product.template', 'type': 'ir.actions.act_window', 'res_id': student.id, 'context': self.env.context }
def copy_data(self, default=None): name = _("%s (copy)") % (self.name) default = dict(default or {}, name=name) return super(Inventory, self).copy_data(default)
def submit_fee_enhancement(self): print '==================submit fee enhancement===================' """ this method is used to manualy subbimit fee. ------------------------------------------------- :return: """ active_id = self._context['active_id'] brw_reg = self.env['registration'].browse(active_id) bankname = self.bank_name sdate = self.cheque_start_date or False exdate = self.cheque_expiry_date or False chk_num = self.chk_num or False party_name = self.party_name or False if brw_reg.state == 'reg': journal_id = self.journal_id.id brw_reg.reg_pay_manually(journal_id, bank_name=bankname, chk_num=chk_num, sdate=sdate, exdate=exdate, cheque_pay=self.journal_id.is_cheque, party_name=party_name) if brw_reg.state == 'awaiting_fee': account_payment_obj = self.env['account.payment'] voucher_pool = self.env['account.voucher'] voucher_line_pool = self.env['account.voucher.line'] inv_obj = brw_reg.invoice_id if not inv_obj: #create voucher with advance payment currency_id = self._get_currency() partner_rec = brw_reg.student_id date = time.strftime('%Y-%m-%d') period_id = self._get_period().id account_id = self.journal_id.default_debit_account_id.id total_amount = self.total_fee brw_reg.paid_amount = brw_reg.paid_amount + self.total_fee if brw_reg.next_year_advance_fee_id: order_id = brw_reg.next_year_advance_fee_id.order_id else: order_id = brw_reg.enquiry_no if not partner_rec.property_account_customer_advance: raise except_orm( _('Warning!'), _("Please define advance account of student %s!") % (partner_rec.name)) # voucher_data = { # 'period_id': period_id, # 'account_id': account_id, # 'partner_id': partner_rec.id, # 'journal_id': self.journal_id.id, # 'currency_id': currency_id, # 'reference': order_id, # 'amount': total_amount, # 'type': 'receipt', # 'state': 'draft', # 'pay_now': 'pay_later', # 'name': '', # 'date': time.strftime('%Y-%m-%d'), # 'company_id': 1, # 'tax_id': False, # 'payment_option': 'without_writeoff', # 'comment': _('Write-Off'), # 'cheque_start_date':self.cheque_start_date, # 'cheque_expiry_date':self.cheque_expiry_date, # 'bank_name':self.bank_name, # 'cheque':self.cheque, # 'party_name' :self.party_name, # 'chk_num':self.chk_num, # 'advance_account_id':partner_rec.property_account_customer_advance.id, # # 'invoice_id':inv_obj.id, # } # payment_vals = { 'period_id': period_id, # 'account_id': partner_rec.property_account_customer_advance.id, 'partner_type': 'customer', 'partner_id': partner_rec.id, 'journal_id': self.journal_id.id, # 'reference': order_id, 'amount': total_amount, 'payment_method_id': 1, 'advance_account_id': partner_rec.property_account_customer_advance.id, 'payment_type': 'inbound', } payment_rec = account_payment_obj.create(payment_vals) payment_rec.post_new() # voucher_id = voucher_pool.create(voucher_data) # Add Journal Entries # voucher_id.proforma_voucher() if brw_reg.paid_amount >= brw_reg.fee_computation_ids[ 0].invoice_amount: brw_reg.fee_status = 'academy_fee_pay' else: brw_reg.fee_status = 'academy_fee_partial_pay' if brw_reg.next_year_advance_fee_id: brw_reg.next_year_advance_fee_id.total_paid_amount += total_amount if round(brw_reg.next_year_advance_fee_id.total_amount, 2) <= round( brw_reg.next_year_advance_fee_id. total_paid_amount, 2): brw_reg.next_year_advance_fee_id.state = 'fee_paid' #brw_reg.fee_status = 'academy_fee_pay' elif round( brw_reg.next_year_advance_fee_id.total_paid_amount, 2 ) < round( brw_reg.next_year_advance_fee_id.total_amount, 2 ) and brw_reg.next_year_advance_fee_id.total_paid_amount != 0.00: brw_reg.next_year_advance_fee_id.state = 'fee_partial_paid' #brw_reg.fee_status = 'academy_fee_partial_pay' brw_reg.next_year_advance_fee_id.payment_ids = [ (4, payment_rec.id) ] brw_reg.next_year_advance_fee_id.journal_ids = [ (4, self.journal_id.id) ] brw_reg.next_year_advance_fee_id.journal_id = self.journal_id.id # send mail for advance payment recipt mail_obj = self.env['mail.mail'] email_server = self.env['ir.mail_server'] email_sender = email_server.search([]) ir_model_data = self.env['ir.model.data'] if total_amount >= brw_reg.fee_computation_ids[ 0].invoice_amount: template_id = ir_model_data.get_object_reference( 'edsys_edu', 'email_template_academic_fee_receipt_paid')[1] else: template_id = ir_model_data.get_object_reference( 'edsys_edu', 'email_template_academic_fee_receipt_open')[1] template_rec = self.env['mail.template'].browse(template_id) template_rec.write({ 'email_to': brw_reg.email, 'email_from': email_sender.smtp_user, 'email_cc': '' }) template_rec.send_mail(payment_rec.id, force_send=True)
def unlink(self): for inventory in self: if (inventory.state not in ('draft', 'cancel') and not self.env.context.get(MODULE_UNINSTALL_FLAG, False)): raise UserError(_('You can only delete a draft inventory adjustment. If the inventory adjustment is not done, you can cancel it.')) return super(Inventory, self).unlink()
class EagleeduApplication(models.Model): _name = 'eagleedu.application' _description = 'This is Student Application Form' # _order = 'id desc' _inherit = ['mail.thread'] application_no = fields.Char(string='Application No.', required=True, copy=False, readonly=True, index=True, default=lambda self: _('New')) application_date = fields.Datetime('Application Date', default=lambda self: fields.datetime.now()) # , default=fields.Datetime.now, required=True name = fields.Char(string='Student Name', required=True, help="Enter Name of Student") st_name_b = fields.Char(string='Student Bangla Name') st_image = fields.Binary(string='Image', help="Provide the image of the Student") st_father_name = fields.Char(string="Father's Name", help="Proud to say my father is", required=False) st_father_name_b = fields.Char(string="বাবার নাম", help="Proud to say my father is") st_father_occupation = fields.Char(string="Father's Occupation", help="father Occupation") st_father_email = fields.Char(string="Father's Email", help="father Occupation") father_mobile = fields.Char(string="Father's Mobile No", help="Father's Mobile No") st_mother_name = fields.Char(string="Mother's Name", help="Proud to say my mother is", required=False) st_mother_name_b = fields.Char(string="মা এর নাম", help="Proud to say my mother is") st_mother_occupation = fields.Char(string="Mother Occupation", help="Proud to say my mother is") st_mother_email = fields.Char(string="Mother Email", help="Proud to say my mother is") mother_mobile = fields.Char(string="Mother's Mobile No", help="mother's Mobile No") date_of_birth = fields.Date(string="Date Of birth", help="Enter your DOB") age = fields.Char(compute="get_student_age", string="Age", store=True, help="Enter your DOB") st_gender = fields.Selection([('male', 'Male'), ('female', 'Female'), ('other', 'Other')], string='Gender', required=False, track_visibility='onchange', help="Your Gender is ") st_blood_group = fields.Selection([('a+', 'A+'), ('a-', 'A-'), ('b+', 'B+'), ('o+', 'O+'), ('o-', 'O-'), ('ab-', 'AB-'), ('ab+', 'AB+')], string='Blood Group', track_visibility='onchange', help="Your Blood Group is ") st_passport_no = fields.Char(string="Passport No.", help="Proud to say my father is", required=False) nationality = fields.Many2one('res.country', string='Nationality', ondelete='restrict',default=19, help="Select the Nationality") academic_year = fields.Many2one('eagleedu.academic.year', string='Academic Year', help="Choose Academic year for which the admission is choosing") register_id = fields.Many2one('eagleedu.register', string="Admission Register", required=True, help="Enter the admission register Name") import_id=fields.Many2one('eagleedu.import.previous.student', string="Import Student") # todo all Name in bangla unicode should auto fill and translate to bangla language # for translate in unicode # @api.onchange('name') # def set_st_name_b(self): # self.st_name_b = self.name # # # @api.model # def create(self, vals): # record = super(IrTranslation, self).create(vals) # name = vals.get('name', False) # name of the field to translate # lang = vals.get('lang', False) # creating record for this language # if 'context' in dir(self.env): # cur_lang = self.env.context.get('lang', False) # current used language # if name == 'eagleedu.application,st_father_name_b' and lang == cur_lang: # langs = self.env['ir.translation']._get_languages() # langs = [l[0] for l in langs if l[0] != cur_lang] # installed languages # # for l in langs: # if self.env.eagleedu.application.st_father_name_b: # t = self.env['ir.translation'].search([ # ('lang', '=', l), # ('type', '=', 'model'), # ('name', '=', 'eagleedu.application,st_father_name_b') # ]) # if t: # self.env['ir.translation'].create({ # 'lang': l, # 'type': 'model', # 'name': 'eagleedu.application,st_father_name_b', # 'res_id': record.res_id, # 'src': record.src, # 'value': t.value, # 'state': 'translated', # }) # # def _get_default_ay(self, cr, uid, context=None): # res = self.pool.get('eagleedu.academic.year').search(cr, uid, [('name', '=', academic_year)], context=context) # return # return res and res[0] or False # # # _defaults = { # 'academic_year': _get_default_ay, # } # user_id = fields.Many2one('res.users', 'User', default=lambda self: self.env.user) # application_date = fields.Datetime('Application Date', default=lambda self: fields.datetime.now()) # , default=fields.Datetime.now, required=True # self.env.ref('module_name.reference_record_id').id house_no = fields.Char(string='House No.', help="Enter the House No.") road_no = fields.Char(string='Area/Road No.', help="Enter the Area or Road No.") post_office = fields.Char(string='Post Office', help="Enter the Post Office Name") city = fields.Char(string='City', help="Enter the City name") bd_division_id = fields.Many2one('eagleedu.bddivision', string= 'State / Division') country_id = fields.Many2one('res.country', string='Country', ondelete='restrict',default=19, help="Select the Country") if_same_address = fields.Boolean(string="Permanent Address same as above", default=True, help="Tick the field if the Present and permanent address is same") per_village = fields.Char(string='Village Name', help="Enter the Village Name") per_po = fields.Char(string='Post Office Name', help="Enter the Post office Name ") per_ps = fields.Char(string='Police Station', help="Enter the Police Station Name") per_dist_id = fields.Many2one('eagleedu.bddistrict', string='District', help="Enter the City of District name") per_bd_division_id = fields.Many2one('eagleedu.bddivision', string='State / Division', help="Enter the City of District name") per_country_id = fields.Many2one('res.country', string='Country', ondelete='restrict', default=19, help="Select the Country") guardian_name = fields.Char(string="Guardian's Name", help="Proud to say my guardian is") guardian_relation = fields.Many2one('eagleedu.guardian.relation', string="Relation to Guardian", required=False, help="Tell us the Relation toyour guardian") guardian_mobile = fields.Char(string="guardian's Mobile No", help="guardian's Mobile No") religious_id = fields.Many2one('eagleedu.religious', string="Religious", help="My Religion is ") class_id = fields.Many2one('eagleedu.class') academic_year = fields.Many2one('eagleedu.academic.year', string='Academic Year') group_division = fields.Many2one('eagleedu.group_division') student_id=fields.Char('Student Id') roll_no = fields.Integer('Roll No') section=fields.Char('Section') state = fields.Selection([('draft', 'Draft'), ('verification', 'Verify'), ('approve', 'Approve'), ('done', 'Done')], string='Status', required=True, default='draft', track_visibility='onchange') company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.user.company_id) email = fields.Char(string="Student Email", help="Enter E-mail id for contact purpose") phone = fields.Char(string="Student Phone", help="Enter Phone no. for contact purpose") mobile = fields.Char(string="Student Mobile", help="Enter Mobile num for contact purpose") nationality = fields.Many2one('res.country', string='Nationality', ondelete='restrict',default=19, help="Select the Nationality") # document_count = fields.Integer(compute='_document_count', string='# Documents') verified_by = fields.Many2one('res.users', string='Verified by', help="The Document is verified by") @api.onchange('guardian_relation') def guardian_relation_changed(self): for rec in self: if rec.guardian_relation.name: if rec.guardian_relation.name=='Father': rec.guardian_mobile=rec.father_mobile rec.guardian_name=rec.st_father_name elif rec.guardian_relation.name=='Mother': rec.guardian_mobile = rec.mother_mobile rec.guardian_name = rec.st_mother_name # @api.depends('application_no', 'application_no.birthday', 'application_date') @api.depends('date_of_birth', 'application_date') def get_student_age(self): for rec in self: age = '' if rec.date_of_birth: end_data = rec.application_date or fields.Datetime.now() delta = relativedelta(end_data, rec.date_of_birth) if delta.years <= 25: age = str(delta.years) + _(" Years ") + str(delta.months) + _(" Month ") + str(delta.days) + _( " Days") else: age = str(delta.years) + _(" Year") rec.age = age @api.model def create(self, vals): """Overriding the create method and assigning the the sequence for the record""" if vals.get('application_no', _('New')) == _('New'): vals['application_no'] = self.env['ir.sequence'].next_by_code('eagleedu.application') or _('New') res = super(EagleeduApplication, self).create(vals) return res # @api.model def send_to_verify(self): """Return the state to done if the documents are perfect""" for rec in self: rec.write({ 'state': 'verification' }) # @api.model def application_verify(self): """Return the state to done if the documents are perfect""" for rec in self: rec.write({ 'state': 'approve' }) #todo show group division when select the class 1 to 8 only # def group_division_show(self): # """Return the state to done if the documents are perfect""" # for rec in self: # rec.write({ # 'state': 'approve' # }) # def get_group_name_auto(self): # for rec in self: # rec.name = str(rec.admitted_class.name) + '(Assign on ' + str(rec.assign_date) +')' # #rec.name = rec.admitted_class.name #+ '(assigned on '+ rec.assign_date +')' # @api.model def create_student(self): """Create student from the application and data and return the student""" for rec in self: values = { 'name': rec.name, 'st_name_b': rec.st_name_b, 'st_image': rec.st_image, 'application_no': rec.id, 'st_father_name': rec.st_father_name, 'st_father_name_b': rec.st_father_name_b, 'father_mobile': rec.father_mobile, 'st_father_occupation': rec.st_father_occupation, 'st_mother_name': rec.st_mother_name, 'st_mother_name_b': rec.st_mother_name_b, 'mother_mobile': rec.mother_mobile, 'st_mother_occupation': rec.st_mother_occupation, 'st_gender': rec.st_gender, 'date_of_birth': rec.date_of_birth, 'st_blood_group': rec.st_blood_group, 'st_passport_no': rec.st_passport_no, 'nationality': rec.nationality.id, 'academic_year': rec.academic_year.id, 'class_id': rec.class_id.id, 'admission_class': rec.register_id.standard.id, 'group_division': rec.group_division.id, 'house_no': rec.house_no, 'road_no': rec.road_no, 'post_office': rec.post_office, 'city': rec.city, 'bd_division_id': rec.bd_division_id.id, 'country_id': rec.country_id.id, 'per_village': rec.per_village, 'per_po': rec.per_po, 'per_ps': rec.per_ps, 'per_dist_id': rec.per_dist_id.id, 'per_bd_division_id': rec.per_bd_division_id.id, 'per_country_id': rec.per_country_id.id, 'guardian_name': rec.guardian_name, 'religious_id': rec.religious_id.id, # 'is_student': True, 'student_id': rec.student_id, 'roll_no': rec.roll_no, 'application_no': rec.application_no, } student = self.env['eagleedu.student'].create(values) rec.write({ 'state': 'done' }) return { 'name': _('Student'), 'view_type': 'form', 'view_mode': 'form', 'res_model': 'eagleedu.student', 'type': 'ir.actions.act_window', 'res_id': student.id, 'context': self.env.context }
def _graph_y_query(self): raise UserError( _('Undefined graph model for Sales Team: %s') % self.name)
def amend_entries(self): # set the accrual account on the selected journal items accrual_account = self.revenue_accrual_account if self.account_type == 'income' else self.expense_accrual_account # Generate journal entries. move_data = {} for aml in self.active_move_line_ids: ref1 = _('Accrual Adjusting Entry (%s recognized) for invoice: %s' ) % (self.percentage, aml.move_id.name) ref2 = _('Accrual Adjusting Entry (%s recognized) for invoice: %s' ) % (100 - self.percentage, aml.move_id.name) move_data.setdefault( aml.move_id, ( [ # Values to create moves. { 'date': self.date, 'ref': ref1, 'journal_id': self.journal_id.id, 'line_ids': [], }, { 'date': aml.move_id.date, 'ref': ref2, 'journal_id': self.journal_id.id, 'line_ids': [], }, ], [ # Messages to log on the chatter. (_('Accrual Adjusting Entry ({percent}% recognized) for invoice:' ) + ' <a href=# data-oe-model=account.move data-oe-id={id}>{name}</a>' ).format( percent=self.percentage, id=aml.move_id.id, name=aml.move_id.name, ), (_('Accrual Adjusting Entry ({percent}% recognized) for invoice:' ) + ' <a href=# data-oe-model=account.move data-oe-id={id}>{name}</a>' ).format( percent=100 - self.percentage, id=aml.move_id.id, name=aml.move_id.name, ), ])) reported_debit = aml.company_id.currency_id.round( (self.percentage / 100) * aml.debit) reported_credit = aml.company_id.currency_id.round( (self.percentage / 100) * aml.credit) if aml.currency_id: reported_amount_currency = aml.currency_id.round( (self.percentage / 100) * aml.amount_currency) else: reported_amount_currency = 0.0 move_data[aml.move_id][0][0]['line_ids'] += [ (0, 0, { 'name': aml.name, 'debit': reported_debit, 'credit': reported_credit, 'amount_currency': reported_amount_currency, 'currency_id': aml.currency_id.id, 'account_id': aml.account_id.id, 'partner_id': aml.partner_id.id, }), (0, 0, { 'name': ref1, 'debit': reported_credit, 'credit': reported_debit, 'amount_currency': -reported_amount_currency, 'currency_id': aml.currency_id.id, 'account_id': accrual_account.id, 'partner_id': aml.partner_id.id, }), ] move_data[aml.move_id][0][1]['line_ids'] += [ (0, 0, { 'name': aml.name, 'debit': aml.debit - reported_debit, 'credit': aml.credit - reported_credit, 'amount_currency': aml.amount_currency - reported_amount_currency, 'currency_id': aml.currency_id.id, 'account_id': aml.account_id.id, 'partner_id': aml.partner_id.id, }), (0, 0, { 'name': ref2, 'debit': aml.credit - reported_credit, 'credit': aml.debit - reported_debit, 'amount_currency': reported_amount_currency - aml.amount_currency, 'currency_id': aml.currency_id.id, 'account_id': accrual_account.id, 'partner_id': aml.partner_id.id, }), ] # Update the account of selected journal items. self.active_move_line_ids.write({'account_id': accrual_account.id}) # When the percentage is 100%, the second move is not needed. if self.percentage < 100: move_vals = [] log_messages = [] for v in move_data.values(): move_vals += v[0] log_messages += v[1] else: move_vals = [v[0][0] for k, v in move_data.items()] log_messages = [v[1][0] for k, v in move_data.items()] created_moves = self.env['account.move'].create(move_vals) created_moves.post() # Reconcile. index = 0 for move in self.active_move_line_ids.mapped('move_id'): if self.percentage < 100: accrual_moves = created_moves[index:index + 2] index += 2 else: accrual_moves = created_moves[index:index + 1] index += 1 to_reconcile = self.active_move_line_ids.filtered( lambda line: line.move_id == move) to_reconcile += accrual_moves.mapped( 'line_ids').filtered(lambda line: line.account_id == accrual_account and not line.reconciled) to_reconcile.reconcile() # Log messages. for created_move, log_message in zip(created_moves, log_messages): created_move.message_post(body=log_message) # open the generated entries action = { 'name': _('Generated Entries'), 'domain': [('id', 'in', created_moves.ids)], 'res_model': 'account.move', 'view_mode': 'tree,form', 'type': 'ir.actions.act_window', 'views': [(self.env.ref('account.view_move_tree').id, 'tree'), (False, 'form')], } if len(created_moves) == 1: action.update({'view_mode': 'form', 'res_id': created_moves.id}) return action
def _get_graph(self): def get_week_name(start_date, locale): """ Generates a week name (string) from a datetime according to the locale: E.g.: locale start_date (datetime) return string "en_US" November 16th "16-22 Nov" "en_US" December 28th "28 Dec-3 Jan" """ if (start_date + relativedelta(days=6)).month == start_date.month: short_name_from = format_date(start_date, 'd', locale=locale) else: short_name_from = format_date(start_date, 'd MMM', locale=locale) short_name_to = format_date(start_date + relativedelta(days=6), 'd MMM', locale=locale) return short_name_from + '-' + short_name_to self.ensure_one() values = [] today = fields.Date.from_string(fields.Date.context_today(self)) start_date, end_date = self._graph_get_dates(today) graph_data = self._graph_data(start_date, end_date) # line graphs and bar graphs require different labels if self.dashboard_graph_type == 'line': x_field = 'x' y_field = 'y' else: x_field = 'label' y_field = 'value' # generate all required x_fields and update the y_values where we have data for them locale = self._context.get('lang') or 'en_US' if self.dashboard_graph_group == 'day': for day in range(0, (end_date - start_date).days + 1): short_name = format_date(start_date + relativedelta(days=day), 'd MMM', locale=locale) values.append({x_field: short_name, y_field: 0}) for data_item in graph_data: index = (data_item.get('x_value') - start_date).days values[index][y_field] = data_item.get('y_value') elif self.dashboard_graph_group == 'week': weeks_in_start_year = int( date(start_date.year, 12, 28).isocalendar() [1]) # This date is always in the last week of ISO years for week in range( 0, (end_date.isocalendar()[1] - start_date.isocalendar()[1]) % weeks_in_start_year + 1): short_name = get_week_name( start_date + relativedelta(days=7 * week), locale) values.append({x_field: short_name, y_field: 0}) for data_item in graph_data: index = int( (data_item.get('x_value') - start_date.isocalendar()[1]) % weeks_in_start_year) values[index][y_field] = data_item.get('y_value') elif self.dashboard_graph_group == 'month': for month in range(0, (end_date.month - start_date.month) % 12 + 1): short_name = format_date(start_date + relativedelta(months=month), 'MMM', locale=locale) values.append({x_field: short_name, y_field: 0}) for data_item in graph_data: index = int((data_item.get('x_value') - start_date.month) % 12) values[index][y_field] = data_item.get('y_value') elif self.dashboard_graph_group == 'user': for data_item in graph_data: values.append({ x_field: self.env['res.users'].browse(data_item.get('x_value')).name or _('Not Defined'), y_field: data_item.get('y_value') }) else: for data_item in graph_data: values.append({ x_field: data_item.get('x_value'), y_field: data_item.get('y_value') }) [graph_title, graph_key] = self._graph_title_and_key() color = '#875A7B' if '+e' in version else '#7c7bad' return [{ 'values': values, 'area': True, 'title': graph_title, 'key': graph_key, 'color': color }]
def default_get(self, fields): IrDefault = self.env['ir.default'] IrConfigParameter = self.env['ir.config_parameter'].sudo() classified = self._get_classified_fields() res = super(ResConfigSettings, self).default_get(fields) # defaults: take the corresponding default value they set for name, model, field in classified['default']: value = IrDefault.get(model, field) if value is not None: res[name] = value # groups: which groups are implied by the group Employee for name, groups, implied_group in classified['group']: res[name] = all(implied_group in group.implied_ids for group in groups) if self._fields[name].type == 'selection': res[name] = int(res[name]) # modules: which modules are installed/to install for name, module in classified['module']: res[name] = module.state in ('installed', 'to install', 'to upgrade') if self._fields[name].type == 'selection': res[name] = int(res[name]) # config: get & convert stored ir.config_parameter (or default) WARNING_MESSAGE = "Error when converting value %r of field %s for ir.config.parameter %r" for name, icp in classified['config']: field = self._fields[name] value = IrConfigParameter.get_param( icp, field.default(self) if field.default else False) if value is not False: if field.type == 'many2one': try: # Special case when value is the id of a deleted record, we do not want to # block the settings screen value = self.env[field.comodel_name].browse( int(value)).exists().id except ValueError: _logger.warning(WARNING_MESSAGE, value, field, icp) value = False elif field.type == 'integer': try: value = int(value) except ValueError: _logger.warning(WARNING_MESSAGE, value, field, icp) value = 0 elif field.type == 'float': try: value = float(value) except ValueError: _logger.warning(WARNING_MESSAGE, value, field, icp) value = 0.0 elif field.type == 'boolean': value = bool(value) res[name] = value # other fields: call the method 'get_values' # The other methods that start with `get_default_` are deprecated for method in dir(self): if method.startswith('get_default_'): _logger.warning( _('Methods that start with `get_default_` are deprecated. Override `get_values` instead(Method %s)' ) % method) res.update(self.get_values()) return res
def _compute_dashboard_button_name(self): """ Sets the adequate dashboard button name depending on the Sales Team's options """ for team in self: team.dashboard_button_name = _( "Big Pretty Button :)") # placeholder
def _check_birthdate(self): for record in self: if record.birth_date > fields.Date.today(): raise ValidationError( _("Birth Date can't be greater than current date!"))
def _change_standard_price(self, new_price, counterpart_account_id=False): """Helper to create the stock valuation layers and the account moves after an update of standard price. :param new_price: new standard price """ # Handle stock valuation layers. svl_vals_list = [] company_id = self.env.company for product in self: if product.cost_method not in ('standard', 'average'): continue quantity_svl = product.sudo().quantity_svl if float_is_zero(quantity_svl, precision_rounding=product.uom_id.rounding): continue diff = new_price - product.standard_price value = company_id.currency_id.round(quantity_svl * diff) if company_id.currency_id.is_zero(value): continue svl_vals = { 'company_id': company_id.id, 'product_id': product.id, 'description': _('Product value manually modified (from %s to %s)') % (product.standard_price, new_price), 'value': value, 'quantity': 0, } svl_vals_list.append(svl_vals) stock_valuation_layers = self.env['stock.valuation.layer'].sudo( ).create(svl_vals_list) # Handle account moves. product_accounts = { product.id: product.product_tmpl_id.get_product_accounts() for product in self } am_vals_list = [] for stock_valuation_layer in stock_valuation_layers: product = stock_valuation_layer.product_id value = stock_valuation_layer.value if product.valuation != 'real_time': continue # Sanity check. if counterpart_account_id is False: raise UserError(_('You must set a counterpart account.')) if not product_accounts[product.id].get('stock_valuation'): raise UserError( _('You don\'t have any stock valuation account defined on your product category. You must define one before processing this operation.' )) if value < 0: debit_account_id = counterpart_account_id credit_account_id = product_accounts[ product.id]['stock_valuation'].id else: debit_account_id = product_accounts[ product.id]['stock_valuation'].id credit_account_id = counterpart_account_id move_vals = { 'journal_id': product_accounts[product.id]['stock_journal'].id, 'company_id': company_id.id, 'ref': product.default_code, 'stock_valuation_layer_ids': [(6, None, [stock_valuation_layer.id])], 'line_ids': [(0, 0, { 'name': _('%s changed cost from %s to %s - %s') % (self.env.user.name, product.standard_price, new_price, product.display_name), 'account_id': debit_account_id, 'debit': abs(value), 'credit': 0, 'product_id': product.id, }), (0, 0, { 'name': _('%s changed cost from %s to %s - %s') % (self.env.user.name, product.standard_price, new_price, product.display_name), 'account_id': credit_account_id, 'debit': 0, 'credit': abs(value), 'product_id': product.id, })], } am_vals_list.append(move_vals) account_moves = self.env['account.move'].create(am_vals_list) account_moves.post() # Actually update the standard price. self.with_context(force_company=company_id.id).sudo().write( {'standard_price': new_price})