def get_avg_efficiency(self, ids, name): """ Get average efficiency of the fuel """ purchase_line_obj = Pool().get('purchase.line') res = {} for asset in self.browse(ids): sum_quantity = 0 purchase_line_ids = purchase_line_obj.search( [('asset', '=', asset.id)], order=[('id', 'DESC')], limit=100) for purchase_line in purchase_line_obj.browse(purchase_line_ids): sum_quantity += Decimal(str(purchase_line.quantity)) if purchase_line_ids: # get the last purchase line for particular asset. last_line = purchase_line_obj.browse(purchase_line_ids[-1]) # get the first purchase line from last 100 records # for particular asset. first_line = purchase_line_obj.browse(purchase_line_ids[0]) if len(purchase_line_ids) == 1: avg_efficiency = (first_line.meter_reading - \ 0)/Decimal(str(purchase_line.quantity)) else: avg_efficiency = (first_line.meter_reading - \ last_line.meter_reading) / (sum_quantity) else: avg_efficiency = 0 res[asset.id] = avg_efficiency return res
def get_avg_efficiency(self, ids, name): """ Get average efficiency of the fuel """ purchase_line_obj = Pool().get('purchase.line') res = {} for asset in self.browse(ids): sum_quantity = 0 purchase_line_ids = purchase_line_obj.search([ ('asset', '=', asset.id) ], order=[('id', 'DESC')], limit=100) for purchase_line in purchase_line_obj.browse(purchase_line_ids): sum_quantity += Decimal(str(purchase_line.quantity)) if purchase_line_ids: # get the last purchase line for particular asset. last_line = purchase_line_obj.browse( purchase_line_ids[-1]) # get the first purchase line from last 100 records # for particular asset. first_line = purchase_line_obj.browse( purchase_line_ids[0]) if len(purchase_line_ids) == 1: avg_efficiency = (first_line.meter_reading - \ 0)/Decimal(str(purchase_line.quantity)) else: avg_efficiency = (first_line.meter_reading - \ last_line.meter_reading) / (sum_quantity) else: avg_efficiency = 0 res[asset.id] = avg_efficiency return res
def transition_check(self): Plots = Pool().get('forest.plot') Preco = Pool().get('forest_work.preconisation') plots_succeed = [] plots_failed = [] Lignes = Preco.browse(Transaction().context.get('active_ids')) for ligne in Lignes: cursor = Transaction().cursor cursor.execute( 'SELECT p.id ' 'FROM forest_plot p ' 'WHERE p.id=%s ' 'GROUP BY p.id' % (ligne.plot.id)) for plotid in cursor.fetchall(): plots = Plots.browse(plotid) for plot in plots: try: if plot.travaux: print "plots_failed ok" self.create_travaux(plot) plots_failed.append(plot.id) else: print "plots_succeed ok" self.create_travaux(plot) plots_succeed.append(plot.id) except Exception, e: raise self.result.plots_succeed = plots_succeed self.result.plots_failed = plots_failed
def default_start(self, fields): Invoice = Pool().get('account.invoice') default = { 'with_refund': True, } origin = Invoice.browse(Transaction().context['active_ids']) def in_group(): pool = Pool() ModelData = pool.get('ir.model.data') User = pool.get('res.user') Group = pool.get('res.group') group = Group( ModelData.get_id('nodux_account_ec_pymes', 'group_sale_return')) transaction = Transaction() user_id = transaction.user if user_id == 0: user_id = transaction.context.get('user', user_id) if user_id == 0: return True user = User(user_id) return origin and group in user.groups if not in_group(): self.raise_user_error( "No esta autorizado a generar Nota de credito") for invoice in Invoice.browse(Transaction().context['active_ids']): if (invoice.state != 'posted' or invoice.payment_lines or invoice.type in ('in_invoice', 'in_credit_note')): default['with_refund'] = False break return default
def update_comment(self, task_id, comment_id): """ Update a specific comment. """ project_obj = Pool().get('project.work') nereid_user_obj = Pool().get('nereid.user') # allow modification only if the user is an admin or the author of # this ticket task = project_obj.browse(task_id) comment = self.browse(comment_id) assert task.type == "task" assert comment.project.id == task.id # Allow only admins and author of this comment to edit it if nereid_user_obj.is_project_admin(request.nereid_user) or \ comment.updated_by == request.nereid_user: self.write(comment_id, {'comment': request.form['comment']}) else: abort(403) if request.is_xhr: comment_record = self.browse(comment_id) html = render_template('comment.jinja', comment=comment_record) return jsonify({ 'success': True, 'html': html, 'state': project_obj.browse(task.id).state, }) return redirect(request.referrer)
def on_change_product(self, vals): product_obj = Pool().get('product.product') if not vals.get('product'): return {} res = {} product = product_obj.browse(vals['product']) if not vals.get('desc'): res['desc'] = product_obj.browse(product.id).rec_name if not vals.get('unit'): res['unit'] = product.default_uom.id return res
def transition_check(self): Party = Pool().get('party.party') parties_succeed = [] parties_failed = [] parties = Party.browse(Transaction().context.get('active_ids')) for party in parties: for identifier in party.identifiers: if identifier.type != 'eu_vat': continue try: if not vat.check_vies(identifier.code): parties_failed.append(party.id) else: parties_succeed.append(party.id) except Exception, e: if hasattr(e, 'faultstring') \ and hasattr(e.faultstring, 'find'): if e.faultstring.find('INVALID_INPUT'): parties_failed.append(party.id) continue if e.faultstring.find('SERVICE_UNAVAILABLE') \ or e.faultstring.find('MS_UNAVAILABLE') \ or e.faultstring.find('TIMEOUT') \ or e.faultstring.find('SERVER_BUSY'): self.raise_user_error('vies_unavailable') raise
def on_change_with_consulLibres(self,values): res = [] i1 = values.get('horaini') f1 = values.get('horaFin') #Chequeo que la entrada sea correcta if ((i1==None) or (f1==None)): return res else: if(f1 < i1): return res objConsultorio = Pool().get('cefiro.consultorio') objConsulta = Pool().get('cefiro.consulta') consultoriosTotId = objConsultorio.search([]) for cons in objConsultorio.browse(consultoriosTotId): estaVacio = True consultasIDs = cons.consultas listaDic = objConsulta.read(consultasIDs) for dic in listaDic: i2 = dic.get('horaini') f2 = dic.get('horaFin') if not((f2<i1) or (f1<i2)): estaVacio = False if estaVacio: res.append(cons.id) self.libres = res return res
def run(self): transaction = Transaction() Model = Pool().get(self.data['model']) with transaction.set_user(self.data['user']), \ transaction.set_context(self.data['context']): instances = self.data['instances'] # Ensure record ids still exist if isinstance(instances, int): if Model.search([('id', '=', instances)]): instances = Model(instances) else: instances = None else: ids = set() for sub_ids in grouped_slice(instances): records = Model.search([('id', 'in', list(sub_ids))]) ids.update(map(int, records)) if ids: instances = Model.browse( [i for i in instances if i in ids]) else: instances = None resultant_args = copy.copy(self.data['args']) if instances is not None: resultant_args = [instances] + resultant_args getattr(Model, self.data['method'])(*resultant_args, **self.data['kwargs']) self.finished()
def get_available_gateways(self): """Return the JSONified list of payment gateways available This is a XHR only method If type is specified as address then an address lookup is done """ address_obj = Pool().get('party.address') value = int(request.args.get('value', 0)) if request.values.get('type') == 'address': # Address lookup only when logged in if request.is_guest_user: abort(403) # If not validated as user's address this could lead to # exploitation by ID if value not in [a.id for a in request.nereid_user.party.addresses]: abort(403) address = address_obj.browse(value) value = address.country.id rv = [{ 'id': g.id, 'name': g.name, 'image': g.get_image(g), } for g in self._get_available_gateways(value)] return jsonify(result = rv)
def asyncto_sync(self): log = logging.getLogger('logfile') log.warn('Asyncto People sync') try: asyncto_obj = Pool().get('auroville.asyncto') people_obj = Pool().get('auroville.people') asyncto_ids = asyncto_obj.search([]) for item in asyncto_obj.browse(asyncto_ids): people_ids = people_obj.search([ ('asynctoid', '=', item.asynctoid), ]) data = { 'asynctoid': item.asynctoid, 'aurovillename': item.aurovillename, 'name': item.name, 'surname': item.surname, 'telephone': item.telephone, 'email': item.email, 'contactperson': item.contactperson, 'masterlistid': int(item.masterlistid) } if people_ids: people_obj.write(people_ids, data) else: people_obj.create(data) # Community except Exception as e: log.error(e)
def parse(cls, report, records, data, localcontext): """ Data must always contain a key 'productions' if records is None """ Production = Pool().get('production') key = attrgetter('reporting_date') if not records: records = Production.browse(data['productions']) productions = Production.search([('id', 'in', map(int, records)), ('reporting_date', '!=', None)], order=[('reporting_date', 'ASC')]) # Raise UserError if no productions were found if not productions: # pragma: no cover raise UserError("No Productions found for the given date range") matrix = [] for reporting_date, prod_on_date in groupby(productions, key=key): matrix.append([reporting_date] + list(prod_on_date)) localcontext.update({'productions_by_date': matrix}) return super(ProductionScheduleReport, cls).parse(report, records, data, localcontext)
def get_calendar_description(cls, uri, cache=None): Calendar = Pool().get('calendar.calendar') calendar_id = cls.calendar(uri) if calendar_id: if not (uri[10:].split('/', 1) + [None])[1]: if cache is not None: cache.setdefault('_calendar', {}) cache['_calendar'].setdefault(Calendar.__name__, {}) ids = list(cache['_calendar'][Calendar.__name__].keys()) if calendar_id not in ids: ids.append(calendar_id) elif 'calendar_description' in cache['_calendar'][ Calendar.__name__][calendar_id]: res = cache['_calendar'][Calendar.__name__][ calendar_id]['calendar_description'] if res is not None: return res else: ids = [calendar_id] res = None for calendar in Calendar.browse(ids): if calendar.id == calendar_id: res = calendar.description if cache is not None: cache['_calendar'][Calendar.__name__]\ .setdefault(calendar.id, {}) cache['_calendar'][Calendar.__name__][ calendar.id]['calendar_description'] = \ calendar.description if res is not None: return res raise DAV_NotFound
def execute(cls, session, data, state_name): model = Pool().get('protection.area') records = model.browse(Transaction().context.get('active_ids')) for record in records: print record record.generate([record]) return []
def do_return_(self, action): Sale = Pool().get('sale.sale') action, data = super(ReturnSale, self).do_return_(action) Sale.write(Sale.browse(data['res_id']), {'carrier': None}) return action, data
def on_change_with_consulLibres(self, values): objConsultorio = Pool().get('cefiro.consultorio') objConsulta = Pool().get('cefiro.consulta') consultoriosTotId = objConsultorio.search([]) res = [] for cons in objConsultorio.browse(consultoriosTotId): estaVacio = True consultasIDs = cons.consultas listaDic = objConsulta.read(consultasIDs) for dic in listaDic: i1 = values.get('horaIni') f1 = values.get('horaFin') i2 = dic.get('horaIni') f2 = dic.get('horaFin') if not ((i1 == None) or (f1 == None)): if not ((f2 < i1) or (f1 < i2)): estaVacio = False if estaVacio: res.append(cons.id) self.libres = res # objConsulta.write(self.id,{'libres':Eval('res')}) return res
def get_calendar_description(cls, uri, cache=None): Calendar = Pool().get('calendar.calendar') calendar_id = cls.calendar(uri) if calendar_id: if not (uri[10:].split('/', 1) + [None])[1]: if cache is not None: cache.setdefault('_calendar', {}) cache['_calendar'].setdefault(Calendar.__name__, {}) ids = cache['_calendar'][Calendar.__name__].keys() if calendar_id not in ids: ids.append(calendar_id) elif 'calendar_description' in cache['_calendar'][ Calendar.__name__][calendar_id]: res = cache['_calendar'][Calendar.__name__][ calendar_id]['calendar_description'] if res is not None: return res else: ids = [calendar_id] res = None for calendar in Calendar.browse(ids): if calendar.id == calendar_id: res = calendar.description if cache is not None: cache['_calendar'][Calendar.__name__]\ .setdefault(calendar.id, {}) cache['_calendar'][Calendar.__name__][ calendar.id]['calendar_description'] = \ calendar.description if res is not None: return res raise DAV_NotFound
def parse(self, report, objects, datas, localcontext): """Get all the purchase orders lines with in the range dates that are given in wizard, product type as fuel and the state is of done or confirmed. :param report: BrowseRecord of the ir.action.report :param objects: BrowseRecordList of the records on which parse report :param datas: a dictionary with datas that will be set in local context of the report :param localcontext: the context used to parse the report """ purchase_obj = Pool().get('purchase.purchase') purchase_line_obj = Pool().get('purchase.line') res = {} purchase_line_ids = purchase_line_obj.search([ ('purchase.purchase_date', '>=', datas['form']['begin_date']), ('purchase.purchase_date', '<=', datas['form']['end_date']), ('purchase.state', 'in', ('done', 'confirmed')), ('product.fleet_management_type', '=', 'fuel') ]) localcontext['purchase_lines'] = purchase_line_obj.browse(purchase_line_ids) localcontext['begin_date'] = datas['form']['begin_date'] localcontext['end_date'] = datas['form']['end_date'] return super(GenerateFuelEfficiencyReport, self).parse(report, objects, datas, localcontext)
def default_request_refund(self, data): """Requests the refund for the current shipment record and returns the response. """ Shipment = Pool().get('stock.shipment.out') shipments = Shipment.browse(Transaction().context['active_ids']) # PICNumber is the argument name expected by endicia in API, # so its better to use the same name here for better understanding pic_numbers = [] for shipment in shipments: if not ( shipment.carrier and shipment.carrier.carrier_cost_method == 'endicia' ): self.raise_user_error('wrong_carrier') if shipment.tracking_number: pic_numbers.append(shipment.tracking_number.tracking_number) test = shipment.carrier.endicia_is_test and 'Y' or 'N' refund_request = RefundRequestAPI( pic_numbers=pic_numbers, accountid=shipment.carrier.endicia_account_id, requesterid=shipment.carrier.endicia_requester_id, passphrase=shipment.carrier.endicia_passphrase, test=test, ) try: response = refund_request.send_request() except RequestError, error: self.raise_user_error('error_label', error_args=(error.message,))
def parse(cls, report, records, data, localcontext): """ Data must always contain a key 'productions' if records is None """ Production = Pool().get('production') key = attrgetter('reporting_date') if not records: records = Production.browse(data['productions']) productions = Production.search([ ('id', 'in', map(int, records)), ('reporting_date', '!=', None) ], order=[('reporting_date', 'ASC')]) # Raise UserError if no productions were found if not productions: # pragma: no cover raise UserError( "No Productions found for the given date range" ) matrix = [] for reporting_date, prod_on_date in groupby(productions, key=key): matrix.append([reporting_date] + list(prod_on_date)) localcontext.update({ 'productions_by_date': matrix }) return super(ProductionScheduleReport, cls).parse( report, records, data, localcontext )
def download_file(self, attachment_id): """ Returns the file for download. The wonership of the task or the project is checked automatically. """ attachment_obj = Pool().get('ir.attachment') work = None if request.args.get('project', None): work = self.get_project(request.args.get('project', type=int)) if request.args.get('task', None): work = self.get_task(request.args.get('task', type=int)) if not work: # Neither task, nor the project is specified raise abort(404) attachment_ids = attachment_obj.search([ ('id', '=', attachment_id), ('resource', '=', '%s,%d' % (self._name, work.id)) ]) if not attachment_ids: raise abort(404) attachment = attachment_obj.browse(attachment_ids[0]) with tempfile.NamedTemporaryFile(delete=False) as f: f.write(attachment.data) return send_file( f.name, attachment_filename=attachment.name, as_attachment=True )
def get_rate(CurrenciesCurrenciesCurrenciesCurrencies, name): ''' Return the rate at the date from the context or the current date ''' Rate = Pool().get('currency.currency.rate') Date = Pool().get('ir.date') res = {} date = Transaction().context.get('date', Date.today()) for currency in CurrenciesCurrenciesCurrenciesCurrencies: rates = Rate.search([ ('currency', '=', currency.id), ('date', '<=', date), ], limit=1, order=[('date', 'DESC')]) if rates: res[currency.id] = rates[0].id else: res[currency.id] = 0 rate_ids = [x for x in res.values() if x] rates = Rate.browse(rate_ids) id2rate = {} for rate in rates: id2rate[rate.id] = rate for currency_id in res.keys(): if res[currency_id]: res[currency_id] = id2rate[res[currency_id]].rate return res
def assign_task(self, task_id): """Assign task to a user :param task_id: Id of Task """ nereid_user_obj = Pool().get('nereid.user') task = self.get_task(task_id) new_assignee = nereid_user_obj.browse(int(request.form['user'])) if self.can_write(task.parent, new_assignee): self.write(task.id, { 'assigned_to': new_assignee.id }) if request.is_xhr: return jsonify({ 'success': True, }) flash("Task assigned to %s" % new_assignee.name) return redirect(request.referrer) flash("Only employees can be assigned to tasks.") return redirect(request.referrer)
def get_languages(self): """Returns available languages for current site .. note:: A special method is required so that the fetch can be speeded up, by pushing the categories to the central cache which cannot be done directly on a browse node. """ lang_obj = Pool().get('ir.lang') cache_key = key_from_list([ Transaction().cursor.dbname, Transaction().user, 'nereid.website.get_languages', ]) # The website is automatically appended to the cache prefix rv = cache.get(cache_key) if rv is None: language_ids = lang_obj.search([('translatable', '=', True)]) languages = lang_obj.browse(language_ids) rv = [{ 'id': l.id, 'name': l.name, 'code': l.code, } for l in languages] cache.set(cache_key, rv, 60*60) return rv
def default_receipt_code(self): config_obj = Pool().get('pos_cash.configuration') config = config_obj.browse(1) sequence_obj = Pool().get('ir.sequence.strict') seq_code = sequence_obj.get_id(config.sequence.id) res = '%04d%s' % (config.company.id, seq_code) return res
def process(self, sale, payment_method_id): """Begins the payment processing. Returns a response object if a redirect to third party website is required, else processes the payment. :param sale: Browse Record of the Sale :param payment_method_id: ID of payment method """ sale_obj = Pool().get('sale.sale') try_to_authorize = ( request.nereid_website.payment_mode == 'auth_if_available' ) payment_method = self.browse(payment_method_id) allowed_gateways = self._get_available_gateways( sale.invoice_address.country.id) if payment_method not in allowed_gateways: current_app.logger.error("Payment method %s is not valid" % \ payment_method.name) abort(403) payment_method_obj = Pool().get(payment_method.model.model) sale_obj.write(sale.id, {'payment_method': payment_method.id}) sale = sale_obj.browse(sale.id) if try_to_authorize and hasattr(payment_method_obj, 'authorize'): return payment_method_obj.authorize(sale) else: return payment_method_obj.capture(sale)
def parse(self, report, objects, datas, localcontext): """Get all the purchase orders lines with in the range dates that are given in wizard, product type as fuel and the state is of done or confirmed. :param report: BrowseRecord of the ir.action.report :param objects: BrowseRecordList of the records on which parse report :param datas: a dictionary with datas that will be set in local context of the report :param localcontext: the context used to parse the report """ purchase_obj = Pool().get('purchase.purchase') purchase_line_obj = Pool().get('purchase.line') res = {} purchase_line_ids = purchase_line_obj.search([ ('purchase.purchase_date', '>=', datas['form']['begin_date']), ('purchase.purchase_date', '<=', datas['form']['end_date']), ('purchase.state', 'in', ('done', 'confirmed')), ('product.fleet_management_type', '=', 'fuel') ]) localcontext['purchase_lines'] = purchase_line_obj.browse( purchase_line_ids) localcontext['begin_date'] = datas['form']['begin_date'] localcontext['end_date'] = datas['form']['end_date'] return super(GenerateFuelEfficiencyReport, self).parse(report, objects, datas, localcontext)
def read(cls, ids, fields_names=None): # Add moves from purchase_request as they can have only one origin PurchaseRequest = Pool().get('purchase.request') added = False if 'moves' in fields_names or []: if 'purchase_request' not in fields_names: fields_names = fields_names[:] fields_names.append('purchase_request') added = True values = super(SaleLine, cls).read(ids, fields_names=fields_names) if 'moves' in fields_names or []: with Transaction().set_context(_check_access=False): purchase_requests = PurchaseRequest.browse( list( set(v['purchase_request'] for v in values if v['purchase_request']))) id2purchase_requests = dict( (p.id, p) for p in purchase_requests) for value in values: if value['purchase_request']: purchase_request = id2purchase_requests[ value['purchase_request']] if (purchase_request.customer and purchase_request.purchase_line): move_ids = tuple( m.id for m in purchase_request.purchase_line.moves) if value['moves'] is None: value['moves'] = move_ids else: value['moves'] += move_ids if added: del value['purchase_request'] return values
def default_start(self, name): defaults = super(ProcessPayment, self).default_start(name) Payment = Pool().get('account.payment') payments = Payment.browse(Transaction().context['active_ids']) defaults['is_paybox'] = any(p.journal.process_method == 'paybox' for p in payments) return defaults
def _get_raw_sequence(cls, invoice, number): Sequence = Pool().get('ir.sequence') seq, = Sequence.browse([invoice.pos.pos_sequence.invoice_sequence.id]) val = number if seq.prefix: val = number[len(seq.prefix):] return val
def default_request_refund(self, data): """Requests the refund for the current shipment record and returns the response. """ Shipment = Pool().get('stock.shipment.out') shipments = Shipment.browse(Transaction().context['active_ids']) # PICNumber is the argument name expected by endicia in API, # so its better to use the same name here for better understanding pic_numbers = [] for shipment in shipments: if not (shipment.carrier and shipment.carrier.carrier_cost_method == 'endicia'): self.raise_user_error('wrong_carrier') pic_numbers.append(shipment.tracking_number) test = shipment.carrier.endicia_is_test and 'Y' or 'N' refund_request = RefundRequestAPI( pic_numbers=pic_numbers, accountid=shipment.carrier.endicia_account_id, requesterid=shipment.carrier.endicia_requester_id, passphrase=shipment.carrier.endicia_passphrase, test=test, ) try: response = refund_request.send_request() except RequestError, error: self.raise_user_error('error_label', error_args=(error, ))
def transition_check(self): Party = Pool().get('party.party') parties_succeed = [] parties_failed = [] parties = Party.browse(Transaction().context.get('active_ids')) for party in parties: for identifier in party.identifiers: if identifier.type != 'eu_vat': continue eu_vat = get_cc_module('eu', 'vat') try: if not eu_vat.check_vies(identifier.code)['valid']: parties_failed.append(party.id) else: parties_succeed.append(party.id) except Exception as e: if hasattr(e, 'faultstring') \ and hasattr(e.faultstring, 'find'): if e.faultstring.find('INVALID_INPUT'): parties_failed.append(party.id) continue if e.faultstring.find('SERVICE_UNAVAILABLE') \ or e.faultstring.find('MS_UNAVAILABLE') \ or e.faultstring.find('TIMEOUT') \ or e.faultstring.find('SERVER_BUSY'): raise VIESUnavailable( gettext('party.msg_vies_unavailable')) from e raise self.result.parties_succeed = parties_succeed self.result.parties_failed = parties_failed return 'result'
def on_change_with_consulLibres(self, values): res = [] i1 = values.get('horaini') f1 = values.get('horaFin') #Chequeo que la entrada sea correcta if ((i1 == None) or (f1 == None)): return res else: if (f1 < i1): return res objConsultorio = Pool().get('cefiro.consultorio') objConsulta = Pool().get('cefiro.consulta') consultoriosTotId = objConsultorio.search([]) for cons in objConsultorio.browse(consultoriosTotId): estaVacio = True consultasIDs = cons.consultas listaDic = objConsulta.read(consultasIDs) for dic in listaDic: i2 = dic.get('horaini') f2 = dic.get('horaFin') if not ((f2 < i1) or (f1 < i2)): estaVacio = False if estaVacio: res.append(cons.id) self.libres = res return res
def run(self): transaction = Transaction() Model = Pool().get(self.data['model']) with transaction.set_user(self.data['user']), \ transaction.set_context(self.data['context']): instances = self.data['instances'] # Ensure record ids still exist if isinstance(instances, int): with transaction.set_context(active_test=False): if Model.search([('id', '=', instances)]): instances = Model(instances) else: instances = None else: ids = set() with transaction.set_context(active_test=False): for sub_ids in grouped_slice(instances): records = Model.search([('id', 'in', list(sub_ids))]) ids.update(map(int, records)) if ids: instances = Model.browse( [i for i in instances if i in ids]) else: instances = None if instances is not None: getattr(Model, self.data['method'])( instances, *self.data['args'], **self.data['kwargs']) if not self.dequeued_at: self.dequeued_at = datetime.datetime.now() self.finished_at = datetime.datetime.now() self.save()
def transition_generate(self): Invoice = Pool().get('account.invoice') invoices = Invoice.browse(Transaction().context['active_ids']) service = 'generate_facturae_%s' % self.start.service getattr(Invoice, service)(invoices, self.start.certificate_password) return 'end'
def transition_check(self): Party = Pool().get('party.party') if not HAS_VATNUMBER or not hasattr(vatnumber, 'check_vies'): return 'no_result' parties_succeed = [] parties_failed = [] parties = Party.browse(Transaction().context.get('active_ids')) for party in parties: if not party.vat_code: continue try: if not vatnumber.check_vies(party.vat_code): parties_failed.append(party.id) else: parties_succeed.append(party.id) except Exception, e: if hasattr(e, 'faultstring') \ and hasattr(e.faultstring, 'find'): if e.faultstring.find('INVALID_INPUT'): parties_failed.append(party.id) continue if e.faultstring.find('SERVICE_UNAVAILABLE') \ or e.faultstring.find('MS_UNAVAILABLE') \ or e.faultstring.find('TIMEOUT') \ or e.faultstring.find('SERVER_BUSY'): self.raise_user_error('vies_unavailable') raise
def get_listings_updated_after(self, updated_after=None): """ This method returns listing, which needs inventory update Downstream module can override change its implementation :return: List of AR of `product.product.channel_listing` """ ChannelListing = Pool().get('product.product.channel_listing') cursor = Transaction().connection.cursor() if not updated_after: # Return all active listings return ChannelListing.search([('channel', '=', self), ('state', '=', 'active')]) else: # Query to find listings # in which product inventory is recently updated or # listing it self got updated recently cursor.execute( """ SELECT listing.id FROM product_product_channel_listing AS listing INNER JOIN stock_move ON stock_move.product = listing.product WHERE listing.channel = %s AND listing.state = 'active' AND ( COALESCE(stock_move.write_date, stock_move.create_date) > %s OR COALESCE(listing.write_date, listing.create_date) > %s ) GROUP BY listing.id """, (self.id, updated_after, updated_after)) listing_ids = map(lambda r: r[0], cursor.fetchall()) return ChannelListing.browse(listing_ids)
def read(cls, ids, fields_names=None): # Add moves from purchase_request as they can have only one origin PurchaseRequest = Pool().get('purchase.request') added = False if 'moves' in fields_names or []: if 'purchase_request' not in fields_names: fields_names = fields_names[:] fields_names.append('purchase_request') added = True values = super(SaleLine, cls).read(ids, fields_names=fields_names) if 'moves' in fields_names or []: with Transaction().set_user(0, set_context=True): purchase_requests = PurchaseRequest.browse( list(set(v['purchase_request'] for v in values if v['purchase_request']))) id2purchase_requests = dict((p.id, p) for p in purchase_requests) for value in values: if value['purchase_request']: purchase_request = id2purchase_requests[ value['purchase_request']] if (purchase_request.customer and purchase_request.purchase_line): move_ids = tuple(m.id for m in purchase_request.purchase_line.moves) if value['moves'] is None: value['moves'] = move_ids else: value['moves'] += move_ids if added: del value['purchase_request'] return values
def get_rate(currencies, name): ''' Return the rate at the date from the context or the current date ''' Rate = Pool().get('currency.currency.rate') Date = Pool().get('ir.date') res = {} date = Transaction().context.get('date', Date.today()) for currency in currencies: rates = Rate.search([ ('currency', '=', currency.id), ('date', '<=', date), ], limit=1, order=[('date', 'DESC')]) if rates: res[currency.id] = rates[0].id else: res[currency.id] = 0 rate_ids = [x for x in res.values() if x] rates = Rate.browse(rate_ids) id2rate = {} for rate in rates: id2rate[rate.id] = rate for currency_id in res.keys(): if res[currency_id]: res[currency_id] = id2rate[res[currency_id]].rate return res
def on_change_with_consulLibres(self,values): objConsultorio = Pool().get('cefiro.consultorio') objConsulta = Pool().get('cefiro.consulta') consultoriosTotId = objConsultorio.search([]) res=[] for cons in objConsultorio.browse(consultoriosTotId): estaVacio = True consultasIDs = cons.consultas listaDic = objConsulta.read(consultasIDs) for dic in listaDic: i1 = values.get('horaIni') f1 = values.get('horaFin') i2=dic.get('horaIni') f2=dic.get('horaFin') if not ((i1==None) or (f1==None)): if not((f2<i1) or (f1<i2)): estaVacio = False if estaVacio: res.append(cons.id) self.libres = res # objConsulta.write(self.id,{'libres':Eval('res')}) return res
def get_context(cls, objects, data): Product = Pool().get('product.product') Locations = Pool().get('stock.location') report_context = super(ProductLedgerReport, cls).get_context( objects, data ) records = [] summary = {} for product_id in data['products']: product = Product(product_id) record = { 'product': product, 'purchases': cls.get_purchases(product.id, data), 'productions': cls.get_productions(product.id, data), 'customers': cls.get_customers(product.id, data), 'lost_and_founds': cls.get_lost_and_founds(product.id, data), 'consumed': cls.get_consumed(product.id, data) } records.append(record) summary[product] = cls.get_summary(record, data) report_context['summary'] = summary report_context['warehouses'] = Locations.browse(data['warehouses']) return report_context
def transition_create_service_invoice(self): HealthService = Pool().get('gnuhealth.health_service') Invoice = Pool().get('account.invoice') Party = Pool().get('party.party') services = HealthService.browse( Transaction().context.get('active_ids')) invoices = [] #Invoice Header for service in services: if service.state == 'invoiced': self.raise_user_error('duplicate_invoice') invoice_data = {} invoice_data['description'] = service.desc invoice_data['party'] = service.patient.name.id invoice_data['account'] = \ service.patient.name.account_receivable.id party_address = Party.address_get(service.patient.name, type='invoice') invoice_data['invoice_address'] = party_address.id invoice_data['reference'] = service.name invoice_data['payment_term'] = \ service.patient.name.customer_payment_term and \ service.patient.name.customer_payment_term.id or \ False #Invoice Lines seq = 0 invoice_lines = [] for line in service.service_line: seq = seq + 1 account = line['product'].template.account_revenue_used.id if line['to_invoice']: invoice_lines.append(('create', [{ 'product': line['product'].id, 'description': line['desc'], 'quantity': line['qty'], 'account': account, 'unit': line['product'].default_uom.id, 'unit_price': line['product'].list_price, 'sequence': seq }])) invoice_data['lines'] = invoice_lines invoices.append(invoice_data) Invoice.create(invoices) # Change to invoiced the status on the service document. HealthService.write(services, {'state': 'invoiced'}) return 'end'
def get_perfilest(self, ids, name): res = {} user_obj = Pool().get('res.user') usrid = Transaction().user usuario = user_obj.browse(usrid) est_obj = Pool().get('cefiro.estudiante') estIDsTot = est_obj.search([]) for elem in self.browse(ids): sol = [] for est in est_obj.browse(estIDsTot): if (est.login == usuario.login): sol.append(est.id) res[elem.id] = sol return res
def get_perfilest(self,ids,name): res = {} user_obj = Pool().get('res.user') usrid = Transaction().user usuario = user_obj.browse(usrid) est_obj = Pool().get('cefiro.estudiante') estIDsTot = est_obj.search([]) for elem in self.browse(ids): sol=[] for est in est_obj.browse(estIDsTot): if (est.login==usuario.login): sol.append(est.id) res[elem.id]=sol return res
def get_usuario(self,ids,name): res = {} user_obj = Pool().get('res.user') usrid = Transaction().user usuario = user_obj.browse(usrid) for elem in self.browse(ids): res[elem.id] = usuario.login return res
def get_perfiles(self,ids,name): res = {} user_obj = Pool().get('res.user') usrid = Transaction().user usuario = user_obj.browse(usrid) psi_obj = Pool().get('cefiro.psicologo') psiIDsTot = psi_obj.search([]) for elem in self.browse(ids): sol=[] for psi in psi_obj.browse(psiIDsTot): if (psi.login==usuario.login): sol.append(psi.id) res[elem.id]=sol return res
def get_usuario(self, ids, name): res = {} user_obj = Pool().get('res.user') usrid = Transaction().user usuario = user_obj.browse(usrid) for elem in self.browse(ids): res[elem.id] = usuario.login return res
def get_compare_context(report, records, data): Location = Pool().get('stock.location') from_location_ids = set() to_location_ids = set() for record in records: for move in record.inventory_moves: from_location_ids.add(move.from_location) to_location_ids.add(move.to_location) from_locations = Location.browse(list(from_location_ids)) to_locations = Location.browse(list(to_location_ids)) return { 'from_location_ids': [l.id for l in from_locations], 'to_location_ids': [l.id for l in to_locations], }
def get_perfiles(self, ids, name): res = {} user_obj = Pool().get('res.user') usrid = Transaction().user usuario = user_obj.browse(usrid) psi_obj = Pool().get('cefiro.psicologo') psiIDsTot = psi_obj.search([]) for elem in self.browse(ids): sol = [] for psi in psi_obj.browse(psiIDsTot): if (psi.login == usuario.login): sol.append(psi.id) res[elem.id] = sol return res
def transition_create_bed_transfer(self): """Making bed tranfer for patients that are not yet admitted equal to free""" inpatient_registrations = Pool().get( 'gnuhealth.inpatient.registration') bed = Pool().get('gnuhealth.hospital.bed') registrations = inpatient_registrations.browse( Transaction().context.get('active_ids')) # Don't allow mass changes. Work on a single record if len(registrations) > 1: self.raise_user_error('choose_one') registration = registrations[0] current_bed = registration.bed destination_bed = self.start.newbed reason = self.start.reason # Check that the new bed is free if destination_bed.state == 'free': # Free the current bed bed.write([current_bed], {'state': 'free'}) # Set as occupied the new bed # Only change the state of the bed to occupied if the patient # was hospitalized if registration.state == 'hospitalized': bed.write([destination_bed], {'state': 'occupied'}) # Change the state of the bed to reserved if the patient admission # has been confirmed but not admitted as yet elif registration.state == 'confirmed': bed.write([destination_bed], {'state': 'reserved'}) # Raise error if patient has been discharged, you should not be # able to transfer an already discharged patient to a bed elif registration.state == 'done': self.raise_user_error( 'Cannot transfer a discharge patient to a bed') # Update the hospitalization record hospitalization_info = {} hospitalization_info['bed'] = destination_bed # Update the hospitalization data transfers = [] transfers.append(('create', [{'transfer_date': datetime.now(), 'bed_from': current_bed, 'bed_to': destination_bed, 'reason': reason}])) hospitalization_info['bed_transfers'] = transfers inpatient_registrations.write([registration], hospitalization_info) else: self.raise_user_error('bed_unavailable') return 'end'
def create(self, values): sequence_obj = Pool().get('ir.sequence') config_obj = Pool().get('cefiro.sec') values = values.copy() config = config_obj.browse(1) values['identidad'] = sequence_obj.get_id(config.numeropaciente.id) return super(Paciente, self).create(values)
def on_change_with_product_fleet_type(self, vals): """Set the value of product_fleet_type so that the invisible and required property may be set """ product_obj = Pool().get('product.product') if vals.get('product'): product = product_obj.browse(vals['product']) return product.fleet_management_type return None
def transition_create_service_invoice(self): HealthService = Pool().get('gnuhealth.health_service') Invoice = Pool().get('account.invoice') Party = Pool().get('party.party') services = HealthService.browse(Transaction().context.get( 'active_ids')) invoices = [] #Invoice Header for service in services: if service.state == 'invoiced': self.raise_user_error('duplicate_invoice') invoice_data = {} invoice_data['description'] = service.desc invoice_data['party'] = service.patient.name.id invoice_data['account'] = \ service.patient.name.account_receivable.id party_address = Party.address_get(service.patient.name, type='invoice') if not party_address: self.raise_user_error('no_invoice_address') invoice_data['invoice_address'] = party_address.id invoice_data['reference'] = service.name if not service.patient.name.customer_payment_term: self.raise_user_error('no_payment_term') invoice_data['payment_term'] = \ service.patient.name.customer_payment_term.id #Invoice Lines seq = 0 invoice_lines = [] for line in service.service_line: seq = seq + 1 account = line['product'].template.account_revenue_used.id if line['to_invoice']: invoice_lines.append(('create', [{ 'product': line['product'].id, 'description': line['desc'], 'quantity': line['qty'], 'account': account, 'unit': line['product'].default_uom.id, 'unit_price': line['product'].list_price, 'sequence': seq }])) invoice_data['lines'] = invoice_lines invoices.append(invoice_data) Invoice.create(invoices) # Change to invoiced the status on the service document. HealthService.write(services, {'state': 'invoiced'}) return 'end'
def _init(self, data): invoice_obj = Pool().get('account.invoice') invoice = invoice_obj.browse(data['id']) if invoice.type not in ['out_credit_note', 'in_credit_note']: self.raise_user_error('invoice_type') if invoice.state != 'open': self.raise_user_error('invoice_state') return {}
def write(cls, pred_succs, values): Work = Pool().get('project.work') super(PredecessorSuccessor, cls).write(pred_succs, values) works = Work.browse(values.itervalues()) for work in works: work.reset_leveling() for work in works: work.compute_dates()
def transition_create_moves(self): Asset = Pool().get('account.asset') with Transaction().set_context(_check_access=True): assets = Asset.search([ ('state', '=', 'running'), ]) assets = Asset.browse(assets) Asset.create_moves(assets, self.start.date) return 'end'