def check_account_charts(self, cr, uid, ids, context=None): """ Check the chart of accounts of the holding vs each virtual chart of accounts of the subsidiaries """ if isinstance(ids, (int, long)): ids = [ids] assert len(ids) == 1, "only 1 id expected" form = self.browse(cr, uid, ids[0], context=context) invalid_items_per_company = {} for subsidiary in form.subsidiary_ids: if not subsidiary.consolidation_chart_account_id: raise osv.except_osv( _('Error'), _('No chart of accounts for company %s') % subsidiary.name) invalid_items = self.check_subsidiary_chart( cr, uid, ids, form.holding_chart_account_id.id, subsidiary.consolidation_chart_account_id.id, context=context) if any(invalid_items): invalid_items_per_company[subsidiary.id] = invalid_items return invalid_items_per_company
def _read_file(self, file_type, record, options): # guess mimetype from file content mimetype = guess_mimetype(record.file) (file_extension, handler, req) = FILE_TYPE_DICT.get(mimetype, (None, None, None)) if handler: try: return getattr(self, '_read_' + file_extension)(record, options) except Exception: _logger.warn("Failed to read file '%s' (transient id %d) using guessed mimetype %s", record.file_name or '<unknown>', record.id, mimetype) # try reading with user-provided mimetype (file_extension, handler, req) = FILE_TYPE_DICT.get(file_type, (None, None, None)) if handler: try: return getattr(self, '_read_' + file_extension)(record, options) except Exception: _logger.warn("Failed to read file '%s' (transient id %d) using user-provided mimetype %s", record.file_name or '<unknown>', record.id, file_type) # fallback on file extensions as mime types can be unreliable (e.g. # software setting incorrect mime types, or non-installed software # leading to browser not sending mime types) if record.file_name: p, ext = os.path.splitext(record.file_name) if ext in EXTENSIONS: try: return getattr(self, '_read_' + ext[1:])(record, options) except Exception: _logger.warn("Failed to read file '%s' (transient id %s) using file extension", record.file_name, record.id) if req: raise ImportError(_("Unable to load \"{extension}\" file: requires Python module \"{modname}\"").format(extension=file_extension, modname=req)) raise ValueError(_("Unsupported file format \"{}\", import only supports CSV, ODS, XLS and XLSX").format(file_type))
def button_upgrade(self, cr, uid, ids, context=None): depobj = self.pool.get('ir.module.module.dependency') todo = self.browse(cr, uid, ids, context=context) self.update_list(cr, uid) i = 0 while i < len(todo): mod = todo[i] i += 1 if mod.state not in ('installed', 'to upgrade'): raise orm.except_orm(_('Error'), _("Can not upgrade module '%s'. It is not installed.") % (mod.name,)) self.check_external_dependencies(mod.name, 'to upgrade') iids = depobj.search(cr, uid, [('name', '=', mod.name)], context=context) for dep in depobj.browse(cr, uid, iids, context=context): if dep.module_id.state == 'installed' and dep.module_id not in todo: todo.append(dep.module_id) ids = map(lambda x: x.id, todo) self.write(cr, uid, ids, {'state': 'to upgrade'}, context=context) to_install = [] for mod in todo: for dep in mod.dependencies_id: if dep.state == 'unknown': raise orm.except_orm(_('Error'), _('You try to upgrade a module that depends on the module: %s.\nBut this module is not available in your system.') % (dep.name,)) if dep.state == 'uninstalled': ids2 = self.search(cr, uid, [('name', '=', dep.name)]) to_install.extend(ids2) self.button_install(cr, uid, to_install, context=context) return dict(ACTION_DICT, name=_('Apply Schedule Upgrade'))
def onchange_product_id(self, cr, uid, ids, product_id, name, bom_template, context=None): """ Changes UoM and name if product_id changes. @param name: Name of the field @param product_id: Changed product_id @return: Dictionary of changed values """ res = super(BomTemplate, self).onchange_product_id( cr, uid, ids, product_id, name, context=context) if (bom_template and res and 'value' in res and res['value'].get('name', False)): if product_id: prod = self.pool['product.product'].browse(cr, uid, product_id, context=context) res['value']['name'] = '%s %s' % (prod.product_tmpl_id.name, _('TEMPLATE')) message = (_('By selecting to use this product as a template' ' all products of template %s will use this BoM') % prod.product_tmpl_id.name) if res.get('warning', False): res['warning'].update({'title': _('Multiple Warnings'), 'message': '%s\n%s' % (res['warning']['message'], message)}) else: res['warning'] = {'title': 'Set as Template', 'message': message} return res
def _jasper_execute_rest(self, ex, current_document, js_conf, pdf_list, ids=None, context=None): """ After retrieve datas to launch report, execute it and return the content """ lang_obj = self.pool.get('res.lang') # Issue 934068 with web client with model is missing from the context if not self.model: self.model = current_document.model_id.model self.model_obj = self.pool.get(self.model) if context is None: context = self.context.copy() if ids is None: ids = [] doc_obj = self.pool.get('jasper.document') js_obj = self.pool.get('jasper.server') cur_obj = self.model_obj.browse(self.cr, self.uid, ex, context=context) aname = False if self.attrs['attachment']: try: aname = eval(self.attrs['attachment'], {'object': cur_obj, 'time': time}) except SyntaxError, e: _logger.warning('Error %s' % str(e)) raise EvalError(_('Attachment Error'), _('Syntax error when evaluate attachment\n\nMessage: "%s"') % str(e)) except NameError, e: _logger.warning('Error %s' % str(e)) raise EvalError(_('Attachment Error'), _('Error when evaluate attachment\n\nMessage: "%s"') % str(e))
def onchange_date_from(self, cr, uid, ids, date_to, date_from): """ If there are no date set for date_to, automatically set one 8 hours later than the date_from. Also update the number_of_days. """ # date_to has to be greater than date_from if (date_from and date_to) and (date_from > date_to): raise osv.except_osv(_('Warning!'),_('The start date must be anterior to the end date.')) result = {'value': {}} # No date_to set so far: automatically compute one 8 hours later if date_from and not date_to: date_to_with_delta = datetime.datetime.strptime(date_from, tools.DEFAULT_SERVER_DATETIME_FORMAT) + datetime.timedelta(hours=8) result['value']['date_to'] = str(date_to_with_delta) # Compute and update the number of days if (date_to and date_from) and (date_from <= date_to): diff_day = self._get_number_of_days(date_from, date_to) result['value']['number_of_days_temp'] = round(math.floor(diff_day))+1 else: result['value']['number_of_days_temp'] = 0 return result
def get_action(self, cr, uid, ids, report_name, data=None, context=None): """Return an action of type ir.actions.report.xml. :param ids: Ids of the records to print (if not used, pass an empty list) :param report_name: Name of the template to generate an action for """ if ids: if not isinstance(ids, list): ids = [ids] context = dict(context or {}, active_ids=ids) report_obj = self.pool['ir.actions.report.xml'] idreport = report_obj.search(cr, uid, [('report_name', '=', report_name)], context=context) try: report = report_obj.browse(cr, uid, idreport[0], context=context) except IndexError: raise osv.except_osv( _('Bad Report Reference'), _('This report is not loaded into the database: %s.' % report_name) ) return { 'context': context, 'data': data, 'type': 'ir.actions.report.xml', 'report_name': report.report_name, 'report_type': report.report_type, 'report_file': report.report_file, 'context': context, }
def onchange_product_id(self,cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order=False, fiscal_position_id=False, date_planned=False, name=False, price_unit=False, notes=False, context=None): warning = {} if not product: return {'value': {'price_unit': price_unit or 0.0, 'name': name or '', 'notes': notes or '', 'product_uom' : uom or False}, 'domain':{'product_uom':[]}} product_obj = self.pool.get('product.product') product_info = product_obj.browse(cr, uid, product) title = False message = False if product_info.purchase_line_warn != 'no-message': if product_info.purchase_line_warn == 'block': raise osv.except_osv(_('Alert for %s!') % (product_info.name), product_info.purchase_line_warn_msg) title = _("Warning for %s") % product_info.name message = product_info.purchase_line_warn_msg warning['title'] = title warning['message'] = message result = super(purchase_order_line, self).onchange_product_id(cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order, fiscal_position_id) if result.get('warning',False): warning['title'] = title and title +' & '+result['warning']['title'] or result['warning']['title'] warning['message'] = message and message +'\n\n'+result['warning']['message'] or result['warning']['message'] return {'value': result.get('value',{}), 'warning':warning}
def validate_initials(self,cr, uid, ids, initials): ini = str(initials).replace(" ", "") ini = ini.replace(".", "") if ini.isalpha(): return True else: raise osv.except_osv(_('Invalid Initials'), _('Enter Initials Correctly'))
def onchange_partner_id(self, cr, uid, ids, type, partner_id, date_invoice=False, payment_term=False, partner_bank_id=False, company_id=False): if not partner_id: return {'value': { 'account_id': False, 'payment_term': False, } } warning = {} title = False message = False partner = self.pool.get('res.partner').browse(cr, uid, partner_id) if partner.invoice_warn != 'no-message': if partner.invoice_warn == 'block': raise osv.except_osv(_('Alert for %s!') % (partner.name), partner.invoice_warn_msg) title = _("Warning for %s") % partner.name message = partner.invoice_warn_msg warning = { 'title': title, 'message': message } result = super(account_invoice, self).onchange_partner_id(cr, uid, ids, type, partner_id, date_invoice=date_invoice, payment_term=payment_term, partner_bank_id=partner_bank_id, company_id=company_id) if result.get('warning',False): warning['title'] = title and title +' & '+ result['warning']['title'] or result['warning']['title'] warning['message'] = message and message + ' ' + result['warning']['message'] or result['warning']['message'] return {'value': result.get('value',{}), 'warning':warning}
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False, context=None): warning = {} if not product: return {'value': {'th_weight' : 0, 'product_packaging': False, 'product_uos_qty': qty}, 'domain': {'product_uom': [], 'product_uos': []}} product_obj = self.pool.get('product.product') product_info = product_obj.browse(cr, uid, product) title = False message = False if product_info.sale_line_warn != 'no-message': if product_info.sale_line_warn == 'block': raise osv.except_osv(_('Alert for %s!') % (product_info.name), product_info.sale_line_warn_msg) title = _("Warning for %s") % product_info.name message = product_info.sale_line_warn_msg warning['title'] = title warning['message'] = message result = super(sale_order_line, self).product_id_change( cr, uid, ids, pricelist, product, qty, uom, qty_uos, uos, name, partner_id, lang, update_tax, date_order, packaging, fiscal_position, flag, context=context) if result.get('warning',False): warning['title'] = title and title +' & '+result['warning']['title'] or result['warning']['title'] warning['message'] = message and message +'\n\n'+result['warning']['message'] or result['warning']['message'] return {'value': result.get('value',{}), 'warning':warning}
def preview(self, cr, uid, ids, context=None): res = {} wi_obj = self.browse(cr, uid, ids[0], context=context) if wi_obj.activity_id.type == 'email': view_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'email_template', 'email_template_preview_form') res = { 'name': _('Email Preview'), 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'email_template.preview', 'view_id': False, 'context': context, 'views': [(view_id and view_id[1] or 0, 'form')], 'type': 'ir.actions.act_window', 'target': 'new', 'nodestroy':True, 'context': "{'template_id':%d,'default_res_id':%d}"% (wi_obj.activity_id.email_template_id.id, wi_obj.res_id) } elif wi_obj.activity_id.type == 'report': datas = { 'ids': [wi_obj.res_id], 'model': wi_obj.object_id.model } res = { 'type' : 'ir.actions.report.xml', 'report_name': wi_obj.activity_id.report_id.report_name, 'datas' : datas, } else: raise osv.except_osv(_('No preview'),_('The current step for this item has no email or report to preview.')) return res
def onchange_parent_id(self, cr, uid, ids, parent_id, context=None): def value_or_id(val): """ return val or val.id if val is a browse record """ return val if isinstance(val, (bool, int, long, float, basestring)) else val.id if not parent_id or not ids: return {'value': {}} if parent_id: result = {} partner = self.browse(cr, uid, ids[0], context=context) if partner.parent_id and partner.parent_id.id != parent_id: result['warning'] = { 'title': _('Warning'), 'message': _('Changing the company of a contact should only be done if it ' 'was never correctly set. If an existing contact starts working for a new ' 'company then a new contact should be created under that new ' 'company. You can use the "Discard" button to abandon this change.')} # for contacts: copy the parent address, if set (aka, at least # one value is set in the address: otherwise, keep the one from # the contact) if partner.type == 'contact': parent = self.browse(cr, uid, parent_id, context=context) address_fields = self._address_fields(cr, uid, context=context) if any(parent[key] for key in address_fields): result['value'] = dict((key, value_or_id(parent[key])) for key in address_fields) return result
def do_button_print(self, cr, uid, ids, context=None): assert(len(ids) == 1) company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id #search if the partner has accounting entries to print. If not, it may not be present in the #psql view the report is based on, so we need to stop the user here. if not self.pool.get('account.move.line').search(cr, uid, [ ('partner_id', '=', ids[0]), ('account_id.type', '=', 'receivable'), ('reconcile_id', '=', False), ('state', '!=', 'draft'), ('company_id', '=', company_id), ], context=context): raise osv.except_osv(_('Error!'),_("The partner does not have any accounting entries to print in the overdue report for the current company.")) self.message_post(cr, uid, [ids[0]], body=_('Printed overdue payments report'), context=context) #build the id of this partner in the psql view. Could be replaced by a search with [('company_id', '=', company_id),('partner_id', '=', ids[0])] wizard_partner_ids = [ids[0] * 10000 + company_id] followup_ids = self.pool.get('account_followup.followup').search(cr, uid, [('company_id', '=', company_id)], context=context) if not followup_ids: raise osv.except_osv(_('Error!'),_("There is no followup plan defined for the current company.")) data = { 'date': fields.date.today(), 'followup_id': followup_ids[0], } #call the print overdue report on this partner return self.do_partner_print(cr, uid, wizard_partner_ids, data, context=context)
def upload_file_sent(self, cr, uid, file_sent): """ Takes a browse record on an lx.file.sent object and uploads it to the server. """ assert isinstance(file_sent, browse_record), _('data parameter must extend lx_data class') assert file_sent._name == 'lx.file.sent', _("file_sent must have _name 'lx.file.sent'") self.cd(self._vers_lx) try: # handle different data types appropriately contents = '' if file_sent.content_type == 'xml': contents = file_sent.xml elif file_sent.content_type == 'pdf': contents = decodestring(file_sent.xml) xml_buffer = StringIO(contents) files = self.ls() # raise exception if file already exists if file_sent.upload_file_name in files: raise osv.except_osv(_('File Already Exists'), _("A file with name '%s' already exists on the FTP server! This should never happen as file names should contain unique sequence numbers...") % file_sent.upload_file_name) # do actual upload self.mkf(file_sent.upload_file_name, xml_buffer) finally: self.try_cd('..') return file_sent.upload_file_name
def calc_period_prec(self, cr, uid, fiscal_year, context={}): fiscalyear_obj = self.pool['account.fiscalyear'] date_start = ( str(datetime.strptime(fiscal_year.date_start, '%Y-%m-%d') - relativedelta(years=1))[:10]) date_stop = ( str(datetime.strptime(fiscal_year.date_stop, '%Y-%m-%d') - relativedelta(years=1))[:10]) id_fy = fiscalyear_obj.search( cr, uid, [('date_start', '=', date_start), ('date_stop', '=', date_stop)]) if not id_fy: raise osv.except_osv( _('Error!'), _('Not find the previous exercise for period %s - %s' % ( date_start, date_stop))) # Anno Successivo date_start = ( str(datetime.strptime(fiscal_year.date_start, '%Y-%m-%d') + relativedelta(years=1))[:10]) date_stop = ( str(datetime.strptime(fiscal_year.date_stop, '%Y-%m-%d') + relativedelta(years=1))[:10]) id_fy1 = fiscalyear_obj.search( cr, uid, [('date_start', '=', date_start), ('date_stop', '=', date_stop)]) if not id_fy1: raise osv.except_osv( _('Error!'), _('Not find the next exercise for period %s - %s' % ( date_start, date_stop))) return id_fy[0], id_fy1[0]
def create_invoices(self, cr, uid, ids, context=None): sale_obj = self.pool.get('sale.order') wizard = self.browse(cr, uid, ids[0], context) sale_ids = context.get('active_ids', []) invoice_obj = self.pool.get('account.invoice') if wizard.advance_payment_method == 'multiple': if len(sale_ids) > 1: raise Warning(_('Can not use multiple invoices in multiple sales orders at once!')) if sale_obj.browse(cr, uid, sale_ids[0], context=context).invoice_ids: raise Warning(_('This sale order has already some invoices created!')) inv_ids = [] for invoice_count in range(wizard.invoice_qty - 1): for sale_id, inv_values in self._prepare_advance_invoice_vals(cr, uid, ids, context=context): first_invoice_date = datetime.strptime(wizard.first_invoice_date, DEFAULT_SERVER_DATE_FORMAT) invoice_date = (first_invoice_date + relativedelta.relativedelta(months=invoice_count)).strftime(DEFAULT_SERVER_DATE_FORMAT) invoice_id = self._create_invoices(cr, uid, inv_values, sale_id, context=context) invoice_obj.write(cr, uid, invoice_id, {'date_invoice':invoice_date}, context=context) inv_ids.append(invoice_id) # create the final invoices of the active sales orders invoice_date = (first_invoice_date + relativedelta.relativedelta(months=wizard.invoice_qty-1)).strftime(DEFAULT_SERVER_DATE_FORMAT) invoice_id = sale_obj.manual_invoice(cr, uid, sale_ids, context).get('res_id',False) invoice_obj.write(cr, uid, invoice_id, {'date_invoice':invoice_date}, context=context) if context.get('open_invoices', False): return sale_obj.action_view_invoice(cr, uid, sale_ids, context=context) return {'type': 'ir.actions.act_window_close'} return super(sale_advance_payment_inv, self).create_invoices(cr, uid, ids, context=context)
def write(self, cr, user, ids, vals, context=None): """ Warn if user does not have rights to modify travel with current number of passengers or to add more than the limit. """ if type(ids) is not list: ids = [ids] users_pool = self.pool.get('res.users') limit = get_basic_passenger_limit(self.pool.get("ir.config_parameter"), cr, user, context=context) if (len(vals.get('passenger_ids', [])) > limit and not users_pool.has_group(cr, user, 'travel.group_travel_manager')): raise orm.except_orm( _('Warning!'), _('Only members of the Travel Managers group have the rights ' 'to add more than %d passengers to a travel.') % limit) for travel in self.browse(cr, user, ids, context=context): if (len(travel.passenger_ids) > limit and not users_pool.has_group(cr, user, 'travel.group_travel_manager')): raise orm.except_orm( _('Warning!'), _('Only members of the Travel Managers group have the ' 'rights to modify a Travel with more than %d passengers ' '(%s).') % (limit, travel.name)) return super(travel_travel, self).write(cr, user, ids, vals, context=context)
def _compute_entries(self, cr, uid, ids, period_id, context=None): result = [] period_obj = self.pool.get('account.period') depreciation_obj = self.pool.get('account.asset.depreciation.line') period = period_obj.browse(cr, uid, period_id, context=context) depreciation_ids = depreciation_obj.search(cr, uid, [ ('asset_id', 'in', ids), ('depreciation_date', '<=', period.fiscalyear_id.date_stop), ('depreciation_date', '>=', period.fiscalyear_id.date_start), ], context=context) if depreciation_ids: list_pointer=0 for line in depreciation_obj.browse(cr,uid,depreciation_ids): if line.move_check: if context['at_day']: raise osv.except_osv( _('Errore'), _('Previous moves amortization found \ please delete those before' )) else: del depreciation_ids[list_pointer] list_pointer+=1 if context is None: context = {} context.update({'depreciation_date':period.date_stop}) return depreciation_obj.create_move(cr, uid, depreciation_ids, context=context)
def create(self, cr, uid, vals, context=None): # PARA SECUENCIAS POR UBICACIONES picking_id = super(stock_picking_out, self).create(cr, uid, vals, context=context) picking = self.pool.get('stock.picking.out').browse(cr, uid, picking_id, context=context) sequence_obj = self.pool.get('ir.sequence') #_logger.error("PINCKING: %r", picking) #if ('name' not in vals) or (vals.get('name')=='/'): if vals['type'] == 'out': location_id = vals.get('location_id', []) if location_id: location = self.pool.get('stock.location').browse(cr, uid, location_id, context) if location.sequence_out_id: vals = {'name': sequence_obj.get_id(cr, uid, location.sequence_out_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_('Warning!'), _('Ubicacion de origen no tiene secuencia asignanda.')) else: for move in picking.move_lines: location_id = move.location_id location = self.pool.get('stock.location').browse(cr, uid, location_id.id, context) if location.sequence_out_id: vals = {'name': sequence_obj.get_id(cr, uid, location.sequence_out_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_('Warning!'), _('Ubicacion de origen no tiene secuencia asignanda.')) return picking_id
def modify_production_order_state(self, cr, uid, ids, action): """ Modifies production order state if work order state is changed. @param action: Action to perform. @return: Nothing """ prod_obj_pool = self.pool.get('mrp.production') oper_obj = self.browse(cr, uid, ids)[0] prod_obj = oper_obj.production_id if action == 'start': if prod_obj.state =='confirmed': prod_obj_pool.force_production(cr, uid, [prod_obj.id]) prod_obj_pool.signal_workflow(cr, uid, [prod_obj.id], 'button_produce') elif prod_obj.state =='ready': prod_obj_pool.signal_workflow(cr, uid, [prod_obj.id], 'button_produce') elif prod_obj.state =='in_production': return else: raise osv.except_osv(_('Error!'),_('Manufacturing order cannot be started in state "%s"!') % (prod_obj.state,)) else: open_count = self.search_count(cr,uid,[('production_id','=',prod_obj.id), ('state', '!=', 'done')]) flag = not bool(open_count) if flag: for production in prod_obj_pool.browse(cr, uid, [prod_obj.id], context= None): if production.move_lines or production.move_created_ids: prod_obj_pool.action_produce(cr,uid, production.id, production.product_qty, 'consume_produce', context = None) prod_obj_pool.signal_workflow(cr, uid, [oper_obj.production_id.id], 'button_produce_done') return
def _prepare_bank_journal(self, cr, uid, line, current_num, default_account_id, company_id, context=None): obj_data = self.pool.get('ir.model.data') obj_journal = self.pool.get('account.journal') for num in xrange(current_num, 100): # journal_code has a maximal size of 5, hence we can enforce the boundary num < 100 journal_code = line['account_type'] == 'cash' and _('CSH')[:3] + str(num) or _('BNK')[:3] + str(num) ids = obj_journal.search(cr, uid, [('code', '=', journal_code), ('company_id', '=', company_id)], context=context) if not ids: break else: raise osv.except_osv(_('Error!'), _('Cannot generate an unused journal code.')) vals = { 'name': line['acc_name'], 'code': journal_code, 'type': line['account_type'] == 'cash' and 'cash' or 'bank', 'company_id': company_id, 'analytic_journal_id': False, 'currency': False, 'default_credit_account_id': default_account_id, 'default_debit_account_id': default_account_id, } if line['currency_id']: vals['currency'] = line['currency_id'] return vals
def _get_default_from(self, cr, uid, context=None): this = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context) if this.alias_domain: return '%s <%s@%s>' % (this.name, this.alias_name, this.alias_domain) elif this.email: return '%s <%s>' % (this.name, this.email) raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias."))
def button_cancel(self, cr, uid, ids, context=None): lines = self.browse(cr, uid, ids, context=context) for procurement in lines.mapped('procurement_ids'): for move in procurement.move_ids: if move.state == 'done' and not move.scrapped: raise osv.except_osv(_('Invalid Action!'), _('You cannot cancel a sale order line which is linked to a stock move already done.')) return super(sale_order_line, self).button_cancel(cr, uid, ids, context=context)
def create(self, cr, uid, vals, context=None): # PARA SECUENCIAS POR UBICACIONES picking_id = super(stock_picking_in, self).create(cr, uid, vals, context=context) # _logger.error("PINCKING id1: %r", picking_id) picking = self.pool.get("stock.picking.in").browse(cr, uid, picking_id, context=context) sequence_obj = self.pool.get("ir.sequence") # if ('name' not in vals) or (vals.get('name')=='/'): if vals["type"] == "in": location_id = vals.get("location_dest_id", []) if location_id: location = self.pool.get("stock.location").browse(cr, uid, location_id, context) if location.sequence_in_id: vals = {"name": sequence_obj.get_id(cr, uid, location.sequence_in_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_("Warning!"), _("Ubicacion de destino no tiene secuencia asignanda.")) else: for move in picking.move_lines: location_id = move.location_dest_id location = self.pool.get("stock.location").browse(cr, uid, location_id.id, context) if location.sequence_in_id: vals = {"name": sequence_obj.get_id(cr, uid, location.sequence_in_id.id, context=context)} self.write(cr, uid, picking_id, vals, context=context) else: raise osv.except_osv(_("Warning!"), _("Ubicacion de destino no tiene secuencia asignanda.")) return picking_id
def action_cancel_inventory(self, cr, uid, ids, context=None): """ Cancels both stock move and inventory @return: True """ move_obj = self.pool.get('stock.move') account_move_obj = self.pool.get('account.move') for inv in self.browse(cr, uid, ids, context=context): move_obj.action_cancel(cr, uid, [x.id for x in inv.move_ids], context=context) for move in inv.move_ids: # import pdb;pdb.set_trace() account_move_ids = account_move_obj.search(cr, uid, [('name', '=', move.name)]) account_move_ids2 = account_move_obj.search(cr, uid, [('ref', '=', move.name)]) account_move_obj.unlink(cr, uid, account_move_ids2, context=context) if account_move_ids: account_move_data_l = account_move_obj.read(cr, uid, account_move_ids, ['state'], context=context) for account_move in account_move_data_l: if account_move['state'] == 'posted': raise osv.except_osv(_('User Error!'), _('In order to cancel this inventory, you must first unpost related journal entries.')) account_move_obj.unlink(cr, uid, [account_move['id']], context=context) self.write(cr, uid, [inv.id], {'state': 'cancel'}, context=context) return True
def default_get(self, cr, uid, fields, context=None): """ This function gets default values """ res = super(project_task_delegate, self).default_get(cr, uid, fields, context=context) if context is None: context = {} record_id = context and context.get('active_id', False) or False if not record_id: return res task_pool = self.pool.get('project.task') task = task_pool.browse(cr, uid, record_id, context=context) task_name =tools.ustr(task.name) if 'project_id' in fields: res['project_id'] = int(task.project_id.id) if task.project_id else False if 'name' in fields: if task_name.startswith(_('CHECK: ')): newname = tools.ustr(task_name).replace(_('CHECK: '), '') else: newname = tools.ustr(task_name or '') res['name'] = newname if 'planned_hours' in fields: res['planned_hours'] = task.remaining_hours or 0.0 if 'prefix' in fields: if task_name.startswith(_('CHECK: ')): newname = tools.ustr(task_name).replace(_('CHECK: '), '') else: newname = tools.ustr(task_name or '') prefix = _('CHECK: %s') % newname res['prefix'] = prefix if 'new_task_description' in fields: res['new_task_description'] = task.description return res
def quickly_create_user(self, cr, uid, ids, context=None): res_users = self.pool.get('res.users') # Make this an option context = dict(context or {}, no_reset_password=True) # TODO Pasar argumentos para activar o desactivar create_user = True for partner in self.browse(cr, SUPERUSER_ID, ids, context): group_ids = [] if not partner.template_user_id: raise osv.except_osv(_('Non template user selected!'), _('Please define a template user for this partner: "%s" (id:%d).') % (partner.name, partner.id)) group_ids = [x.id for x in partner.template_user_id.groups_id] user_ids = self.retrieve_user(cr, SUPERUSER_ID, partner, context) if create_user: # create a user if necessary, and make sure it is in the portal # group if not user_ids: user_ids = [ self._create_user(cr, SUPERUSER_ID, partner, context)] res_users.write( cr, SUPERUSER_ID, user_ids, {'active': True, 'groups_id': [(6, 0, group_ids)]}) # prepare for the signup process # TODO make an option of this # partner.signup_prepare() # TODO option to send or not email # self._send_email(cr, uid, partner, context) elif user_ids: # deactivate user res_users.write(cr, SUPERUSER_ID, user_ids, {'active': False})
def confirm(self, order_id): cr, uid, context = request.cr, request.uid, request.context transaction_obj = request.registry.get('payment.transaction') sale_order_obj = request.registry.get('sale.order') order = sale_order_obj.browse(cr, SUPERUSER_ID, order_id, context=context) if not order or not order.order_line: return request.redirect("/quote/%s" % (order_id)) # find transaction tx_id = transaction_obj.search(cr, SUPERUSER_ID, [('reference', '=', order.name)], context=context) tx = transaction_obj.browse(cr, SUPERUSER_ID, tx_id, context=context) # create draft invoice if transaction is ok if tx and tx.state == 'pending': sale_order_obj.action_button_confirm(cr, SUPERUSER_ID, [order_id], context=context) sale_order_obj.signal_workflow(cr, SUPERUSER_ID, [order.id], 'manual_invoice', context=context) message = _('Order payed by %s, waiting for payment confirmation') % (tx.partner_id.name,) self.__message_post(message, order_id, type='comment', subtype='mt_comment') elif tx and tx.state == 'done': sale_order_obj.signal_workflow(cr, SUPERUSER_ID, [order.id], 'manual_invoice', context=context) invoice = order.invoice_ids request.registry['account.invoice'].signal_workflow(cr, SUPERUSER_ID, [invoice.id], 'invoice_open', context=context) period_id = request.registry['account.period'].find(cr, SUPERUSER_ID, time.strftime('%Y-%m-%d'), context=context)[0] message = _('Order payed by %s') % (tx.partner_id.name,) self.__message_post(message, order_id, type='comment', subtype='mt_comment') # if website_sale is installed, we need to clean the sale_order linked to the website # otherwise the system will mix transactions on the next SO if hasattr(request.website, 'sale_reset'): request.website.sale_reset() return request.redirect("/quote/%s/%s" % (order.id, order.access_token))
def model_copy(self, cr, uid, ids, context=None): for row in self.read(cr, uid, ids, context=context): if not row.get('cron_id',False): continue cron_ids = [row['cron_id'][0]] remaining = self.pool.get('ir.cron').read(cr, uid, cron_ids, ['numbercall'])[0]['numbercall'] try: (model_name, id) = row['doc_source'].split(',') id = int(id) model = self.pool[model_name] except: raise osv.except_osv(_('Wrong Source Document!'), _('Please provide another source document.\nThis one does not exist!')) default = {'state':'draft'} doc_obj = self.pool.get('subscription.document') document_ids = doc_obj.search(cr, uid, [('model.model','=',model_name)]) doc = doc_obj.browse(cr, uid, document_ids)[0] for f in doc.field_ids: if f.value=='date': value = time.strftime('%Y-%m-%d') else: value = False default[f.field.name] = value state = 'running' # if there was only one remaining document to generate # the subscription is over and we mark it as being done if remaining == 1: state = 'done' id = self.pool[model_name].copy(cr, uid, id, default, context) self.pool.get('subscription.subscription.history').create(cr, uid, {'subscription_id': row['id'], 'date':time.strftime('%Y-%m-%d %H:%M:%S'), 'document_id': model_name+','+str(id)}) self.write(cr, uid, [row['id']], {'state':state}) return True
def calc_route_details(self, start_date, end_date, delete, recalc=True): dt_sta = datetime.strptime(start_date, FORMAT) day_number = self.day_id.sequence - 1 dt_end = datetime.strptime(end_date, FORMAT) # Check Dates if not self._valid_dates(dt_sta, dt_end): raise except_orm(_('Error'), _('Date range not valid.')) if not self.partner_ids and not recalc: raise except_orm(_('Error'), _('No customers assigned to the route')) domain = [ ('date', '>=', start_date), ('route_id', '=', self.id), ] if not delete: domain.append(('date', '<=', end_date)) detail_objs = self.env['route.detail'].search(domain) # Create a detail for the date and add the customer to the list if detail_objs: detail_objs.unlink() for p_info in self.partner_ids: reg = p_info.regularity if p_info.init_date: # Get specific date start dt_sta = datetime.strptime(p_info.init_date, FORMAT) # Check Dates Again # if not self._valid_dates(dt_sta, dt_end): # raise except_orm(_('Error'), # _('Date range not valid.')) interval = 1 if reg == '1_week' else (2 if reg == '2_week' else (3 if reg == '3_week' else (4 if reg == '4_week' else (1 if reg == '3yes_1no' else (1 if reg == '3no_1yes' else (1 if reg == '2yes_2no' else False)))))) # To include end date in rrules if dt_end.weekday() == day_number: dt_end = dt_end + timedelta(days=1) rrules = rrule(WEEKLY, dtstart=dt_sta, interval=interval, byweekday=day_number).between(dt_sta, dt_end, inc=True) customer_dates = [datetime.strftime(x, FORMAT) for x in rrules] if not customer_dates and not recalc: raise except_orm(_('Error'), _('Imposible to schedule dates between %s and \ %s with regularity of %s \ week(s)' % (start_date, end_date, str(interval)))) to_remove = [] if reg == '3yes_1no': count = 0 for date in customer_dates: count += 1 if count == 4: to_remove.append(date) count = 0 if reg == '2yes_2no': count = 0 for date in customer_dates: count += 1 if count >= 3: if count == 3: to_remove.append(date) else: to_remove.append(date) count = 0 if reg == '3no_1yes': count = 0 for date in customer_dates: count += 1 if count in (1,2,3): to_remove.append(date) else: count = 0 for date in to_remove: customer_dates.remove(date) for date in customer_dates: domain = [ ('date', '=', date), ('route_id', '=', p_info.route_id.id), ] detail_objs = self.env['route.detail'].search(domain) # Create a detail for the date and add the customer to de list if not detail_objs: vals = { 'route_id': p_info.route_id.id, 'date': date, 'state': 'pending', } det_obj = self.env['route.detail'].create(vals) # Detail obj already exists for the date, re-write it else: if len(detail_objs) > 1: # Bad situation raise except_orm(_('Error'), _('2 details of same day for same \ route')) det_obj = detail_objs[0] if det_obj.state in ['done', 'on_course']: raise except_orm(_('Error'), _('Can not re-schedule a route in %s \ state' % det_obj.state)) # Put the existing detail to pending det_obj.write({'state': 'pending'}) # Check if customer is already in customers lists domain = [('detail_id', '=', det_obj.id), ('customer_id', '=', p_info.partner_id.id)] cust_objs = self.env['customer.list'].search(domain) if cust_objs: cust_objs.unlink() # Delete the customer list regiser # Create a customer list record for the detail if self.type != 'telesale': # Add customer to customer lists of detail vals = { 'detail_id': det_obj.id, 'sequence': p_info.sequence, 'customer_id': p_info.partner_id.id, # 'result': 'pending' } self.env['customer.list'].create(vals) # Create the list of calls else: det_name = det_obj.name_get()[0][1] vals = { 'name': _("Telesale Call ") + p_info.partner_id.name, 'partner_id': p_info.partner_id.id, 'detail_id': det_obj.id, 'description': _("Scheduled Call from %s" % det_name), 'date': det_obj.date + " 06:00:00" } self.env['crm.phonecall'].create(vals)
def _ubl_add_order_ref(self, cr, uid, ubl_list, inv, context=None): ubl_ref = context.get("ubl_ref") if not ubl_ref and not inv.ubl_ref and not inv.name: raise osv.except_osv(_("Error"), _("No Order Reference!")) ubl_list.append(("cac:OrderReference", [("cbc:ID", ubl_ref or inv.ubl_ref or inv.name)]))
def _ubl_profile(self, cr, uid, inv, context): profile = self.pool.get("ubl.profile")._get_ubl(cr, uid, context) if not profile: raise osv.except_osv(_("Error"), _("No UBL Profile defined!")) return profile
def update_price_based_on_purchase_currency(self, cr, uid, value, pricelist_id, product_id, context): if not product_id or not pricelist_id: return pricelist_data_obj = self.pool.get('product.pricelist').browse( cr, uid, [pricelist_id], context=context)[0] # not in purchase currency condition. #if not pricelist_data_obj.use_purchase_currency: # return value # get price_unit original_price = value.get('value', {}).get('price_unit', -1) #Jimmy add 2016-01-21 11:27 if original_price == 0: original_price = self.get_purchase_price(cr, pricelist_id, product_id) # update price based on purchase_invoice_currency # get invoice currency invoice_currency_id = pricelist_data_obj.currency_id.id # get purchase currency product_pool = self.pool.get('product.product') product_obj = product_pool.browse(cr, uid, product_id, context=context) purchase_curr_id = product_obj.purchase_currency_id.id warning_msgs = "" if not purchase_curr_id: # no set purchase currency. # todo raise warning warn_msg = _("""Product Purchase Curreny is not configured yet.\n" "use company currency \n.""") warning_msgs += _("No valid product purchase currency found !:") + \ warn_msg + "\n\n" purchase_curr_id = product_obj.company_id.currency_id.id currency_obj = self.pool.get('res.currency') if purchase_curr_id != invoice_currency_id: original_price = currency_obj.compute(cr, uid, purchase_curr_id, invoice_currency_id, original_price, context=context) product_name = '.' if product_obj.description_sale: product_name += product_obj.description_sale # update price unit & currency to_update_vals = { 'price_unit': original_price, 'pur_currency_id': purchase_curr_id, 'name': product_name, } # update value.get('value', {}).update(to_update_vals) #if warning_msgs: # warning = value.get('warning', {}) # old_warning_msgs = warning.get('message', '') # warning.update({'message': old_warning_msgs + warning_msgs}) # value.update({'warning': warning}) return value
def reconcile(self, cr, uid, ids, context=None): move_line_obj = self.pool.get('account.move.line') obj_model = self.pool.get('ir.model.data') if context is None: context = {} form = self.browse(cr, uid, ids, context=context)[0] max_amount = form.max_amount or 0.0 power = form.power allow_write_off = form.allow_write_off reconciled = unreconciled = 0 if not form.account_ids: raise osv.except_osv(_('User Error!'), _('You must select accounts to reconcile.')) for account_id in form.account_ids: params = (account_id.id, ) if not allow_write_off: query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL AND state <> 'draft' GROUP BY partner_id HAVING ABS(SUM(debit-credit)) = 0.0 AND count(*)>0""" else: query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL AND state <> 'draft' GROUP BY partner_id HAVING ABS(SUM(debit-credit)) < %s AND count(*)>0""" params += (max_amount, ) # reconcile automatically all transactions from partners whose balance is 0 cr.execute(query, params) partner_ids = [id for (id, ) in cr.fetchall()] for partner_id in partner_ids: cr.execute( "SELECT id " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND partner_id=%s " \ "AND state <> 'draft' " \ "AND reconcile_id IS NULL", (account_id.id, partner_id)) line_ids = [id for (id, ) in cr.fetchall()] if line_ids: reconciled += len(line_ids) if allow_write_off: move_line_obj.reconcile(cr, uid, line_ids, 'auto', form.writeoff_acc_id.id, form.period_id.id, form.journal_id.id, context) else: move_line_obj.reconcile_partial(cr, uid, line_ids, 'manual', context=context) # get the list of partners who have more than one unreconciled transaction cr.execute( "SELECT partner_id " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " \ "AND partner_id IS NOT NULL " \ "GROUP BY partner_id " \ "HAVING count(*)>1", (account_id.id,)) partner_ids = [id for (id, ) in cr.fetchall()] #filter? for partner_id in partner_ids: # get the list of unreconciled 'debit transactions' for this partner cr.execute( "SELECT id, debit " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND partner_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " \ "AND debit > 0 " \ "ORDER BY date_maturity", (account_id.id, partner_id)) debits = cr.fetchall() # get the list of unreconciled 'credit transactions' for this partner cr.execute( "SELECT id, credit " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND partner_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " \ "AND credit > 0 " \ "ORDER BY date_maturity", (account_id.id, partner_id)) credits = cr.fetchall() (rec, unrec) = self.do_reconcile(cr, uid, credits, debits, max_amount, power, form.writeoff_acc_id.id, form.period_id.id, form.journal_id.id, context) reconciled += rec unreconciled += unrec # add the number of transactions for partners who have only one # unreconciled transactions to the unreconciled count partner_filter = partner_ids and 'AND partner_id not in (%s)' % ','.join( map(str, filter(None, partner_ids))) or '' cr.execute( "SELECT count(*) " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " + partner_filter, (account_id.id,)) additional_unrec = cr.fetchone()[0] unreconciled = unreconciled + additional_unrec context = dict(context, reconciled=reconciled, unreconciled=unreconciled) model_data_ids = obj_model.search( cr, uid, [('model', '=', 'ir.ui.view'), ('name', '=', 'account_automatic_reconcile_view1')]) resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])[0]['res_id'] return { 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.automatic.reconcile', 'views': [(resource_id, 'form')], 'type': 'ir.actions.act_window', 'target': 'new', 'context': context, }
def _rec_message(self, cr, uid, ids, context=None): return _('Error ! You can not create recursive Menu.')
def make_po(self, cr, uid, ids, context=None): """ Resolve the purchase from procurement, which may result in a new PO creation, a new PO line creation or a quantity change on existing PO line. Note that some operations (as the PO creation) are made as SUPERUSER because the current user may not have rights to do it (mto product launched by a sale for example) @return: dictionary giving for each procurement its related resolving PO line. """ res = {} company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id po_obj = self.pool.get('purchase.order') po_line_obj = self.pool.get('purchase.order.line') seq_obj = self.pool.get('ir.sequence') pass_ids = [] linked_po_ids = [] sum_po_line_ids = [] for procurement in self.browse(cr, uid, ids, context=context): partner = self._get_product_supplier(cr, uid, procurement, context=context) if not partner: self.message_post(cr, uid, [procurement.id], _('There is no supplier associated to product %s') % (procurement.product_id.name)) res[procurement.id] = False else: schedule_date = self._get_purchase_schedule_date(cr, uid, procurement, company, context=context) purchase_date = self._get_purchase_order_date(cr, uid, procurement, company, schedule_date, context=context) line_vals = self._get_po_line_values_from_proc(cr, uid, procurement, partner, company, schedule_date, context=context) #look for any other draft PO for the same supplier, to attach the new line on instead of creating a new draft one available_draft_po_ids = [] #po_obj.search(cr, uid, [ # ('partner_id', '=', partner.id), ('state', '=', 'draft'), ('picking_type_id', '=', procurement.rule_id.picking_type_id.id), # ('location_id', '=', procurement.location_id.id), ('company_id', '=', procurement.company_id.id), ('dest_address_id', '=', procurement.partner_dest_id.id)], context=context) if available_draft_po_ids: po_id = available_draft_po_ids[0] po_rec = po_obj.browse(cr, uid, po_id, context=context) #if the product has to be ordered earlier those in the existing PO, we replace the purchase date on the order to avoid ordering it too late if datetime.strptime(po_rec.date_order, DEFAULT_SERVER_DATETIME_FORMAT) > purchase_date: po_obj.write(cr, uid, [po_id], {'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}, context=context) #look for any other PO line in the selected PO with same product and UoM to sum quantities instead of creating a new po line available_po_line_ids = po_line_obj.search(cr, uid, [('order_id', '=', po_id), ('product_id', '=', line_vals['product_id']), ('product_uom', '=', line_vals['product_uom'])], context=context) if available_po_line_ids: po_line = po_line_obj.browse(cr, uid, available_po_line_ids[0], context=context) po_line_id = po_line.id new_qty, new_price = self._calc_new_qty_price(cr, uid, procurement, po_line=po_line, context=context) if new_qty > po_line.product_qty: po_line_obj.write(cr, SUPERUSER_ID, po_line.id, {'product_qty': new_qty, 'price_unit': new_price}, context=context) sum_po_line_ids.append(procurement.id) else: line_vals.update(order_id=po_id) po_line_id = po_line_obj.create(cr, SUPERUSER_ID, line_vals, context=context) linked_po_ids.append(procurement.id) else: name = seq_obj.get(cr, uid, 'purchase.order') or _('PO: %s') % procurement.name po_vals = { 'name': name, 'origin': procurement.origin, 'partner_id': partner.id, 'location_id': procurement.location_id.id, 'picking_type_id': procurement.rule_id.picking_type_id.id, 'pricelist_id': partner.property_product_pricelist_purchase.id, 'currency_id': partner.property_product_pricelist_purchase and partner.property_product_pricelist_purchase.currency_id.id or procurement.company_id.currency_id.id, 'date_order': purchase_date.strftime(DEFAULT_SERVER_DATETIME_FORMAT), 'company_id': procurement.company_id.id, 'fiscal_position': po_obj.onchange_partner_id(cr, uid, None, partner.id, context=context)['value']['fiscal_position'], 'payment_term_id': partner.property_supplier_payment_term.id or False, 'dest_address_id': procurement.partner_dest_id.id, } po_id = self.create_procurement_purchase_order(cr, SUPERUSER_ID, procurement, po_vals, line_vals, context=context) po_line_id = po_obj.browse(cr, uid, po_id, context=context).order_line[0].id pass_ids.append(procurement.id) res[procurement.id] = po_line_id self.write(cr, uid, [procurement.id], {'purchase_line_id': po_line_id}, context=context) if pass_ids: self.message_post(cr, uid, pass_ids, body=_("Draft Purchase Order created"), context=context) if linked_po_ids: self.message_post(cr, uid, linked_po_ids, body=_("Purchase line created and linked to an existing Purchase Order"), context=context) if sum_po_line_ids: self.message_post(cr, uid, sum_po_line_ids, body=_("Quantity added in existing Purchase Order Line"), context=context) return res
def copy(self, cr, uid, id, default=None, context=None): raise osv.except_osv( _("Operation not supported"), _("You cannot duplicate a campaign, Not supported yet."))
def get_worked_day_lines(self, cr, uid, contract_ids, date_from, date_to, context=None): """ @param contract_ids: list of contract id @return: returns a list of dict containing the input that should be applied for the given contract between date_from and date_to """ def was_on_leave(employee_id, datetime_day, context=None): res = False day = datetime_day.strftime("%Y-%m-%d") holiday_ids = self.pool.get('hr.holidays').search(cr, uid, [('state','=','validate'),('employee_id','=',employee_id),('type','=','remove'),('date_from','<=',day),('date_to','>=',day)]) if holiday_ids: res = self.pool.get('hr.holidays').browse(cr, uid, holiday_ids, context=context)[0].holiday_status_id.name return res res = [] for contract in self.pool.get('hr.contract').browse(cr, uid, contract_ids, context=context): print "1111mmmmmmmmmm" if not contract.working_hours: #fill only if the contract as a working schedule linked attendances = { 'name': _("Normal Working Hours paid at 100%"), 'sequence': 0, 'code': 'HPR', 'number_of_days': 0.0, 'number_of_hours': 0.0, 'contract_id': contract.id, } print "22222222nnnnnnnnnnnn" res += [attendances] continue attendances = { 'name': _("Normal Working Days paid at 100%"), 'sequence': 1, 'code': 'WORK100', 'number_of_days': 0.0, 'number_of_hours': 0.0, 'contract_id': contract.id, } leaves = {} day_from = datetime.strptime(date_from,"%Y-%m-%d") day_to = datetime.strptime(date_to,"%Y-%m-%d") nb_of_days = (day_to - day_from).days + 1 for day in range(0, nb_of_days): working_hours_on_day = self.pool.get('resource.calendar').working_hours_on_day(cr, uid, contract.working_hours, day_from + timedelta(days=day), context) if working_hours_on_day: #the employee had to work leave_type = was_on_leave(contract.employee_id.id, day_from + timedelta(days=day), context=context) if leave_type: #if he was on leave, fill the leaves dict if leave_type in leaves: leaves[leave_type]['number_of_days'] += 1.0 leaves[leave_type]['number_of_hours'] += working_hours_on_day else: leaves[leave_type] = { 'name': leave_type, 'sequence': 5, 'code': leave_type, 'number_of_days': 1.0, 'number_of_hours': working_hours_on_day, 'contract_id': contract.id, } else: #add the input vals to tmp (increment if existing) attendances['number_of_days'] += 1.0 attendances['number_of_hours'] += working_hours_on_day leaves = [value for key,value in leaves.items()] res += [attendances] + leaves return res
def import_one_storeview_orders(self, cr, uid, job, storeview, payment_defaults, defaults, mappinglines=False, context=None): start_time = False if not storeview.warehouse: raise osv.except_osv( _('Config Error'), _('Storeview %s has no warehouse. You must assign a warehouse in order to import orders' ) % storeview.name) #This needs to be reconsidered. If there is an error, it will skip it # if storeview.import_orders_start_datetime and not \ # storeview.last_import_datetime: start_time = storeview.import_orders_start_datetime end_time = storeview.import_orders_end_datetime skip_status = storeview.skip_order_status use_company = job.mage_instance.use_company if storeview.last_import_datetime: start_time = storeview.last_import_datetime if storeview.invoice_policy: defaults.update({'order_policy': storeview.invoice_policy}) if storeview.picking_policy: defaults.update({'picking_policy': storeview.picking_policy}) if not job.mage_instance.order_statuses and not storeview.allow_storeview_level_statuses: statuses = DEFAULT_STATUS_FILTERS elif storeview.allow_storeview_level_statuses and storeview.order_statuses: if job.mage_instance.states_or_statuses == 'state': statuses = [ s.mage_order_state for s in storeview.order_statuses ] else: statuses = [ s.mage_order_status for s in storeview.order_statuses ] else: if job.mage_instance.states_or_statuses == 'state': statuses = [ s.mage_order_state for s in job.mage_instance.order_statuses ] else: statuses = [ s.mage_order_status for s in job.mage_instance.order_statuses ] filters = { 'store_id': { '=': storeview.external_id }, 'status': { 'in': statuses } } if start_time: filters.update({'created_at': {'gteq': start_time}}) if end_time: dict = {'lteq': end_time} filters.update({'CREATED_AT': dict}) #Make the external call and get the order ids #Calling info is really inefficient because it loads data we dont need print 'Filters', filters order_data = self._get_job_data(cr, uid, job, 'sales_order.search', [filters]) if not order_data: print 'No Data' return True #The following code needs a proper implementation, #However this code will be very fast in excluding unnecessary orders #and do a good job of pre-filtering order_basket = [] order_ids = [x['increment_id'] for x in order_data] for id in order_ids: new_val = "('" + id + "')" order_basket.append(new_val) val_string = ','.join(order_basket) query = """WITH increments AS (VALUES %s) \ SELECT column1 FROM increments \ LEFT OUTER JOIN sale_order ON \ (increments.column1 = sale_order.mage_order_number) \ WHERE sale_order.mage_order_number IS NULL""" % val_string cr.execute(query) res = cr.fetchall() increment_ids = [z[0] for z in res] increment_ids.sort() increment_ids = order_ids datas = [ increment_ids[i:i + 300] for i in range(0, len(increment_ids), 300) ] for dataset in datas: try: orders = self._get_job_data(cr, uid, job, 'sales_order.multiload', [dataset]) except Exception, e: print 'Could not retrieve multiple order info' continue if not orders: continue for order in orders: #TODO: Add proper logging and debugging order_obj = self.pool.get('sale.order') order_ids = order_obj.search( cr, uid, [('mage_order_number', '=', order['increment_id'])]) if order_ids: if not skip_status: status = self.set_one_order_status( cr, uid, job, order, 'imported', 'Order Imported') print 'Skipping existing order %s' % order['increment_id'] continue try: sale_order = self.process_one_order( cr, uid, job, order, storeview, payment_defaults, defaults, mappinglines, use_company) #Implement something to auto approve if configured # sale_order.action_button_confirm() except Exception, e: print 'Exception Processing Order with Id: %s' % order[ 'increment_id'], e continue if not skip_status: status = self.set_one_order_status(cr, uid, job, order, 'imported', 'Order Imported') if not status: print 'Created order but could not notify Magento' print 'Successfully Imported order with ID: %s' % order[ 'increment_id'] #Once the order flagged in the external system, we must commit #Because it is not possible to rollback in an external system cr.commit()
def action_send_mail(self, email_to, model, edi_select, object_id, mail_id=False, update_context_other=None): """ Fonction qui permet de remplir et d'appeller le wizard d'envoi des mails :param email_to: Partenaire auquel on souhaite envoyer le mail :type email_to: recordset(res.partner) :param model: Objet pour lequel on recherchera un modèle de mail :type model: Char (exemple:'sale.order') :param edi_select: Permet de passer une valeur edi pour la recherche du modèle :type edi_select: Char :param object_id: Id de l'objet depuis lequel on envoie le mail :type object_id: integer :param mail_id: Optionnel: permet de forcer un template de mail :type mail_id: recordset(mail.template) """ templates_obj = self.env['mail.template'] model_obj = self.env['ir.model'] model_id = model_obj.search([('model', '=', model)], limit=1) #Si on a pas passé de modèle spécifique, on recherche celui lié à l'edi et au modèle d'objet if not mail_id: mail_id = templates_obj.search([('edi_select', '=', edi_select), ('model_id', '=', model_id.id)], limit=1) if not mail_id: mail_id = templates_obj.search( [('model_id', '=', model_id.id)], limit=1) mail_dict = mail_id.get_email_template([object_id]) attachments = {} if mail_dict and mail_dict.get(object_id): mail = mail_dict[object_id] #On rempli le wizard (destinataire, sujet...) context = self.env.context.copy() context.update({ 'default_email_from': templates_obj.render_template(mail.email_from, mail.model_id.model, object_id), 'default_email_to': templates_obj.render_template(mail.email_to, mail.model_id.model, object_id), 'default_email_cc': templates_obj.render_template(mail.email_cc, mail.model_id.model, object_id), 'default_reply_to': templates_obj.render_template(mail.reply_to, mail.model_id.model, object_id), 'default_subject': templates_obj.render_template(mail.subject, mail.model_id.model, object_id), 'default_body': templates_obj.render_template(mail.body_html, mail.model_id.model, object_id), 'default_template_id': mail_id.id, 'default_use_template': bool(mail), 'model_objet': model, 'default_id_active': object_id, }) if update_context_other: context.update(update_context_other) #Ajout des éventuelles pièces jointes for attach in mail.attachment_ids: attachments[attach.datas_fname] = attach.datas if attachments: attachment = attachments attachment_obj = self.env['ir.attachment'] att_ids = [] for fname, fcontent in attachment.iteritems(): data_attach = { 'name': fname, 'datas': fcontent, 'datas_fname': fname, 'description': fname, 'res_model': mail.model_id.model, 'res_id': object_id, } att_ids.append(attachment_obj.create(data_attach).id) context['default_attachment_ids'] = att_ids #Recherche et renvoi de l'action du wizard action_struc = {} obj = self.env[model].browse(object_id) action_dict = get_form_view(obj, 'partner_openprod.wizard_send_mail') if action_dict and action_dict.get('id') and action_dict.get( 'type'): action = self.env[action_dict['type']].browse( action_dict['id']) action_struc = action.read() action_struc[0]['context'] = context action_struc = action_struc[0] return action_struc else: raise ValidationError( _('There is no mail template for %s. Please create a mail model ' 'in the configuration menu.' % (model))) return False
def _get_company_detail(self, form, analytic_acc=False): res = [] period_pool = self.pool.get('account.period') account_pool = self.pool.get('account.account') budget_line_pool = self.pool.get('account.budget.lines') fisc_budget_line_pool = self.pool.get('account.fiscalyear.budget.lines') account_chart = form.get('chart_account_id', []) analytic_chart = analytic_acc and analytic_acc or form.get('chart_analytic_account_id', []) period_from = form.get('period_from', False) period_to = form.get('period_to', False) self.total = {'planned_amount':0.0, 'next_planned_amount':0.0, 'balance':0.0} period_from_start = period_from and period_pool.browse(self.cr, self.uid, period_from, context=self.context).date_start or '' period_stop = period_to and period_pool.browse(self.cr, self.uid, period_to, context=self.context).date_stop or '' current_periods = period_pool.search(self.cr, self.uid, [('fiscalyear_id', '=', self.fiscalyear.id)], context=self.context) next_periods = period_pool.search(self.cr, self.uid, [('fiscalyear_id', '=', self.next_fiscalyear.id)], context=self.context) analytic_child_ids = self._get_children_and_consol(self.cr, self.uid, analytic_chart, 'account.analytic.account', self.context) account_child_ids = self._get_children_and_consol(self.cr, self.uid, account_chart, 'account.account', self.context) general_account = self._sort_filter(self.cr, self.uid, account_child_ids, context=self.context) budget_class = {'id':False, 'name':'', 'class':''} class_total = {'planned_amount':0.0, 'next_planned_amount':0.0, 'balance':0.0} for account in account_pool.browse(self.cr, self.uid, general_account, context=self.context): classification = account.budget_classification and account.budget_classification[0] or False if budget_class['id'] != classification.id: if budget_class['id'] != False: res.append({'code':'*', 'class':budget_class['class'], 'name':budget_class['name'], 'balance': class_total['balance'], 'planned_amount':class_total['planned_amount'], 'next_planned_amount':class_total['next_planned_amount']}) class_total = {'planned_amount':0.0, 'next_planned_amount':0.0, 'balance':0.0} budget_class['id'] = classification.id account_budget = {'code':account.code, 'name':account.name, 'planned_amount':0.0, 'next_planned_amount':0.0, 'balance':0.0} current_lines = budget_line_pool.search(self.cr, self.uid, [('period_id', 'in', current_periods), ('analytic_account_id', 'in', analytic_child_ids), ('general_account_id', '=', account.id)], context=self.context) next_lines = fisc_budget_line_pool.search(self.cr, self.uid, [('fiscalyear_id', '=', self.next_fiscalyear.id), ('analytic_account_id', 'in', analytic_child_ids), ('general_account_id', '=', account.id)], context=self.context) bal_lines = budget_line_pool.search(self.cr, self.uid, [('period_id', 'in', self.periods), ('analytic_account_id', 'in', analytic_child_ids), ('general_account_id', '=', account.id)], context=self.context) if current_lines: for line in budget_line_pool.browse(self.cr, self.uid, current_lines, context=self.context): account_budget['planned_amount'] += line.planned_amount self.total['planned_amount'] += account_budget['planned_amount'] class_total['planned_amount'] += account_budget['planned_amount'] if res: if res[len(res) - 1]['code'] == account_budget['code'] and account_budget['code'] != '*': res[len(res) - 1]['planned_amount'] += account_budget['planned_amount'] if next_lines: for line in fisc_budget_line_pool.browse(self.cr, self.uid, next_lines, context=self.context): account_budget['next_planned_amount'] += line.planned_amount self.total['next_planned_amount'] += account_budget['next_planned_amount'] class_total['next_planned_amount'] += account_budget['next_planned_amount'] if res: if res[len(res) - 1]['code'] == account_budget['code'] and account_budget['code'] != '*': res[len(res) - 1]['next_planned_amount'] += account_budget['next_planned_amount'] if bal_lines: for line in budget_line_pool.browse(self.cr, self.uid, bal_lines, context=self.context): account_budget['balance'] += line.balance + line.confirm self.total['balance'] += account_budget['balance'] class_total['balance'] += account_budget['balance'] if res: if res[len(res) - 1]['code'] == account_budget['code'] and account_budget['code'] != '*': res[len(res) - 1]['balance'] += account_budget['balance'] res.append(account_budget) budget_class['name'] = classification.name budget_class['class'] = classification.code res.append({ 'code':'*', 'name':budget_class['name'], 'class':budget_class['class'] or 1, 'planned_amount':class_total['planned_amount'], 'next_planned_amount':class_total['next_planned_amount'], 'balance':class_total['balance'], }) res.append({ 'code': '*', 'name': _('Total'), 'planned_amount': self.total['planned_amount'], 'next_planned_amount': self.total['next_planned_amount'], 'balance': self.total['balance'], }) return res
def _get_location_options(self): """@return a list of tuples with the selection field options. """ return [('undefine', _('Undefine')), ('international', _('International')), ('national', _('National'))]
def periodic_print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data = {} data['ids'] = context.get('active_ids', []) data['model'] = context.get('active_model', 'ir.ui.menu') data['form'] = self.read(cr, uid, ids[0]) ap_obj = self.pool.get('account.period') if data['form']['filter'] == 'byperiod': data['form']['date_from'] = '' data['form']['date_to'] = '' data['form']['periods'] = self.find_periods(cr, uid, data['form']['fiscalyear'],data['form']['org_periods_from'], data['form']['org_periods_to']) elif data['form']['filter'] == 'bydate': self._check_date(cr, uid, data) data['form']['periods'] = [] elif data['form']['filter'] == 'none': data['form']['date_from'] = '' data['form']['date_to'] = '' data['form']['periods'] = [] elif data['form']['filter'] == False: raise osv.except_osv(_('Error !'),_('Select filter in Filters.')) else: self._check_date(cr, uid, data) data['form']['periods'] = self.find_periods(cr, uid, data['form']['fiscalyear'],data['form']['org_periods_from'], data['form']['org_periods_to']) period_by_date = str(ap_obj.search(cr, uid, [('fiscalyear_id','=',data['form']['fiscalyear'][0]),('date_start','>=',data['form']['date_from']),('date_stop','<=',data['form']['date_to'])],)) lis2 = str(data['form']['periods']).replace("[","(").replace("]",")") sqlmm = """select min(p.date_start) as inicio, max(p.date_stop) as fin from account_period p where p.id in %s""" % lis2 cr.execute(sqlmm) minmax = cr.dictfetchall() if minmax: if (data['form']['date_to'] < minmax[0]['inicio']) or (data['form']['date_from'] > minmax[0]['fin']): raise osv.except_osv(_('Error !'),_('La interseccion entre el periodo y fecha es vacio')) data['form']['compr0_periods'] =[] if data['form']['compr0_fiscalyear_id']: if data['form']['compr0_filter'] == 'byperiod': data['form']['compr0_periods'] = self.find_periods(cr, uid, data['form']['compr0_fiscalyear_id'],data['form']['compr0_periods_from'], data['form']['compr0_periods_to']) # data['form']['compr0_periods'] = ap_obj.search(cr, uid, [('fiscalyear_id','=',data['form']['compr0_fiscalyear_id'][0]),('date_start','>=',data['form']['compr0_date_from']),('date_stop','<=',data['form']['compr0_date_to'])], ) data['form']['compr0_date_from'] = '' data['form']['compr0_date_to'] = '' elif data['form']['compr0_filter'] == "bydate": self._compr0_check_date(cr, uid, data) data['form']['compr0_periods_from'] = '' data['form']['compr0_periods_to'] = '' elif data['form']['compr0_filter'] == 'none': data['form']['compr0_date_from'] = '' data['form']['compr0_date_to'] ='' data['form']['compr0_periods_from'] = '' data['form']['compr0_periods_to'] = '' elif data['form']['compr1_filter'] == False: raise osv.except_osv(_('Error !'),_('Select filter in Comparison1.')) else: self._compr0_check_date(cr, uid, data) lis2 = str(ap_obj.search(cr, uid, [('fiscalyear_id','=',data['form']['compr0_fiscalyear_id'][0]),('date_start','>=',data['form']['compr0_date_from']),('date_stop','<=',data['form']['compr0_date_to'])], )) sqlmm = """select min(p.date_start) as inicio, max(p.date_stop) as fin from account_period p where p.id in %s"""% str(lis2).replace("[","(").replace("]",")") cr.execute(sqlmm) minmax = cr.dictfetchall() if minmax: if (data['form']['compr0_date_to'] < minmax[0]['inicio']) or (data['form']['compr0_date_from'] > minmax[0]['fin']): raise osv.except_osv(_('Error !'),_('La interseccion entre el periodo y fecha es vacio')) data['form']['compr1_periods'] = [] if data['form']['compr1_fiscalyear_id']: if data['form']['compr1_filter'] == 'byperiod': data['form']['compr1_periods'] = self.find_periods(cr, uid, data['form']['compr1_fiscalyear_id'],data['form']['compr1_periods_from'], data['form']['compr1_periods_to']) data['form']['compr1_date_from'] = '' data['form']['compr1_date_to'] = '' elif data['form']['compr1_filter'] == "bydate": self._compr1_check_date(cr, uid, data) data['form']['compr1_periods_from'] = '' data['form']['compr1_periods_to'] = '' elif data['form']['compr1_filter'] == 'none': data['form']['compr1_date_from'] = '' data['form']['compr1_date_to'] = '' data['form']['compr1_periods_from'] = '' data['form']['compr1_periods_to'] = '' elif data['form']['compr1_filter'] == False: raise osv.except_osv(_('Error !'),_('Select filter in Comparison2.')) else: self._compr1_check_date(cr, uid, data) lis2 = str(ap_obj.search(cr, uid, [('fiscalyear_id','=',data['form']['compr1_fiscalyear_id'][0]),('date_start','>=',data['form']['compr1_date_from']),('date_stop','<=',data['form']['compr1_date_to'])], )) sqlmm = """select min(p.date_start) as inicio, max(p.date_stop) as fin from account_period p where p.id in %s"""% str(lis2).replace("[","(").replace("]",")") cr.execute(sqlmm) minmax = cr.dictfetchall() if minmax: if (data['form']['compr1_date_to'] < minmax[0]['inicio']) or (data['form']['compr1_date_from'] > minmax[0]['fin']): raise osv.except_osv(_('Error !'),_('La interseccion entre el periodo y fecha es vacio')) if data['form']['periodic_columns'] == 'one': name = 'periodic1.1cols' if data['form']['periodic_columns'] == 'two': name="periodic.2cols" if data['form']['compr0_fiscalyear_id'] and data['form']['periodic_columns'] == 'one': name = 'periodic2.1cols' if data['form']['compr1_fiscalyear_id'] and data['form']['periodic_columns'] == 'one': name = 'periodic3.1cols' if data['form']['compr0_fiscalyear_id'] and data['form']['periodic_columns'] == 'two': name = 'periodic1.2cols' if data['form']['compr1_fiscalyear_id'] and data['form']['periodic_columns'] == 'two': name = 'periodic2.2cols' if data['form']['periodic_columns'] == 'four': if data['form']['inf_type'] == 'GL': name = 'afr.analytic.ledger' else: name = 'periodic.4cols' if data['form']['periodic_columns'] == 'four' and data['form']['compr0_fiscalyear_id']: name = 'periodic2.4cols' if data['form']['periodic_columns'] == 'four' and data['form']['compr1_fiscalyear_id']: name = 'periodic3.4cols' return {'type': 'ir.actions.report.xml', 'report_name': name, 'datas': data}
def _get_trans(self, source): return _(source)
def calculation(self, cr, uid, ids, transfer, context=None): """Method that calculates employee's end of service allowance and adds a record to hr.employment.termination.lines. @return: Boolean True """ transfer = transfer == True and transfer or False payroll = self.pool.get('payroll') allow_list = [] for rec in self.browse(cr, uid, ids, context=context): self.pool.get('hr.employment.termination.lines').unlink( cr, uid, [l.id for l in rec.line_ids], context) exception_allow_deduct_obj = self.pool.get( 'hr.allowance.deduction.exception') allow_ids = exception_allow_deduct_obj.search( cr, uid, [('employee_id', '=', rec.employee_id.id), ('action', '=', 'special'), ('types', '=', 'allow')]) allow = exception_allow_deduct_obj.browse(cr, uid, allow_ids) deduct_ids = exception_allow_deduct_obj.search( cr, uid, [('employee_id', '=', rec.employee_id.id), ('action', '=', 'special'), ('types', '=', 'deduct')]) deduct = exception_allow_deduct_obj.browse(cr, uid, deduct_ids) total_allow = 0 for a in allow: current_date = mx.DateTime.Parser.DateTimeFromString( rec.dismissal_date) end_date = mx.DateTime.Parser.DateTimeFromString(a.end_date) emp_end_date_days = (end_date - current_date).days day = a.amount / 30 allownce = emp_end_date_days * day #print"total" ,total_allow ,emp_end_date_days ,allownce ,a ,a.allow_deduct_id.account_id.id,a.id allownce_id = self.pool.get( 'hr.employment.termination.lines').create( cr, uid, { 'allow_deduct_id': a.allow_deduct_id.id, 'account_id': a.allow_deduct_id.account_id.id, 'termination_id': rec.id, 'amount': allownce, 'name': a.allow_deduct_id.name }) allow_list.append(allownce_id) for d in deduct: current_date = mx.DateTime.Parser.DateTimeFromString( rec.dismissal_date) end_date = mx.DateTime.Parser.DateTimeFromString(a.end_date) emp_end_date_days = (end_date - current_date).days day = d.amount / 30 deduct = emp_end_date_days * day #print"$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$deduct" ,emp_end_date_days ,deduct ,d.id deduct_id = self.pool.get( 'hr.employment.termination.lines').create( cr, uid, { 'allow_deduct_id': d.allow_deduct_id.id, 'account_id': d.allow_deduct_id.account_id.id, 'termination_id': rec.id, 'amount': -deduct, 'name': d.allow_deduct_id.name }) allow_list.append(deduct_id) allowance_ids = rec.dismissal_type.allowance_ids if not allowance_ids: raise orm.except_orm(_('Sorry'), _('No Allwances to be calculated')) for allow in allowance_ids: amount = payroll.compute_allowance_deduction( cr, uid, rec.employee_id, allow.id) line_id = self.pool.get('hr.employment.termination.lines').create( cr, uid, { 'allow_deduct_id': allow.id, 'account_id': allow.account_id.id, 'termination_id': rec.id, 'amount': amount['amount'], 'name': allow.name }) allow_list.append(line_id) self.write(cr, uid, ids, { 'state': 'calculate', 'date': time.strftime('%Y-%m-%d') }, context=context) return allow_list
def sum_dr(self): if self.res_pl['type'] == _('Net Profit'): self.result_sum_dr += self.res_pl['balance'] return self.result_sum_dr
def get_data(self, data): def get_account_repr(account, account_type): return { 'code': account.code, 'name': account.name, 'level': account.level, 'balance': account.balance and (account_type == 'income' and -1 or 1) * account.balance, 'type': account.type, } cr, uid = self.cr, self.uid account_pool = self.pool['account.account'] currency_pool = self.pool['res.currency'] types = ['expense', 'income'] ctx = self.context.copy() ctx['fiscalyear'] = data['form'].get('fiscalyear_id', False) if ctx['fiscalyear']: ctx['fiscalyear'] = ctx['fiscalyear'][0] if data['form']['filter'] == 'filter_period': ctx['periods'] = data['form'].get('periods', False) elif data['form']['filter'] == 'filter_date': ctx['date_from'] = data['form'].get('date_from', False) ctx['date_to'] = data['form'].get('date_to', False) ctx['state'] = data['form'].get('target_move', 'all') cal_list = {} account_id = data['form'].get('chart_account_id', False) if account_id: account_id = account_id[0] account_ids = account_pool._get_children_and_consol(cr, uid, account_id, context=ctx) accounts = account_pool.browse(cr, uid, account_ids, context=ctx) for typ in types: accounts_temp = [] for account in accounts: if (account.user_type.report_type) and ( account.user_type.report_type == typ): currency = (account.currency_id and account.currency_id or account.company_id.currency_id) if typ == 'expense' and account.type != 'view' and ( account.debit != account.credit): self.result_sum_dr += account.debit - account.credit if typ == 'income' and account.type != 'view' and ( account.debit != account.credit): self.result_sum_cr += account.credit - account.debit if data['form']['display_account'] == 'bal_movement': if (not currency_pool.is_zero(self.cr, self.uid, currency, account.credit) ) or (not currency_pool.is_zero( self.cr, self.uid, currency, account.debit)) or (not currency_pool.is_zero( self.cr, self.uid, currency, account.balance)): accounts_temp.append(get_account_repr( account, typ)) elif data['form']['display_account'] == 'bal_solde': if not currency_pool.is_zero( self.cr, self.uid, currency, account.balance): accounts_temp.append(get_account_repr( account, typ)) else: accounts_temp.append(get_account_repr(account, typ)) if self.result_sum_dr > self.result_sum_cr: self.res_pl['type'] = _('Net Loss') self.res_pl['balance'] = (self.result_sum_dr - self.result_sum_cr) else: self.res_pl['type'] = _('Net Profit') self.res_pl['balance'] = (self.result_sum_cr - self.result_sum_dr) self.result[typ] = accounts_temp cal_list[typ] = self.result[typ] if cal_list: temp = {} for i in range( 0, max(len(cal_list['expense']), len(cal_list['income']))): if i < len(cal_list['expense']) and i < len( cal_list['income']): temp = { 'code': cal_list['expense'][i]['code'], 'name': cal_list['expense'][i]['name'], 'level': cal_list['expense'][i]['level'], 'balance': cal_list['expense'][i]['balance'], 'type': cal_list['expense'][i]['type'], 'code1': cal_list['income'][i]['code'], 'name1': cal_list['income'][i]['name'], 'level1': cal_list['income'][i]['level'], 'balance1': cal_list['income'][i]['balance'], 'type1': cal_list['income'][i]['type'], } self.result_temp.append(temp) else: if i < len(cal_list['income']): temp = { 'code': '', 'name': '', 'level': False, 'balance': False, 'type': False, 'code1': cal_list['income'][i]['code'], 'name1': cal_list['income'][i]['name'], 'level1': cal_list['income'][i]['level'], 'balance1': cal_list['income'][i]['balance'], 'type1': cal_list['income'][i]['type'], } self.result_temp.append(temp) if i < len(cal_list['expense']): temp = { 'code': cal_list['expense'][i]['code'], 'name': cal_list['expense'][i]['name'], 'level': cal_list['expense'][i]['level'], 'balance': cal_list['expense'][i]['balance'], 'type': cal_list['expense'][i]['type'], 'code1': '', 'name1': '', 'level1': False, 'balance1': False, 'type1': False, } self.result_temp.append(temp) return None
def project_task_create_note(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids, context=context): body = _("Task created") self.message_post(cr, uid, [procurement.id], body=body, context=context) if procurement.sale_line_id and procurement.sale_line_id.order_id: procurement.sale_line_id.order_id.message_post(body=body)
def sum_cr(self): if self.res_pl['type'] == _('Net Loss'): self.result_sum_cr += self.res_pl['balance'] return self.result_sum_cr
def generate_bbacomm(self, cr, uid, ids, type, reference_type, partner_id, reference, context=None): partner_obj = self.pool.get('res.partner') reference = reference or '' algorithm = False if partner_id: algorithm = partner_obj.browse(cr, uid, partner_id, context=context).out_inv_comm_algorithm algorithm = algorithm or 'random' if (type == 'out_invoice'): if reference_type == 'bba': if algorithm == 'date': if not self.check_bbacomm(reference): doy = time.strftime('%j') year = time.strftime('%Y') seq = '001' seq_ids = self.search(cr, uid, [('type', '=', 'out_invoice'), ('reference_type', '=', 'bba'), ('reference', 'like', '+++%s/%s/%%' % (doy, year))], order='reference') if seq_ids: prev_seq = int(self.browse(cr, uid, seq_ids[-1]).reference[12:15]) if prev_seq < 999: seq = '%03d' % (prev_seq + 1) else: raise osv.except_osv(_('Warning!'), _('The daily maximum of outgoing invoices with an automatically generated BBA Structured Communications has been exceeded!' \ '\nPlease create manually a unique BBA Structured Communication.')) bbacomm = doy + year + seq base = int(bbacomm) mod = base % 97 or 97 reference = '+++%s/%s/%s%02d+++' % (doy, year, seq, mod) elif algorithm == 'partner_ref': if not self.check_bbacomm(reference): partner_ref = self.pool.get('res.partner').browse(cr, uid, partner_id).ref partner_ref_nr = re.sub('\D', '', partner_ref or '') if (len(partner_ref_nr) < 3) or (len(partner_ref_nr) > 7): raise osv.except_osv(_('Warning!'), _('The Partner should have a 3-7 digit Reference Number for the generation of BBA Structured Communications!' \ '\nPlease correct the Partner record.')) else: partner_ref_nr = partner_ref_nr.ljust(7, '0') seq = '001' seq_ids = self.search(cr, uid, [('type', '=', 'out_invoice'), ('reference_type', '=', 'bba'), ('reference', 'like', '+++%s/%s/%%' % (partner_ref_nr[:3], partner_ref_nr[3:]))], order='reference') if seq_ids: prev_seq = int(self.browse(cr, uid, seq_ids[-1]).reference[12:15]) if prev_seq < 999: seq = '%03d' % (prev_seq + 1) else: raise osv.except_osv(_('Warning!'), _('The daily maximum of outgoing invoices with an automatically generated BBA Structured Communications has been exceeded!' \ '\nPlease create manually a unique BBA Structured Communication.')) bbacomm = partner_ref_nr + seq base = int(bbacomm) mod = base % 97 or 97 reference = '+++%s/%s/%s%02d+++' % (partner_ref_nr[:3], partner_ref_nr[3:], seq, mod) elif algorithm == 'random': if not self.check_bbacomm(reference): base = random.randint(1, 9999999999) bbacomm = str(base).rjust(7, '0') base = int(bbacomm) mod = base % 97 or 97 mod = str(mod).rjust(2, '0') reference = '+++%s/%s/%s%s+++' % (bbacomm[:3], bbacomm[3:7], bbacomm[7:], mod) else: raise osv.except_osv(_('Error!'), _("Unsupported Structured Communication Type Algorithm '%s' !" \ "\nPlease contact your OpenERP support channel.") % algorithm) return {'value': {'reference': reference}}
def unlink(self, cr, uid, ids, context=None): raise osv.except_osv(_('Error!'), _('You cannot delete any record!'))
def product_id_change_with_wh(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position_id=False, flag=False, warehouse_id=False, context=None): context = context or {} product_uom_obj = self.pool.get('product.uom') product_obj = self.pool.get('product.product') warning = {} #UoM False due to hack which makes sure uom changes price, ... in product_id_change res = self.product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=False, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position_id=fiscal_position_id, flag=flag, context=context) if not product: res['value'].update({'product_packaging': False}) return res # set product uom in context to get virtual stock in current uom if 'product_uom' in res.get('value', {}): # use the uom changed by super call context = dict(context, uom=res['value']['product_uom']) elif uom: # fallback on selected context = dict(context, uom=uom) #update of result obtained in super function product_obj = product_obj.browse(cr, uid, product, context=context) res['value'].update({'product_tmpl_id': product_obj.product_tmpl_id.id, 'delay': (product_obj.sale_delay or 0.0)}) # Calling product_packaging_change function after updating UoM res_packing = self.product_packaging_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, packaging, context=context) res['value'].update(res_packing.get('value', {})) warning_msgs = res_packing.get('warning') and res_packing['warning']['message'] or '' if product_obj.type == 'product': #determine if the product needs further check for stock availibility is_available = self._check_routing(cr, uid, ids, product_obj, warehouse_id, context=context) #check if product is available, and if not: raise a warning, but do this only for products that aren't processed in MTO if not is_available: uom_record = False if uom: uom_record = product_uom_obj.browse(cr, uid, uom, context=context) if product_obj.uom_id.category_id.id != uom_record.category_id.id: uom_record = False if not uom_record: uom_record = product_obj.uom_id compare_qty = float_compare(product_obj.virtual_available, qty, precision_rounding=uom_record.rounding) if compare_qty == -1: warn_msg = _('You plan to sell %.2f %s but you only have %.2f %s available !\nThe real stock is %.2f %s. (without reservations)') % \ (qty, uom_record.name, max(0,product_obj.virtual_available), uom_record.name, max(0,product_obj.qty_available), uom_record.name) warning_msgs += _("Not enough stock ! : ") + warn_msg + "\n\n" #update of warning messages if warning_msgs: warning = { 'title': _('Configuration Error!'), 'message' : warning_msgs } res.update({'warning': warning}) return res
def get_available_message(self, cr, uid, posid, context=None): if context is None: context = {} date_now = time.strftime("%Y-%m-%d") date_time_now = time.strftime("%Y-%m-%d %H:%M:%S") res = {} default_res = { 'm_id': None, 'm_type': 0, 'm_title': None, 'm_content': None } messages_ids = self.search(cr, uid, [('active', '=', True), ('start_at', '<=', date_now), ('stop_at', '>=', date_now), ('pos_ids', '=', posid)]) _logger.info('messages_ids : %r', messages_ids) if messages_ids: for m_id in messages_ids: message = self.browse(cr, uid, m_id, context=context) m_title = _(message.title) m_type = message.message_type m_frequency = int(message.frequency) m_interval = int(message.interval) m_message = message.message res = { 'm_id': m_id, 'm_type': m_type, 'm_title': m_title, 'm_content': m_message } if m_frequency == 1: nb_read_max = 1 else: nb_read_max = 24 date_read_start = time.strftime("%Y-%m-%d 00:00:00") date_read_stop = time.strftime("%Y-%m-%d 23:59:00") obj_read = self.pool.get('pos.message.read') read_ids = obj_read.search( cr, uid, [('pos_id', '=', posid), ('message_id', '=', m_id), ('date_read', '>', date_read_start), ('date_read', '<', date_read_stop)]) if read_ids: # once if nb_read_max == 1: res = default_res continue message_read = obj_read.browse(cr, uid, read_ids[0], context=context) mr_date_plus = datetime.strptime( message_read.date_read, "%Y-%m-%d %H:%M:%S") + timedelta(hours=m_interval) mr_date_now = datetime.strptime(date_time_now, "%Y-%m-%d %H:%M:%S") if mr_date_now >= mr_date_plus: break else: res = default_res continue else: break else: res = default_res return res
def _get_status_agenda(self, cursor, user_id, context=None): return ( ('draft', _('Draft')), ('cs', _('Consultation')), ('tech', _('Technique')), ('open', _('Open')), ('busy', _('Busy')), ('close', _('Close')), ('cancel', _('Cancel')), ('no_show', _('No Show')), ('wait', _('Wait')), ('nwnm', _('No Wait')), ('in', _('In')), ('in_between', _('In Between')), ('done', 'Out'), ('office', _('Office')), # pourquoi devoir rajouter cette valeur )
def send_reminder_mail(self, cr, uid, ids, context=None): model_data_obj = self.pool["ir.model.data"] template_id = model_data_obj.get_object_reference( cr, uid, "account_dunning", "email_to_customer_reminder")[1] compose_form = model_data_obj.get_object_reference( cr, uid, "mail", "email_compose_message_wizard_form")[1] if ids and template_id and compose_form: composition_mode = len(ids) > 1 and "mass_mail" or "comment" partner_ids = set() profile_template_id = None for reminder in self.browse(cr, uid, ids, context=context): reminder_template = reminder.profile_id.template_id if reminder_template: if not profile_template_id: profile_template_id = reminder_template.id elif profile_template_id != reminder_template.id: raise Warning( _("You cannot send mass e-mails with different dunning profiles" )) partner_ids.add(reminder.partner_id.id) if reminder.state == ("sent"): raise Warning( _('The reminder was already sent to the customer. If you want to send a reminder again,' 'you need to call the reminder wizard again!')) # check if partner has email partner_ids = list(partner_ids) partner_obj = self.pool["res.partner"] partner_noemail_ids = partner_obj.search( cr, uid, [("id", "in", partner_ids), ("email", "=", False)], context=context) if partner_noemail_ids: partner_noemail_ids = partner_noemail_ids[:10] partner_names = [] for partner in partner_obj.browse(cr, uid, partner_noemail_ids, context=context): partner_names.append(partner.name) raise Warning( _('Partner(s) %s has no email address') % ", ".join(partner_names)) # show wizard for sending if profile_template_id: template_id = profile_template_id email_context = { "active_ids": ids, "active_id": ids[0], "active_model": "account.reminder", "default_model": "account.reminder", "default_res_id": ids[0], "default_composition_mode": composition_mode, "default_template_id": template_id, "default_use_template": bool(template_id) } return { "name": _("Compose Email"), "type": "ir.actions.act_window", "view_type": "form", "view_mode": "form", "res_model": "mail.compose.message", "views": [(compose_form, "form")], "view_id": compose_form, "target": "new", "context": email_context, } return True
def holidays_first_validate_notificate(self, cr, uid, ids, context=None): for obj in self.browse(cr, uid, ids, context=context): self.message_post(cr, uid, [obj.id], _("Request approved, waiting second validation."), context=context)
class crm_meeting(osv.osv): _inherit = "crm.meeting" _description = "consultations meetings" _order = "date asc" def selection_partner_id(self, cr, uid, ids, context=None): """ Get the partner_id to write it in the crm.meeting record """ res = {} fmt = 'YYYY-MM-DD HH:mm:ss' print "PASSING IN: %s CONTEXT IS: %s" % (inspect.stack()[0][3], context) self.write(cr, uid, ids, { 'partner_id': context.get('default_partner_id'), 'given_date': arrow.now().to('UTC').format(fmt), 'user_id': uid }, context=None) # set state to busy self.statechange_busy(cr, uid, ids, context) return res def default_get(self, cr, uid, fields, context=None): """ Surcharge la valeur par defaut de la durée d'un RDV """ res = super(crm_meeting, self).default_get(cr, uid, fields, context=context) res['duration'] = 0.25 return res def onchange_slot(self, cr, uid, ids, state, date, duration, organizer, context=None): """ This method to check and avoid creating slot when it's not desirable We start by searching the closed slot. """ if context == None: context = {} # slot_ids = self.search(cr, uid, [('state', 'in', (('close',)))])# récupere tous les records close OK res = {'value': {}} print "PASSING through", inspect.stack()[0][3] print "STATE, DATE, DURATION, ORGANIZER: %s, %s, %s, %s" % ( state, date, duration, organizer) slot_ids = self.search(cr, uid, [('date', '=', date)]) print "RESULT OF SEARCH:", slot_ids for record in self.browse(cr, uid, slot_ids, context=context): print "RECORD DATE IS;", record.date print "DATE_DEADLINE IS", record.date_deadline print "PARTNER NAME:", record.partner_id.name if slot_ids: warning = { 'title': _("Warning for a close slot"), 'message': _("Well are you sure you want to add a slot"), } return {'value': res.get('value', {}), 'warning': warning} return {'value': {}} def onchange_partner_id(self, cr, uid, ids, state, given_date, context=None): """ Set state to busy when partner_id not empty Set given_date is date when the appointement is given Set user_id to the user who give the appointment """ print "PASSING IN: %s CONTEXT IS: %s" % (inspect.stack()[0][3], context) foo = self.read(cr, uid, ids, fields=[ 'write_date', ], context=context, load='_classic_read') fmt = 'YYYY-MM-DD HH:mm:ss' return { 'value': { 'state': 'busy', 'given_date': arrow.now().to('UTC').format(fmt), 'user_id': uid } } def onchange_dates(self, cr, uid, ids, start_date, duration=False, end_date=False, allday=False, context=None): res = super(crm_meeting, self).onchange_dates(cr, uid, ids, start_date, duration=duration, end_date=end_date, allday=allday, context=context) slot_ids = self.search(cr, uid, [('date', '=', start_date)]) if slot_ids: res.update({ 'warning': { 'title': _("Warning for a close slot"), 'message': _("Well are you sure you want to add a slot"), } }) return res def _get_status_agenda(self, cursor, user_id, context=None): return ( ('draft', _('Draft')), ('cs', _('Consultation')), ('tech', _('Technique')), ('open', _('Open')), ('busy', _('Busy')), ('close', _('Close')), ('cancel', _('Cancel')), ('no_show', _('No Show')), ('wait', _('Wait')), ('nwnm', _('No Wait')), ('in', _('In')), ('in_between', _('In Between')), ('done', 'Out'), ('office', _('Office')), # pourquoi devoir rajouter cette valeur ) def statechange_draft(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "draft"}, context=context) return True def statechange_open(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "open"}, context=context) return True def statechange_close(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "close"}, context=context) return True def statechange_cancel(self, cr, uid, ids, context=None): """ Set the state of crm.meeting record to cancel and create a new crm.meeting lot with the cancel crm.meeting """ self.write(cr, uid, ids, {"state": "cancel"}, context=context) vals = self.read(cr, uid, ids, fields=['date', 'duration', 'date_deadline', 'tag'], context=context, load='_classic_read') # vals est une liste de dictionnaire avec les données des records for n in vals: # on boucle sur les données des record retournées. # n est un dictionnaire # comment récupérer le statut cs ou technique? C'est tag # pour info duration est de type float. # il nous faut supprimer la clef "id" qui est systématiquement fournie dans le return de read del n['id'] # del context['default_partner_id'] n.update({'name': 'Factory', 'state': n['tag']}) self.create(cr, uid, n, context=context) return True def statechange_in(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "in"}, context=context) return True def statechange_in_between(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "in_between"}, context=context) return True def statechange_out(self, cr, uid, ids, context=None): if context is None: context = {} # set meeting to close self.write(cr, uid, ids, {"state": "done"}, context=context) # return True #uncomment if just want the change state to out # get info for the quotation meeting = self.browse( cr, uid, ids[0], context=context ) # comment if you don't want to open a quotation view # pricelist = part.property_product_pricelist and part.property_product_pricelist.id or False res = { 'default_partner_id': meeting.partner_id.id, 'default_pricelist_id': meeting.partner_id.property_product_pricelist.id, 'default_date_acte': meeting.datewotime, 'default_origin': 'Office', } return { # Comment if you don't want to open a quotation view 'name': _('Bla bla'), 'view_type': 'form', 'view_mode': 'form', 'res_model': 'sale.order', # 'context': "{'default_partner_id': %s}" % (meeting.partner_id.id,), # 'context': "{'default_partner_id': %s, 'default_date_acte':%s}" % (meeting.partner_id.id, meeting.datewotime), 'context':res, 'type': 'ir.actions.act_window', 'target': 'current', } def statechange_free(self, cr, uid, ids, context=None): self.write(cr, uid, ids, { "state": "done", "free": True }, context=context) return True def statechange_no_show(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "no_show"}, context=context) return True def statechange_busy(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "busy"}, context=context) return True def statechange_wait(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "wait"}, context=context) return True def statechange_nwnm(self, cr, uid, ids, context=None): self.write(cr, uid, ids, {"state": "nwnm"}, context=context) return True def _get_datewotime(self, cr, uid, ids, field_name, arg, context={}): """ will get the date without timestamp from date giving possibility to search by date """ res = {} if context is None: context = {} fmt = '%Y-%m-%d %H:%M:%S' # set format. Adapted to the format of stored dates in postgresql local_tz = pytz.timezone(context.get( 'tz', 'Pacific/Noumea')) # get tz from context records = self.browse(cr, uid, ids, context) for record in records: wd = datetime.strptime( record.date, fmt, ) # convert string date from database to datetime py object wd = pytz.UTC.localize( wd) # make aware datetime object needed for astimezone() wd = wd.astimezone(local_tz) # convert UTC time to local time res[record.id] = wd.date() # print "In _GET_DATEWOTIME. res is: %s" % res return res def _format_fullmotive(self, cr, uid, ids, name, args, context=None): """ Concatenate the motive and motive comment to get the fullmotive So you can keep some statistics on motive and get real information for patient motive """ res = {} for br in self.browse(cr, uid, ids, context=None): motive = br.motive.name or '' motivecomment = br.motive_comment or '' fullmotive = motive + ' ' + motivecomment res[br.id] = fullmotive return res _columns = { 'subject': fields.char( 'Subject', size=128, help="Object of the meeting", ), # not sure it's usefull 'motive': fields.many2one( 'oph.motive', 'Motive', ), 'motive_comment': fields.char('Comment', size=128, help='Comment to precise the motive'), 'fullmotive': fields.function(_format_fullmotive, type='char', size=128, string='Full Motive', store=True, method=True), 'chief_complaint': fields.text('Chief Complaint'), 'state': fields.selection(_get_status_agenda, 'State', readonly=False), 'partner_id': fields.many2one( 'res.partner', 'Partner', ), 'tono_ids': fields.one2many('oph.measurement', 'meeting_id', 'Tonometry', domain=[('type_id.code', '=', 'tono')]), 'refraction_ids': fields.one2many('oph.measurement', 'meeting_id', 'Refraction', domain=[('type_id.code', '=', 'ref')]), 'keratometry_ids': fields.one2many('oph.measurement', 'meeting_id', 'Keratometry', domain=[('type_id.code', '=', 'ker')]), 'va_ids': fields.one2many('oph.measurement', 'meeting_id', 'Visual Acuity', domain=[('type_id.code', '=', 'va')]), 'sle_ids': fields.one2many('oph.measurement', 'meeting_id', 'Slit Lamp Exam', domain=[('type_id.code', '=', 'sle')]), 'pachy_ids': fields.one2many('oph.measurement', 'meeting_id', 'Center Corneal Thickness', domain=[('type_id.code', '=', 'pachy')]), 'datewotime': fields.function(_get_datewotime, method=True, type='date', string='DateWOtime', store=True), 'todo_list_ids': fields.one2many( 'oph.todolist', 'meeting_id', 'TODO', ), #=============================================================== 'medication_line_ids': fields.one2many('oph.medication.line', 'meeting_id', 'Medication Line'), # cut/paste to inherit class crm.meeting cf oph_prescription.py #=============================================================== 'reporting_line_ids': fields.one2many('oph.reporting', 'meeting_id', 'Reporting Line'), 'conclusion_ids': fields.one2many('oph.measurement', 'meeting_id', 'Conclusion Line', domain=[('type_id.code', '=', 'conc')]), 'miscellaneous_ids': fields.one2many('oph.measurement', 'meeting_id', 'Miscellaneous informations', domain=[('type_id.code', '=', 'misc')]), 'tag': fields.selection( [ ('office', _('Office')), ('or', _('OR')), ('cs', _('Consultation') ), # Add for persistence usefull for change to cancel ('tech', _('Technique') ), # Add for persistence usefull for change to cancel ], 'Tag', select=True, readonly=True), 'free': fields.boolean('Free', help='True if not invoiced'), # for free consultation 'neuro': fields.text('Neuro Observation'), 'mh': fields.text('Medical History'), 'allergia': fields.one2many('oph.allergen', 'meeting_id', 'Allergia'), 'pricelist': fields.related('partner_id', 'property_product_pricelist', type='many2one', relation='product.pricelist', string='Pricelist', store=False), 'given_date': fields.datetime( 'Given Date', help='Date when the appointement is given to the partner'), } _defaults = { 'state': 'open', # TODO is it OK 'name': 'RDV', 'duration': 0.25, 'tag': 'cs', 'free': False } def unlink(self, cr, uid, ids, context=None): for meeting in self.browse(cr, uid, ids, context=context): if meeting.state not in ('draft', 'open'): raise osv.except_osv( _('Error!'), _('Impossible to delete a meeting not in draft state or open!' )) return super(crm_meeting, self).unlink(cr, uid, ids, context=context)
def write(self, cr, uid, ids, vals, context=None): check_fnct = self.pool.get('hr.holidays.status').check_access_rights for holiday in self.browse(cr, uid, ids, context=context): if holiday.state in ('validate','validate1') and not check_fnct(cr, uid, 'write', raise_exception=False): raise osv.except_osv(_('Warning!'),_('You cannot modify a leave request that has been approved. Contact a human resource manager.')) return super(hr_holidays, self).write(cr, uid, ids, vals, context=context)
def copy(self, default=None): default = dict(default or {}) default['name'] = _('%s (copy)') % self.name return super(res_partner, self).copy(default)