def set_shares(self, ids, name, value): share_obj = Pool().get('webdav.share') if not value: return attachments = self.browse(ids) for action in value: if action[0] == 'create': for attachment in attachments: action[1]['path'] = attachment.path share_obj.create(action[1]) elif action[0] == 'write': share_obj.write(action[1], action[2]) elif action[0] == 'delete': share_obj.delete(action[1]) elif action[0] == 'delete_all': paths = [a.path for a in attachments] share_ids = share_obj.search([ ('path', 'in', paths), ]) share_obj.delete(share_ids) elif action[0] == 'unlink': pass elif action[0] == 'add': pass elif action[0] == 'unlink_all': pass elif action[0] == 'set': pass else: raise Exception('Bad arguments')
def crear_linea_publicacion_diario(self,producto,descripcion,medida,fecha): edicion = Pool().get('edicion.edicion') publicacion = Pool().get('edicion.publicacion_diario') ubicacion = "NO POSEE" try: split = descripcion.split("\n")[1].split("Ubicacion:") ubicacion = split[0] + split[1] except: pass edic = 0 try: edic= edicion(edicion.search([('fecha', '=', fecha)])[0]) except: edic=edicion.create([{ 'fecha':fecha }])[0] edic.save() pub = publicacion.create([{ 'termino_pago':publicacion(Transaction().context.get('active_id')).termino_pago, 'cliente':publicacion(Transaction().context.get('active_id')).cliente, 'producto' : producto, 'descrip' : descripcion, 'medidas' : medida, 'ubicacion': ubicacion, 'edicion' : edic, 'venta' : publicacion(Transaction().context.get('active_id')).venta, 'viene_de_cm' : True, }])[0] pub.save()
def create_period(cls, fiscalyears, interval=1): ''' Create periods for the fiscal years with month interval ''' Period = Pool().get('account.period') to_create = [] for fiscalyear in fiscalyears: period_start_date = fiscalyear.start_date while period_start_date < fiscalyear.end_date: period_end_date = period_start_date + \ relativedelta(months=interval - 1) + \ relativedelta(day=31) if period_end_date > fiscalyear.end_date: period_end_date = fiscalyear.end_date name = datetime_strftime(period_start_date, '%Y-%m') if name != datetime_strftime(period_end_date, '%Y-%m'): name += ' - ' + datetime_strftime(period_end_date, '%Y-%m') to_create.append({ 'name': name, 'start_date': period_start_date, 'end_date': period_end_date, 'fiscalyear': fiscalyear.id, 'type': 'standard', }) period_start_date = period_end_date + relativedelta(days=1) if to_create: Period.create(to_create)
def _make_gls_label(self): """ This method gets the prepared Shipment object and calls the GLS API for label generation. """ Attachment = Pool().get('ir.attachment') for index, package in enumerate(self.packages, start=1): shipment = package._get_shipment_object() shipment.parcel = index label = shipment.create_label() response = Response.parse(label) # Get tracking number tracking_number = response.values.get('T8913') assert tracking_number package.tracking_number = tracking_number package.save() # Create attachment Attachment.create([{ 'name': "%s_%s_%s.zpl" % ( tracking_number, self.gls_parcel_number, package.code), 'data': response.values.get('zpl_content'), 'resource': '%s,%s' % (self.__name__, self.id), }]) return tracking_number
def make_scanform(self): """ Generate the SCAN Form for bag """ Attachment = Pool().get('ir.attachment') if not self.shipments: self.raise_user_error('bag_empty') pic_numbers = [shipment.tracking_number for shipment in self.shipments] test = self.carrier.endicia_is_test and 'Y' or 'N' scan_request = SCANFormAPI( pic_numbers=pic_numbers, accountid=self.carrier.endicia_account_id, requesterid=self.carrier.endicia_requester_id, passphrase=self.carrier.endicia_passphrase, test=test, ) response = scan_request.send_request() result = objectify_response(response) if not hasattr(result, 'SCANForm'): self.raise_user_error( 'error_scanform', error_args=(result.ErrorMsg,) ) else: self.submission_id = str(result.SubmissionID) self.save() Attachment.create([{ 'name': 'SCAN%s.png' % str(result.SubmissionID), 'data': buffer(base64.decodestring(result.SCANForm.pyval)), 'resource': '%s,%s' % (self.__name__, self.id) }])
def createinvoice(cls, projects): invoice = Pool().get('account.invoice') products = Pool().get('product.product') #print products.search_rec_name(name='Openlabs').name for project in projects: details = { 'payment_term': project.party.customer_payment_term.id, 'party': project.party.id, 'account': project.company.account_receivable.id, 'invoice_address': cls._get_invoice_address(project.party), } details['description'] = project.name lines = [ ('create', { 'line': 'line', 'quantity': 3, 'unit': 30, 'divisor': 4, 'percentage': 25, 'days': 30, }) ] details['lines'] = lines invoice.create(details) return True
def _create_address(cls, data): "Create a new party.address" Address = Pool().get('party.address') NereidUser = Pool().get('nereid.user') ContactMechanism = Pool().get('party.contact_mechanism') email = data.pop('email') phone = data.pop('phone') if request.is_guest_user: existing = NereidUser.search([ ('email', '=', email), ('company', '=', request.nereid_website.company.id), ]) if existing: cls._handle_guest_checkout_with_regd_email(email) data['country'] = data.pop('country') data['subdivision'] = data.pop('subdivision') data['party'] = request.nereid_user.party.id ContactMechanism.create({ 'type': 'email', 'party': request.nereid_user.party.id, 'email': email, }) ContactMechanism.create({ 'type': 'phone', 'party': request.nereid_user.party.id, 'value': phone, }) address = Address.create(data) Address.write([address], {'email': email, 'phone': phone}) return address
def reservador(self,ids,name,value): obj_consulta = Pool().get('cefiro.consulta') for reser in self.browse(ids): for i in range(len(reser.dtini)): obj_consulta.create({'horaini':reser.dtini[i],'horaFin':reser.dtfin[i],'consultorio':reser.consultorio,'psicologos':[]}) return res
def cache_prestashop_id(cls, prestashop_id): """Cache the value of country corresponding to the prestashop_id by creating a record in the cache model :param prestashop_id: Prestashop ID :returns: Active record of the country cached """ CountryPrestashop = Pool().get('country.country.prestashop') SaleChannel = Pool().get('sale.channel') channel = SaleChannel(Transaction().context['current_channel']) channel.validate_prestashop_channel() client = channel.get_prestashop_client() country_data = client.countries.get(prestashop_id) country = cls.search([('code', '=', country_data.iso_code.pyval)]) if not country: cls.raise_user_error( 'country_not_found', (country_data.iso_code.pyval,) ) CountryPrestashop.create([{ 'country': country[0].id, 'channel': channel.id, 'prestashop_id': prestashop_id, }]) return country and country[0] or None
def transition_do_create(self): """Create the entry for the newly created item sheet""" values = {} for key in self.start._fields.keys(): if isinstance(self.start._fields[key], fields.Function): continue if key in ['trunks', 'total_volume_uom', 'mean_volume_uom', 'main_variety']: continue values[key] = getattr(self.start, key) MarkingSheet = Pool().get('marking_sheet.marking_sheet') active_id = Transaction().context['active_id'] marking_sheet = MarkingSheet(active_id) # Set trunks trunks = [trunk.id for trunk in marking_sheet.trunks] values['trunks'] = [('add', trunks)] # Find the main variety (the top-level variety that has a higher # weight) volumes = {} for trunk in marking_sheet.trunks: variety = trunk.variety while not variety.parent is None: variety = variety.parent volumes[variety] = volumes.get(variety, 0) + trunk.total_cubing values['main_variety'] = max(volumes.iteritems(), key=operator.itemgetter(1))[0].id ItemsSheet = Pool().get('items_sheet.items_sheet') ItemsSheet.create([values]) return 'end'
def cache_prestashop_id(cls, prestashop_id): """Cache the value of subdivision corresponding to the prestashop_id by creating a record in the cache model :param prestashop_id: Prestashop ID :returns: Active record of the subdivision cached """ SubdivisionPrestashop = Pool().get("country.subdivision.prestashop") Country = Pool().get("country.country") SaleChannel = Pool().get("sale.channel") channel = SaleChannel(Transaction().context["current_channel"]) channel.validate_prestashop_channel() client = channel.get_prestashop_client() state_data = client.states.get(prestashop_id) # The country should have been cached till now for sure country = Country.get_using_ps_id(state_data.id_country.pyval) subdivision = cls.search([("code", "=", country.code + "-" + state_data.iso_code.pyval)]) if not subdivision: cls.raise_user_error("subdivision_not_found", (country.code + "-" + state_data.iso_code.pyval,)) SubdivisionPrestashop.create( [{"subdivision": subdivision[0].id, "channel": channel.id, "prestashop_id": prestashop_id}] ) return subdivision and subdivision[0] or None
def round_down_total(cls, records): ''' Round down total order price and add remaining amount as new sale line ''' SaleLine = Pool().get('sale.line') sale_lines = [] for record in records: # Check if there's already a roundoff line, remove and create new # if there is. round_off_line = SaleLine.search([ ('sale', '=', record.id), ('is_round_off', '=', True), ]) if round_off_line: SaleLine.delete(round_off_line) floored_total = floor(record.total_amount) amount_diff = record.total_amount - Decimal(floored_total) sale_lines.append({ 'sale': record, 'is_round_off': True, 'type': 'line', 'quantity': -1, 'unit_price': amount_diff, 'description': 'Round Off' }) SaleLine.create( [line for line in sale_lines if line['unit_price']] )
def edit_task(self): """ Edit the task """ Activity = Pool().get("nereid.activity") Work = Pool().get("timesheet.work") task = self.get_task(self.id) Work.write([task.work], {"name": request.form.get("name")}) self.write([task], {"comment": request.form.get("comment")}) Activity.create( [ { "actor": request.nereid_user.id, "object_": "project.work, %d" % task.id, "verb": "edited_task", "target": "project.work, %d" % task.parent.id, "project": task.parent.id, } ] ) if request.is_xhr: return jsonify({"success": True, "name": self.rec_name, "comment": self.comment}) return redirect(request.referrer)
def export_to_magento(self, category): """Export the current product to the magento category corresponding to the given `category` under the current magento_channel in context :param category: Active record of category to which the product has to be exported :return: Active record of product """ Channel = Pool().get('sale.channel') SaleChannelListing = Pool().get('product.product.channel_listing') channel = Channel.get_current_magento_channel() if not category.magento_ids: self.raise_user_error( 'invalid_category', (category.complete_name,) ) listing = SaleChannelListing.search([ ('channel', '=', channel.id), ('product', '=', self.id), ]) if listing: self.raise_user_error( 'invalid_product', (self.name,) ) if not self.products[0].code: self.raise_user_error( 'missing_product_code', (self.name,) ) with magento.Product( channel.magento_url, channel.magento_api_user, channel.magento_api_key ) as product_api: # We create only simple products on magento with the default # attribute set # TODO: We have to call the method from core API extension # because the method for catalog create from core API does not seem # to work. This should ideally be from core API rather than # extension magento_id = product_api.call( 'ol_catalog_product.create', [ 'simple', int(Transaction().context['magento_attribute_set']), self.products[0].code, self.get_product_values_for_export_to_magento( [category], [channel] ) ] ) SaleChannelListing.create([{ 'product_identifier': str(magento_id), 'channel': channel.id, 'product': self.id, 'magento_product_type': 'simple', }]) return self
def remove_tag(cls, task_id, tag_id): """ Assigns the provided to this task :param task_id: ID of task :param tag_id: ID of tag """ Activity = Pool().get("nereid.activity") task = cls.get_task(task_id) cls.write([task], {"tags": [("unlink", [tag_id])]}) Activity.create( [ { "actor": request.nereid_user.id, "object_": "project.work, %d" % task.id, "verb": "removed_tag_from_task", "target": "project.work, %d" % task.parent.id, "project": task.parent.id, } ] ) if request.method == "POST": flash("Tag removed from task %s" % task.rec_name) return redirect(request.referrer) flash("Tag cannot be removed") return redirect(request.referrer)
def create_using_magento_data(cls, order_data): """ Create a sale from magento data. If you wish to override the creation process, it is recommended to subclass and manipulate the returned unsaved active record from the `get_sale_using_magento_data` method. :param order_data: Order data from magento :return: Active record of record created """ MagentoException = Pool().get('magento.exception') MagentoOrderState = Pool().get('magento.order_state') sale = cls.get_sale_using_magento_data(order_data) sale.add_lines_using_magento_data(order_data) sale.save() # Process sale now tryton_state = MagentoOrderState.get_tryton_state(order_data['state']) try: sale.process_sale_using_magento_state(order_data['state']) except UserError, e: # Expecting UserError will only come when sale order has # magento exception. # Just ignore the error and leave this order in draft state # and let the user fix this manually. MagentoException.create([{ 'origin': '%s,%s' % (sale.__name__, sale.id), 'log': "Error occurred on transitioning to state %s.\nError " "Message: %s" % (tryton_state['tryton_state'], e.message), }])
def change_constraint_dates(cls, task_id): """ Change the constraint dates """ Activity = Pool().get("nereid.activity") task = cls.get_task(task_id) data = {"constraint_start_time": False, "constraint_finish_time": False} constraint_start = request.form.get("constraint_start_time", None) constraint_finish = request.form.get("constraint_finish_time", None) if constraint_start: data["constraint_start_time"] = datetime.strptime(constraint_start, "%m/%d/%Y") if constraint_finish: data["constraint_finish_time"] = datetime.strptime(constraint_finish, "%m/%d/%Y") cls.write([task], data) Activity.create( [ { "actor": request.nereid_user.id, "object_": "project.work, %d" % task.id, "verb": "changed_date", "project": task.parent.id, } ] ) if request.is_xhr: return jsonify({"success": True}) flash("The constraint dates have been changed for this task.") return redirect(request.referrer)
def transition_create_(self): Appointment = Pool().get("gnuhealth.appointment") appointments = [] # Iterate over days day_count = (self.start.date_end - self.start.date_start).days + 1 for single_date in (self.start.date_start + timedelta(n) for n in range(day_count)): if ( (single_date.weekday() == 0 and self.start.monday) or (single_date.weekday() == 1 and self.start.tuesday) or (single_date.weekday() == 2 and self.start.wednesday) or (single_date.weekday() == 3 and self.start.thursday) or (single_date.weekday() == 4 and self.start.friday) or (single_date.weekday() == 5 and self.start.saturday) or (single_date.weekday() == 6 and self.start.sunday) ): # Iterate over time dt = datetime.combine(single_date, self.start.time_start) dt_end = datetime.combine(single_date, self.start.time_end) while dt < dt_end: appointment = { "healthprof": self.start.healthprof.id, "speciality": self.start.specialty.id, "institution": self.start.institution.id, "appointment_date": dt, "appointment_date_end": dt + timedelta(minutes=self.start.appointment_minutes), "state": "free", } appointments.append(appointment) dt += timedelta(minutes=self.start.appointment_minutes) if appointments: Appointment.create(appointments) return "open_"
def createMasseEauGeometries(cls, filename, version): meau_model = Pool().get('eau.masseeau') # Initialisation de la lecture du fichier srs = osr.SpatialReference() srs.ImportFromEPSG(2154) driver = ogr.GetDriverByName('ESRI Shapefile') dataset = driver.Open(filename, 0) layer = dataset.GetLayer() feature = layer.GetFeature(0) geo = ogr.ForceToMultiLineString(feature.geometry()) geo.AssignSpatialReference(srs) models = [] # Lecture for index in xrange(layer.GetFeatureCount()): feature = layer.GetFeature(index) geo = ogr.ForceToMultiLineString(feature.GetGeometryRef()) geo.AssignSpatialReference(srs) geo.FlattenTo2D() sql = psycopg2.extensions.AsIs('ST_GeomFromWKB(%s, %s)' % ( psycopg2.extensions.Binary(buffer(geo.ExportToWkb())), geo.GetSpatialReference().GetAuthorityCode('PROJCS'))) models.append({ 'cdmassedea': feature['CdMasseDEa'], 'cdeumassed': feature['CdEUMasseD'], 'name': feature['NomMasseDE'], 'cdcategori': feature['CdCategori'], 'datecreati': parse(feature['DateCreati']).strftime("%Y-%m-%d"), 'datemajmas': parse(feature['DateMajMas']).strftime("%Y-%m-%d"), 'stmassedea': feature['StMasseDEa'], 'cdnaturema': feature['CdNatureMa'], 'appartjeud': feature['AppartJeuD'], 'echdefmass': feature['EchDefMass'], 'typemassed': feature['TypeMasseD'], 'typologiea': feature['TypologieA'], 'categorieg': feature['CategorieG'], 'typologied': feature['TypologieD'], 'critdecoup': feature['CritDecoup'], 'longeurtot': feature['LongeurTot'], 'rangstrahl': feature['RangStrahl'], 'rangstra0': feature['RangStra0'], 'taillefcts': feature['TailleFctS'], 'cdecoregio': feature['CdEcoRegio'], 'cdhydroeco': feature['CdHydroEco'], 'cdhydroe0': feature['CdHydroE0'], 'cdctxpisci': feature['CdCtxPisci'], 'cdbassindc': feature['CdBassinDC'], 'cdeussbass': feature['CdEUSsBass'], 'geom': sql, 'version': version, }) if len(models) > 500: # Enregistrer et vider par paquets de 500 meau_model.create(models) models = [] # Enregistrement du dernier paquet meau_model.create(models)
def create_using_amazon_data(cls, order_data, line_data): """ Create a sale using amazon data :param order_data: Order data from amazon :return: Active record of record created """ Party = Pool().get('party.party') Address = Pool().get('party.address') SaleChannel = Pool().get('sale.channel') ChannelException = Pool().get('channel.exception') amazon_channel = SaleChannel( Transaction().context['current_channel'] ) assert amazon_channel.source == 'amazon_mws' party_values = { 'name': order_data['BuyerName']['value'], 'email': order_data['BuyerEmail']['value'], } party = Party.find_or_create_using_amazon_data(party_values) if 'Phone' in order_data['ShippingAddress']: party.add_phone_using_amazon_data( order_data['ShippingAddress']['Phone']['value'] ) party_invoice_address = party_shipping_address = \ Address.find_or_create_for_party_using_amazon_data( party, order_data['ShippingAddress'] ) sale = cls.get_sale_using_amazon_data(order_data, line_data) sale.party = party.id sale.invoice_address = party_invoice_address.id sale.shipment_address = party_shipping_address.id sale.channel = amazon_channel.id sale.save() # TODO: Handle Discounts # TODO: Handle Taxes if sale.total_amount != Decimal( order_data['OrderTotal']['Amount']['value'] ): ChannelException.create([{ 'origin': '%s,%s' % (sale.__name__, sale.id), 'log': 'Order total does not match.', 'channel': sale.channel.id, }]) return sale # We import only completed orders, so we can confirm them all cls.quote([sale]) cls.confirm([sale]) # TODO: Process the order for invoice as the payment info is received return sale
def remove_tag(cls, task_id, tag_id): """ Assigns the provided to this task :param task_id: ID of task :param tag_id: ID of tag """ Activity = Pool().get('nereid.activity') task = cls.get_task(task_id) cls.write( [task], {'tags': [('remove', [tag_id])]} ) Activity.create([{ 'actor': request.nereid_user.id, 'object_': 'project.work, %d' % task.id, 'verb': 'removed_tag_from_task', 'target': 'project.work, %d' % task.parent.id, 'project': task.parent.id, }]) if request.method == 'POST': flash('Tag removed from task %s' % task.rec_name) return redirect(request.referrer) flash("Tag cannot be removed") return redirect(request.referrer)
def edit_task(self): """ Edit the task """ Activity = Pool().get('nereid.activity') Work = Pool().get('timesheet.work') task = self.get_task(self.id) Work.write([task.work], { 'name': request.form.get('name'), }) self.write([task], { 'comment': request.form.get('comment') }) Activity.create([{ 'actor': request.nereid_user.id, 'object_': 'project.work, %d' % task.id, 'verb': 'edited_task', 'target': 'project.work, %d' % task.parent.id, 'project': task.parent.id, }]) if request.is_xhr: return jsonify({ 'success': True, 'name': self.rec_name, 'comment': self.comment, }) return redirect(request.referrer)
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 export_to_magento(self, category): """Export the current product to the magento category corresponding to the given `category` under the current website in context :param category: Active record of category to which the product has to be exported :return: Active record of product """ Website = Pool().get('magento.instance.website') WebsiteProductTemplate = Pool().get('magento.website.template') if not category.magento_ids: self.raise_user_error( 'invalid_category', (category.complete_name,) ) if self.magento_ids: self.raise_user_error( 'invalid_product', (self.name,) ) if not self.products[0].code: self.raise_user_error( 'missing_product_code', (self.name,) ) website = Website(Transaction().context['magento_website']) instance = website.instance with magento.Product( instance.url, instance.api_user, instance.api_key ) as product_api: # We create only simple products on magento with the default # attribute set # TODO: We have to call the method from core API extension # because the method for catalog create from core API does not seem # to work. This should ideally be from core API rather than # extension magento_id = product_api.call( 'ol_catalog_product.create', [ 'simple', int(Transaction().context['magento_attribute_set']), self.products[0].code, self.get_product_values_for_export_to_magento( [category], [website] ) ] ) WebsiteProductTemplate.create([{ 'magento_id': magento_id, 'website': website.id, 'template': self.id, }]) self.write([self], { 'magento_product_type': 'simple' }) return self
def update_task(self, task_id, project_id=None): """ Accepts a POST request against a task_id and updates the ticket :param task_id: The ID of the task which needs to be updated """ history_obj = Pool().get('project.work.history') task = self.get_task(task_id) history_data = { 'project': task.id, 'updated_by': request.nereid_user.id, 'comment': request.form['comment'] } updatable_attrs = ['state'] post_attrs = [request.form.get(attr, None) for attr in updatable_attrs] if any(post_attrs): # Combined update of task and history since there is some value # posted in addition to the comment task_changes = {} for attr in updatable_attrs: if getattr(task, attr) != request.form[attr]: task_changes[attr] = request.form[attr] if task_changes: # Only write change if anything has really changed self.write(task.id, task_changes) comment_id = self.browse(task.id).history[-1].id history_obj.write(comment_id, history_data) else: # just create comment since nothing really changed since this # update. This is to cover to cover cases where two users who # havent refreshed the web page close the ticket comment_id = history_obj.create(history_data) else: # Just comment, no update to task comment_id = history_obj.create(history_data) if request.nereid_user.id not in (p.id for p in task.participants): # Add the user to the participants if not already in the list self.write( task.id, {'participants': [('add', [request.nereid_user.id])]} ) if request.is_xhr: comment_record = history_obj.browse(comment_id) html = render_template('comment.jinja', comment=comment_record) return jsonify({ 'success': True, 'html': html, 'state': self.browse(task.id).state, }) return redirect(request.referrer)
def add_phone_using_amazon_data(self, amazon_phone): """ Add contact mechanism for party """ ContactMechanism = Pool().get("party.contact_mechanism") if not ContactMechanism.search( [("party", "=", self.id), ("type", "in", ["phone", "mobile"]), ("value", "=", amazon_phone)] ): ContactMechanism.create([{"party": self.id, "type": "phone", "value": amazon_phone}])
def crear(self,ids,name,value): user_obj = Pool().get('res.user') for elem in self.browse(ids): yaCreados = user_obj.search([('login','=','elem.login')]) if len(yaCreados)==0: user_obj.create({'name':elem.name,'login':elem.login,'password':value}) else: user_obj.write(yaCreados,{'password':value}) return
def register_transaction_handler(cls): message_module_name = "pdq.pdq" message_class_name = PDQTransactionHandler.__name__ transaction_handler = Pool().get('hl7.transaction_handler') logger.debug("PDQ Transaction Handler:%s" % str(transaction_handler)) transactions = transaction_handler.search([('message_handler_class_name', '=', message_class_name)]) if not transactions: transaction_handler.create([{"message_type": "QBP^Q22^QBP_Q21", "message_handler_module_name": message_module_name, "message_handler_class_name": message_class_name}]) transaction_handler.create([{"message_type": "QBP^ZV1^QBP_Q21", "message_handler_module_name": message_module_name, "message_handler_class_name": message_class_name}])
def transition_debit(self): IssuedCheck = Pool().get('account.issued.check') Move = Pool().get('account.move') MoveLine = Pool().get('account.move.line') period_id = Pool().get('account.period').find(1, date=self.start.date) for check in IssuedCheck.browse(Transaction().context.get( 'active_ids')): if check.state != 'issued': self.raise_user_error('check_not_issued', error_args=(check.name,)) if not self.start.bank_account.journal.issued_check_account: self.raise_user_error('no_journal_check_account', error_args=(self.start.bank_account.journal.name,)) move, = Move.create([{ 'journal': self.start.bank_account.journal.id, 'period': period_id, 'date': self.start.date, }]) lines = [] lines.append({ 'debit': check.amount, 'credit': Decimal('0.00'), 'account': self.start.bank_account.journal.issued_check_account.id, 'move': move.id, 'journal': self.start.bank_account.journal.id, 'period': period_id, 'party': check.receiving_party.id, }) lines.append({ 'account': self.start.bank_account.journal.debit_account.id, 'debit': Decimal('0.00'), 'credit': check.amount, 'move': move.id, 'journal': self.start.bank_account.journal.id, 'period': period_id, 'date': self.start.date, 'party': check.receiving_party.id }) MoveLine.create(lines) IssuedCheck.write([check], {'state': 'debited'}) Move.post([move]) return 'end'
def create_for_party_using_magento_data(cls, party, address_data): """ Create address from the address record given and link it to the party. :param party: Party active record :param address_data: Dictionary of address data from magento :return: Active record of created address """ Country = Pool().get('country.country') Subdivision = Pool().get('country.subdivision') ContactMechanism = Pool().get('party.contact_mechanism') country = None subdivision = None if address_data['country_id']: country = Country.search_using_magento_code( address_data['country_id'] ) if address_data['region']: subdivision = Subdivision.search_using_magento_region( address_data['region'], country ) address, = cls.create([{ 'party': party.id, 'name': ' '.join([ address_data['firstname'], address_data['lastname'] ]), 'street': address_data['street'], 'zip': address_data['postcode'], 'city': address_data['city'], 'country': country and country.id or None, 'subdivision': subdivision and subdivision.id or None, }]) # Create phone as contact mechanism if address_data.get('telephone') and not ContactMechanism.search([ ('party', '=', party.id), ('type', 'in', ['phone', 'mobile']), ('value', '=', address_data['telephone']), ]): ContactMechanism.create([{ 'party': party.id, 'type': 'phone', 'value': address_data['telephone'], }]) return address
def _add_sale_payment( self, credit_card_form=None, payment_profile=None, alternate_payment_method=None ): """ Add sale payment against sale with given credit card or payment profile or any other alternate payment method. Payments are processed then using these sale payments. All payment profiles are saved as of now. """ AddSalePaymentWizard = Pool().get( 'sale.payment.add', type="wizard" ) payment_wizard = AddSalePaymentWizard( AddSalePaymentWizard.create()[0] ) if current_website.credit_card_gateway and ( payment_profile or credit_card_form ): gateway = current_website.credit_card_gateway if payment_profile: self.validate_payment_profile(payment_profile) payment_wizard.payment_info.use_existing_card = True payment_wizard.payment_info.payment_profile = payment_profile.id elif credit_card_form: # TODO: Do not allow saving payment profile for guest user. # This can introduce an issue when guest user # checkouts multiple times with the same card payment_wizard.payment_info.use_existing_card = False payment_wizard.payment_info.payment_profile = None payment_wizard.payment_info.address = self.invoice_address payment_wizard.payment_info.owner = credit_card_form.owner.data payment_wizard.payment_info.number = \ credit_card_form.number.data payment_wizard.payment_info.expiry_month = \ credit_card_form.expiry_month.data payment_wizard.payment_info.expiry_year = \ unicode(credit_card_form.expiry_year.data) payment_wizard.payment_info.csc = credit_card_form.cvv.data elif alternate_payment_method: gateway = alternate_payment_method.gateway payment_wizard.payment_info.use_existing_card = False payment_wizard.payment_info.payment_profile = None payment_wizard.payment_info.sale = self.id payment_wizard.payment_info.party = self.party.id payment_wizard.payment_info.credit_account = \ self.party.account_receivable.id payment_wizard.payment_info.currency_digits = self.currency_digits payment_wizard.payment_info.amount = self._get_amount_to_checkout() payment_wizard.payment_info.reference = self.reference payment_wizard.payment_info.method = gateway.method payment_wizard.payment_info.provider = gateway.provider payment_wizard.payment_info.gateway = gateway with Transaction().set_context(active_id=self.id): try: payment_wizard.transition_add() except UserError, e: flash(e.message) abort(redirect(request.referrer))
def write(cls, records, values, *args): pool = Pool() UomCategory = Pool().get('product.uom.category') Uom = Pool().get('product.uom') product_templates = pool.get("product.template") product_products = pool.get("product.product") product_suppliers = pool.get("purchase.product_supplier") for ids in records: mark = int(ids.mark) product_template = product_templates.search([('id', '=', mark)]) product_product = product_products.search([('template', '=', mark) ]) product_supplier = product_suppliers.search([('product', '=', mark) ]) uom_uom_min_Package = Uom.search([ ('id', '=', product_template[0].min_Package.id) ]) uom_uom_default_uom = Uom.search([ ('id', '=', product_template[0].default_uom.id) ]) uom_category = UomCategory.search([ ('id', '=', product_template[0].default_uom.category.id) ]) lv = {} lvc = {} uom_min_Package = {} uom_default_uom = {} if 'name' in values: UomCategory.write(uom_category, { 'name': values['name'] + uom_category[0].name.split('/')[1] }) if 'uom_min_Package' in values: uom_min_Package['name'] = values['uom_min_Package'] uom_min_Package['symbol'] = values['uom_min_Package'] values.pop('uom_min_Package') Uom.write(uom_uom_min_Package, uom_min_Package) if 'uom_default_uom' in values: uom_default_uom['name'] = values['uom_default_uom'] uom_default_uom['symbol'] = values['uom_default_uom'] values.pop('uom_default_uom') if 'capacity' in values: Uom.write(uom_uom_default_uom, {'active': False}) uom_uom_default_uom = Uom.create([{ u'category': uom_category[0].id, u'digits': 2, u'name': uom_uom_default_uom[0].name, u'rounding': 0.01, u'symbol': uom_uom_default_uom[0].name, u'rate': round(1 / float(values['capacity']), 12), u'factor': float(values['capacity']), u'active': True }]) values['sale_uom'] = uom_uom_default_uom[0].id values['purchase_uom'] = uom_uom_default_uom[0].id values['default_uom'] = uom_uom_default_uom[0].id if uom_default_uom: Uom.write(uom_uom_default_uom, uom_default_uom) if 'party' in values: lvc['party'] = values['party'] values.pop('party') if lvc != {}: product_suppliers.write(product_supplier, lvc) if 'code' in values: UomCategory.write(uom_category, { 'name': uom_category[0].name.split('/')[0] + values['name'] }) lv['code'] = values['code'] values.pop('code') if 'template' in values: lv['template'] = values[mark] values.pop('template') if lv != {}: product_products.write(product_product, lv) if 'mark' in values: values.pop('mark') if 'categories' in values: values['categories'] = [[ u'add', [values['categories']] ], [u'remove', [product_template[0].categories[0].id]]] if values != {}: product_templates.write(product_template, values) if 'sale_uom' in values: values.pop('sale_uom') if 'purchase_uom' in values: values.pop('purchase_uom') return super(New_products, cls).write(records, values)
def test_create_required_without_value(self): "Test create text required without value" Text = Pool().get('test.text_required') with self.assertRaises(UserError): Text.create([{}])
def create(cls, vlist): UserId = Pool().get('hrp_internal_delivery.test_straight') location_id = UserId.get_warehouse_frozen_id() # Config = Pool().get('purchase.configuration') # config = Config(1) # 库存地配置 # location_id = [config.hospital.id,config.outpatient_service.id,config.warehouse.id,config.medical.id,config.endoscopic.id,config.preparation.id,config.ward.id,config.herbs.id] price_content = Pool().get('hrp_report.price_profit_loss_content') UomCategory = Pool().get('product.category') Date = Pool().get('ir.date') today = str(Date.today()) price = Pool().get("product.template") product = Pool().get("product.product") if str(vlist[0]['effective_date']) == today: product_id = vlist[0]['retrieve_the_code'] Product = product.search([('id', '=', product_id)]) product_template_id = Product[0].template.id New = price.search([('id', '=', product_template_id)]) if New: lvc = { 'list_price': vlist[0]['new_list_price'], 'cost_price': vlist[0]['new_cost_price'] } price.write(New, lvc) content = [] for each in location_id: content_dict = {} with Transaction().set_context( stock_date_end=Date.today()): quantities = product.products_by_location( [each['warehouse']], [product_id], with_childs=True) if quantities.values(): stock_level_warehouse = [ v for v in quantities.values() ][0] else: stock_level_warehouse = 0 with Transaction().set_context( stock_date_end=Date.today()): quantities = product.products_by_location( [each['freeze']], [product_id], with_childs=True) if quantities.values(): stock_level_freeze = [ v for v in quantities.values() ][0] else: stock_level_freeze = 0 stock_level = stock_level_warehouse + stock_level_freeze party = Product[0].product_suppliers if party: party = party[0].party.name else: party = '' categories = [i.id for i in Product[0].categories] uom_category = UomCategory.search([('id', '=', categories[0])]) uom_name = uom_category[0].name if uom_name == u'西药': content_dict['drug_type'] = '00' if uom_name == u'中成药': content_dict['drug_type'] = '01' if uom_name == u'中草药': content_dict['drug_type'] = '02' if uom_name == u'颗粒中': content_dict['drug_type'] = '03' if uom_name == u'原料药': content_dict['drug_type'] = '04' if uom_name == u'敷药': content_dict['drug_type'] = '05' if uom_name == u'同位素': content_dict['drug_type'] = '07' content_dict['location'] = each['warehouse'] content_dict['code'] = vlist[0]['product_code'] content_dict['product'] = vlist[0]['product_name'] content_dict['drug_specifications'] = vlist[0][ 'drug_specifications'] content_dict['list_price'] = vlist[0]['list_price'] content_dict['cost_price'] = vlist[0]['cost_price'] content_dict['new_list_price'] = vlist[0][ 'new_list_price'] content_dict['new_cost_price'] = vlist[0][ 'new_cost_price'] content_dict['inventory'] = float(stock_level) content_dict['effective_date'] = today content_dict['party'] = party content_dict['uom'] = Product[ 0].template.default_uom.id content_dict['price_profit_loss'] = decimal.Decimal( str(stock_level)) * (decimal.Decimal( str(vlist[0]['new_cost_price'])) - vlist[0]['cost_price']) content_dict[ 'price_list_profit_loss'] = decimal.Decimal( str(stock_level)) * (decimal.Decimal( str(vlist[0]['new_list_price'])) - vlist[0]['list_price']) content.append(content_dict) price_content.create(content) else: pass return super(PriceData, cls).create(vlist)
def create(cls, vlist): pool = Pool() UomCategory = Pool().get('product.uom.category') Uom = Pool().get('product.uom') product_templates = pool.get("product.template") product_products = pool.get("product.product") product_supplier = pool.get("purchase.product_supplier") product_configurations = pool.get("product.configuration") product_configuration = product_configurations.search([]) for value in vlist: product_codes = product_products.search([('name', '=', value['code'])]) if product_codes: cls.raise_user_error(u'%s已经存在!') % value['name'] uom_category = UomCategory.create([{ 'name': value['name'] + '/' + value['code'] }]) uom_min_Package = Uom.create([{ u'category': uom_category[0].id, u'digits': 2, u'name': value['uom_min_Package'], u'rounding': 1, u'symbol': value['uom_min_Package'], u'rate': 1.0, u'factor': 1.0, u'active': True }]) uom_default_uom = Uom.create([{ u'category': uom_category[0].id, u'digits': 2, u'name': value['uom_default_uom'], u'rounding': 0.01, u'symbol': value['uom_default_uom'], u'rate': round(1 / float(int(value['capacity'])), 12), u'factor': float(value['capacity']), u'active': True }]) print value['name'] is_antimicrobials = value['is_antimicrobials'] party = value['party'] medical_insurance_code = value['medical_insurance_code'] attach = value['attach'] concentration = value['concentration'] concentration_unit = value['concentration_unit'] dose_unit = value['dose_unit'] retrieve_the_code = value['retrieve_the_code'] capacity = value['capacity'] is_direct_sending = value['is_direct_sending'] approval_number = value['approval_number'] a_charge = value['a_charge'] drup_level = value['drup_level'] compound_dose = value['compound_dose'] purchase_code = value['purchase_code'] retail_package = uom_min_Package[0].id # value['retail_package'] medical_insurance_description = value[ 'medical_insurance_description'] new_term = value['new_term'] state = value['state'] min_Package = Uom(uom_min_Package[0].id) dosage_form_description = value['dosage_form_description'] interim = value['interim'] national_essential_medicines = value[ 'national_essential_medicines'] poison_hemp_spirit = value['poison_hemp_spirit'] manufacturers_describtion = value['manufacturers_describtion'] name = value['name'] active = True type = value['type'] default_uom = uom_default_uom[0].id code = value['code'] list_price = value['list_price'] cost_price = value['cost_price'] cost_price_method = value['cost_price_method'] categories = [[u'add', [value['categories']]]] salable = value['salable'] purchasable = value['purchasable'] manufacturers_code = value['manufacturers_code'] consumable = value['consumable'] dose = value['dose'] if 'dose' in value and dose != None: drug_specificationss = str( value['dose'].encode('utf-8')) + str( (value['dose_unit']).encode('utf-8')) + '*' + str( (value['capacity'] ).encode('utf-8')) + str(min_Package) elif 'concentration' in value and concentration != None: drug_specificationss = str( value['concentration']).encode('utf-8') + ( value['concentration_unit'] ).encode('utf-8') + '*' + str( (value['capacity']).encode('utf-8')) + str(min_Package) else: drug_specificationss = '*' + str( (value['capacity']).encode('utf-8')) + str(min_Package) value['drug_specifications'] = str(drug_specificationss) add_each = [{ 'is_antimicrobials': is_antimicrobials, 'medical_insurance_code': medical_insurance_code, 'attach': attach, 'concentration': concentration, 'concentration_unit': concentration_unit, 'dose': dose, 'dose_unit': dose_unit, 'retrieve_the_code': retrieve_the_code, 'capacity': capacity, 'is_direct_sending': is_direct_sending, 'a_charge': a_charge, 'drup_level': drup_level, 'compound_dose': compound_dose, 'purchase_code': purchase_code, 'retail_package': retail_package, 'medical_insurance_description': medical_insurance_description, 'new_term': new_term, 'state': state, 'manufacturers_code': manufacturers_code, 'min_Package': min_Package, 'dosage_form_description': dosage_form_description, 'manufacturers_describtion': manufacturers_describtion, 'poison_hemp_spirit': poison_hemp_spirit, 'national_essential_medicines': national_essential_medicines, 'interim': interim, 'drug_specifications': drug_specificationss, 'name': name, 'active': active, 'type': type, 'default_uom': default_uom, 'list_price': list_price, 'cost_price': cost_price, 'cost_price_method': cost_price_method, 'categories': categories, 'approval_number': approval_number, 'salable': salable, 'purchasable': purchasable, 'consumable': consumable, 'sale_uom': default_uom, 'purchase_uom': default_uom, }] account_revenue = product_configuration[0].account_revenue shelf_life_state = product_configuration[0].shelf_life_state account_expense = product_configuration[0].account_expense expiration_state = product_configuration[0].expiration_state if account_revenue == None: raise ValueError('Please fill in the product configuration') else: add_each[0]['account_revenue'] = int(account_revenue) if shelf_life_state == None: raise ValueError('Please fill in the product configuration') else: add_each[0]['shelf_life_state'] = str(shelf_life_state) if account_expense == None: raise ValueError('Please fill in the product configuration') else: add_each[0]['account_expense'] = int(account_expense) if expiration_state == None: raise ValueError('Please fill in the product configuration') else: add_each[0]['expiration_state'] = str(expiration_state) product_template = product_templates.create(add_each) marks = int(product_template[0].id) product_product = product_products.create([{ 'template': marks, 'code': code, 'active': True }]) product_supplier.create([{'product': marks, 'party': party}]) value['mark'] = marks return super(New_products, cls).create(vlist)
def create_categories_from_file(filename): """ This method must be called within the context of an open transaction :param filename: The full path to the file containing uncompressed XML :param pool: Initialised pool for the database """ from trytond.pool import Pool category_obj = Pool().get('product.category') static_file_obj = Pool().get('nereid.static.file') static_folder_obj = Pool().get('nereid.static.folder') id_map = {} tree = etree.parse(filename) categories = tree.getroot().xpath('Response/CategoriesList/Category') logging.info("%d Categories to import" % len(categories)) folder_id = static_folder_obj.create({ 'folder_name': 'category', 'description': 'Product Category Images', }) for category in categories: name_en = category.xpath('Name[@langid=1]') desc_en = category.xpath('Description[@langid=1]') data = { # Get the english name 'name': name_en and name_en[0].get('Value') or 'Products', 'description': desc_en and desc_en[0].get('Value') or '', # Enable later 'displayed_on_eshop': False, # Fill the hierarchy only at a second pass 'parent': False } id_map[category.get('ID')] = category_obj.create(data) if category.get('LowPic'): image_id = static_file_obj.create({ 'name': (name_en and name_en[0].get('Value').replace('/', '-') \ or 'Products') + '-' + category.get('ID'), 'folder': folder_id, 'type': 'remote', 'remote_path': category.get('LowPic') }) category_obj.write(id_map[category.get('ID')], {'image': image_id}) logging.info("%d Categories created without hierarchy" % len(id_map)) logging.info("Setting up hierarchies") for category in categories: if category.get('ID') == '1': # its the root category continue parent_category = category.xpath('ParentCategory') if parent_category: category_obj.write( id_map[category.get('ID')], {'parent': id_map[parent_category[0].get('ID')]}) logging.info("Saved hierarchy") # Now create the hierarchies logging.info("Creating URIs for all categories") for cat_id, category_id in id_map.iteritems(): try: category_obj.update_uri([category_id]) category_obj.write(category_id, {'displayed_on_eshop': True}) except Exception, exc: if 'UserError' in exc: logging.warning( "Error on URI creation for Category ID:%s\n%s" % (cat_id, exc)) else: raise exc
def test_create_required_without_value(self): "Test create binary without value" Binary = Pool().get('test.binary_required') with self.assertRaises(UserError): binary, = Binary.create([{}])
def test_create_required_without_value(self): "Test create one2many required without value" One2Many = Pool().get('test.one2many_required') with self.assertRaises(RequiredValidationError): One2Many.create([{}])
def test_create_required_without_value(self): "Test create date required without value" Date = Pool().get('test.date_required') with self.assertRaises(RequiredValidationError): Date.create([{}])
def test_create_required_without_value(self): "Test create float required without value" Float = Pool().get('test.float_required') with self.assertRaises(RequiredValidationError): Float.create([{}])
def find_or_create_bom_for_magento_bundle(cls, order_data): """ Find or create a BoM for bundle product from the data sent in magento order :param order_data: Order Data from magento :return: Found or created BoM's active record """ Uom = Pool().get('product.uom') ProductBom = Pool().get('product.product-production.bom') Channel = Pool().get('sale.channel') identified_boms = cls.identify_boms_from_magento_data(order_data) if not identified_boms: return channel = Channel.get_current_magento_channel() for item_id, data in identified_boms.iteritems(): bundle_product = \ channel.get_product(data['bundle']['sku']) # It contains a list of tuples, in which the first element is the # product's active record and second is its quantity in the BoM child_products = [(channel.get_product(each['sku']), (float(each['qty_ordered']) / float(data['bundle']['qty_ordered']))) for each in data['components']] # Here we match the sets of BoM components for equality # Each set contains tuples of product and quantity of that # product in the BoM # If everything for a BoM matches, then we dont create a new one # and use this BoM itself # XXX This might eventually have issues because of rounding # in quantity for product_bom in bundle_product.boms: existing_bom_set = set([(input.product.id, input.quantity) for input in product_bom.bom.inputs]) new_bom_set = set([(product.id, qty) for product, qty in child_products]) if existing_bom_set == new_bom_set: break else: # No matching BoM found, create a new one unit, = Uom.search([('name', '=', 'Unit')]) bom, = cls.create([{ 'name': bundle_product.name, 'inputs': [('create', [{ 'uom': unit.id, 'product': product.id, 'quantity': quantity, }]) for product, quantity in child_products], 'outputs': [('create', [{ 'uom': unit, 'product': bundle_product.id, 'quantity': bundle_product.quantity, }])] }]) product_bom = ProductBom.create([{ 'product': bundle_product.id, 'bom': bom.id, }]) return product_bom
def do_create_(self, action): Config = Pool().get('purchase.configuration') config = Config(1) # 库存地配置 internal = Pool().get('stock.shipment.internal') data = {} ZY = config.hospital.storage_location.id # 住院药房 MZ = config.outpatient_service.storage_location.id # 门诊药房 TJ = config.medical.storage_location.id # 体检药房 NJ = config.endoscopic.storage_location.id # 内镜药房 ZJ = config.preparation.storage_location.id # 制剂室 FS = config.ward.storage_location.id # 放射科 CY = config.herbs.storage_location.id # 草药房 date = time.strftime('%Y%m', time.localtime()) sequence_dict = {ZY: 'B', MZ: 'X', TJ: 'T', NJ: 'N', ZJ: 'J', FS: 'F', CY: 'C'} Keys = sequence_dict.keys() for state_name, state in self.states.iteritems(): if isinstance(state, StateView): data[state_name] = getattr(self, state_name)._default_values list_straights = [] lv = {} lv['starts'] = data['start']['type'] lv['company'] = 1 lv['to_location'] = config.transfers.id # 中转库存地transfers lv['from_location'] = data['start']['from_location'] lv['place_of_service'] = data['start']['to_location'] lv['planned_date'] = data['start']['planned_date'] lv['drug_starts'] = data['start']['starts'] lv['state'] = u'draft' Move = data['start']['moves'] if data['start']['type'] == '00': state = '00' else: state = '06' if data['start']['type'] == '00': list_branch = [] list = [] for each in Move: if each['is_collar'] == True: list_branch.append(1) dict = {} dict['origin'] = None # each['origin'] dict['to_location'] = config.transfers.id # 中转库 dict['product'] = each['product'] dict['from_location'] = data['start']['from_location'] dict['invoice_lines'] = () dict['company'] = 1 # each['company'] dict['is_direct_sending'] = each['is_direct_sending'] # 是否直送 dict['unit_price'] = each['unit_price'] # 产品的价格 dict['lot'] = None dict['starts'] = state dict['uom'] = each['company'] dict['real_number'] = each['proposal'] # 产品的请领数量 dict['quantity'] = each['proposal'] list.append(dict) lv['moves'] = [['create', list]] if len(list_branch) == 5: from_id = data['start']['to_location'] if from_id in Keys: start_number = sequence_dict[from_id] start_ = start_number + '20' start_condition_done = 'Y' + start_number + '20' ShipmentNumber = internal.search([('number', 'like', start_ + '%')], order=[["create_date", "DESC"]]) DoneShipment = internal.search([('number', 'like', start_condition_done + '%')], order=[["create_date", "DESC"]]) done_number_sequence = DoneShipment[0].number[8:12] done_number = DoneShipment[0].number[2:8] if ShipmentNumber: if int(ShipmentNumber[0].number[1:7]) == int(date): number_sequence = ShipmentNumber[0].number[7:11] if int(done_number) == int(date): if int(done_number_sequence) > int(number_sequence): number_int = int(done_number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: number_int = int(number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: number_int = int(number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence elif DoneShipment: if int(DoneShipment[0].number[2:8]) == int(date): number_sequence = DoneShipment[0].number[8:12] if int(done_number) == int(date): number_int = int(done_number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: number_int = int(number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence internal.create([lv]) list_branch[:] list = [] from_id = data['start']['to_location'] if from_id in Keys: start_number = sequence_dict[from_id] start_condition = start_number + str(date) start_condition_done = 'Y' + start_number + '20' ShipmentNumber = internal.search([('number', 'like', start_condition + '%')], order=[["create_date", "DESC"]]) DoneShipment = internal.search([('number', 'like', start_condition_done + '%')], order=[["create_date", "DESC"]]) if DoneShipment: done_number_sequence = DoneShipment[0].number[8:12] done_number = DoneShipment[0].number[2:8] else: done_number_sequence = 0 done_number = 0 if ShipmentNumber: if int(ShipmentNumber[0].number[1:7]) == int(date): number_sequence = ShipmentNumber[0].number[7:11] if int(done_number) == int(date): if int(done_number_sequence) > int(number_sequence): number_int = int(done_number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: number_int = int(number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: number_int = int(number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence elif DoneShipment: if int(DoneShipment[0].number[2:8]) == int(date): number_sequence = DoneShipment[0].number[8:12] if int(done_number) == int(date): number_int = int(done_number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: number_int = int(number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence if list == []: pass else: internal.create([lv]) return action, {} else: for each in Move: if each['is_collar'] == True: ############################## 对内部请领单据的处理(合单) ############################## interna_query = internal.search([ ('straights', '=', True), ('place_of_service', '=', data['start']['to_location']), ('state', '=', 'draft'), ('to_location', '=', config.transfers.id), ('planned_date', '=', data['start']['planned_date']), ('drug_starts', '=', data['start']['starts']), ]) Move = Pool().get('stock.move') if interna_query: list_product = [] list_move = [] move_query = {} for query_each in interna_query: mmm = query_each.moves for i in mmm: if i.change_start == True: list_product.append(i.product.id) list_move.append(i.id) move_query[i.product.id] = [i.id, i.quantity] if each['product'] in list_product: move_id = move_query[each['product']][0] move_quantity = move_query[each['product']][-1] move_line = Move.search([('id', '=', move_id)]) quantity = move_quantity + each['proposal'] Move.write(move_line, {'quantity': quantity, 'real_number': quantity}) else: create_move = Pool().get('stock.move') dict = {} dict['origin'] = None # each['origin'] dict['to_location'] = config.transfers.id # 中转库 dict['product'] = each['product'] dict['from_location'] = data['start']['from_location'] dict['invoice_lines'] = () # each['invoice_lines'] dict['company'] = 1 # each['company'] dict['is_direct_sending'] = each['is_direct_sending'] # 是否直送 dict['unit_price'] = each['unit_price'] # 产品的价格 dict['lot'] = None dict['starts'] = state dict['uom'] = each['company'] dict['real_number'] = each['proposal'] # 产品的请领数量 dict['quantity'] = each['proposal'] dict['shipment'] = 'stock.shipment.internal,' + str(interna_query[0].id) create_move.create([dict]) else: dict = {} dict['origin'] = None # each['origin'] dict['to_location'] = config.transfers.id # 中转库 dict['product'] = each['product'] dict['from_location'] = data['start']['from_location'] dict['invoice_lines'] = () # each['invoice_lines'] dict['company'] = 1 # each['company'] dict['is_direct_sending'] = each['is_direct_sending'] # 是否直送 dict['unit_price'] = each['unit_price'] # 产品的价格 dict['lot'] = None dict['starts'] = state dict['uom'] = each['company'] dict['real_number'] = each['proposal'] # 产品的请领数量 dict['quantity'] = each['proposal'] list_straights.append(dict) lv['straights'] = True from_id = data['start']['to_location'] if from_id in Keys: start_number = sequence_dict[from_id] start_ = start_number + str(date) start_condition_done = 'Y' + start_number + '20' ShipmentNumber = internal.search([('number', 'like', start_ + '%')], order=[["create_date", "DESC"]]) done_list_number = [] DoneShipment = internal.search([('number', 'like', start_condition_done + '%')]) for i in DoneShipment: done_list_number.append(int(i.number[8:12])) done_list_number.sort() done_number_sequence = done_list_number[-1] if ShipmentNumber: if int(ShipmentNumber[0].number[1:7]) == int(date): number_sequence = ShipmentNumber[0].number[7:11] if int(done_number_sequence) > int(number_sequence): number_int = int(done_number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: number_int = int(number_sequence) + 1 EndNumber = str(number_int).zfill(4) NumberSequence = start_number + str(date) + str(EndNumber) lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence else: NumberSequence = start_number + date + '0001' lv['number'] = NumberSequence lv['moves'] = [['create', list_straights]] Lines = Pool().get('purchase.line') party_partysd = Pool().get("purchase.purchase") Party = party_partysd.search([ ('party', '=', each['party']), ('purchase_date', '=', data['start']['planned_date']), ('delivery_place', '=', data['start']['to_location']), ('state', '=', 'draft'), ]) antrag_auf = [] Antrag_list = {} lines_dict = {} if Party: product_id = [] lines_dicts = {} for lines in Party[0].lines: product_id.append(lines.product.id) lines_dicts[lines.product.id] = lines.id if each['product'] in product_id: product = Pool().get('product.product') product_id = each['product'] unit_price = product.search([('id', '=', product_id)])[0].template.cost_price line = Lines.search([('id', '=', lines_dicts[each['product']])]) quantity = line[0].quantity + each['proposal'] Lines.write(line, {'quantity': quantity, 'unit_price': unit_price}) else: sequence_sort = [] for lines in Party[0].lines: sequence_sort.append(lines.id) sequence_number = len(sequence_sort) + 1 numid = Party[0].id lines_dict['sequence'] = sequence_number # 序列 lines_dict['product'] = each['product'] lines_dict['quantity'] = each['proposal'] # 产品请领的数量 lines_dict['unit'] = None lines_dict['description'] = ' ' # 产品的描述 product = Pool().get('product.product') product_id = each['product'] unit_price = product.search([('id', '=', product_id)])[0].template.cost_price lines_dict['unit_price'] = unit_price # 产品的价格 lines_dict['unit'] = each['company'] lines_dict['purchase'] = numid lines_dict['drug_starts'] = data['start']['starts'] antrag_auf.append(lines_dict) Lines.create(antrag_auf) else: Party = Pool().get('party.party') party = Party.search([ ('id', '=', each['party']) ]) if party: supplier_payment_term = party[0].supplier_payment_term else: supplier_payment_term = None Antrag_list['party'] = each['party'] Antrag_list['invoice_address'] = party[0].addresses[0].id Antrag_list['payment_term'] = supplier_payment_term Antrag_list['company'] = 1 Antrag_list['delivery_place'] = data['start']['to_location'] # 送货点 Antrag_list['purchase_date'] = data['start']['planned_date'] # Antrag_list['warehouse'] = 4 # each['warehouse_location'] party_partysd.create([Antrag_list]) Party_partysd = party_partysd.search([ ('delivery_place', '=', data['start']['to_location']), ('party', '=', each['party']), ('purchase_date', '=', data['start']['planned_date']), ('state', '=', 'draft'), ]) sequence_number = 0 for each_par in Party_partysd: sequence_number += 1 numid = each_par.id lines_dict['sequence'] = sequence_number lines_dict['product'] = each['product'] lines_dict['quantity'] = each['proposal'] # 产品请领的数量 lines_dict['unit'] = None lines_dict['description'] = ' ' # 产品的描述 product = Pool().get('product.product') product_id = each['product'] unit_price = product.search([('id', '=', product_id)])[0].template.cost_price lines_dict['unit_price'] = unit_price # 产品的价格 lines_dict['unit'] = each['company'] lines_dict['purchase'] = numid lines_dict['drug_starts'] = data['start']['starts'] antrag_auf.append(lines_dict) Lines.create(antrag_auf) if 'moves' in lv.keys(): internal.create([lv]) purchase_id = internal.search([ ('straights', '=', True), ('drug_starts', '=', data['start']['starts']), ('state', '=', 'draft'), ('to_location', '=', config.transfers.id), ('planned_date', '=', data['start']['planned_date']), ]) order_number = purchase_id[0].number party_write = Pool().get("purchase.purchase") Party = party_write.search([ ('purchase_date', '=', data['start']['planned_date']), ('delivery_place', '=', data['start']['to_location']), ('state', '=', 'draft'), ]) for party in Party: for i in party.lines: if i.drug_starts == data['start']['starts']: line = Lines.search([('id', '=', i.id)]) Lines.write(line, {'internal_order': order_number}) else: pass return action, {}
def test_create_required_without_value(self): "Test create selection required without value" Selection = Pool().get('test.multi_selection_required') with self.assertRaises(RequiredValidationError): Selection.create([{}])
def sign_in(cls): ''' Step 1: Sign In or Register GET ~~~ Renders a sign-in or register page. If guest checkout is enabled, then an option to continue as guest is also permitted, in which case the email is a required field. POST ~~~~ For guest checkout, this sign in would create a new party with the name as the current session_id and move the shopping cart's sale to the new user's ownership Designer notes: The registration or login must contact the corresponding handlers. Login and Registraion handlers are designed to handle a `next` parameter where the user would be redirected to if the operation was successful. The next url is provided in the context OTOH, if the user desires to checkout as guest, the user is required to fill in the email and submit the form, which posts the email to this handler. ''' NereidCart = Pool().get('nereid.cart') NereidUser = Pool().get('nereid.user') Party = Pool().get('party.party') if not current_user.is_anonymous(): form = cls.sign_in_form( email=current_user.email, checkout_mode='account', ) else: # Guest user form = cls.sign_in_form( email=session.get('email'), checkout_mode='guest', ) if form.validate_on_submit(): if form.checkout_mode.data == 'guest': if not cls.allowed_as_guest(form.email.data): return render_template( 'checkout/signin-email-in-use.jinja', email=form.email.data) cart = NereidCart.open_cart() party_name = unicode( _('Guest with email: %(email)s', email=form.email.data)) if cart.sale.party == request.nereid_website.guest_user.party: # Create a party with the email as email, and session as # name, but attach the session to it. party, = Party.create([{ 'name': party_name, 'nereid_session': session.sid, 'addresses': [], 'contact_mechanisms': [('create', [{ 'type': 'email', 'value': form.email.data, }])] }]) cart.sale.party = party # TODO: Avoid this if the user comes to sign-in twice. cart.sale.shipment_address = None cart.sale.invoice_address = None cart.sale.save() else: # Perhaps the email changed ? party = cart.sale.party party.name = party_name # contact_mechanism of email type will always be there for # Guest user contact_mechanism = filter(lambda c: c.type == 'email', party.contact_mechanisms)[0] contact_mechanism.value = form.email.data contact_mechanism.save() party.email = form.email.data party.save() return redirect(url_for('nereid.checkout.shipping_address')) else: # The user wants to use existing email to login user = NereidUser.authenticate(form.email.data, form.password.data) if user: # FIXME: Remove remember_me login_user(user, remember=form.remember.data) return redirect( url_for('nereid.checkout.shipping_address')) else: failed_login.send() if not current_user.is_anonymous(): # Registered user with a fresh login can directly proceed to # step 2, which is filling the shipping address # # if this is a recent sign-in by a registred user # automatically proceed to the shipping_address step return redirect(url_for('nereid.checkout.shipping_address')) return render_template( 'checkout/signin.jinja', form=form, next=url_for('nereid.checkout.shipping_address'))
def test_create_required_without_value(self): "Test create integer required without value" Integer = Pool().get('test.integer_required') with self.assertRaises(RequiredValidationError): Integer.create([{}])
def create(cls): "Create a session" Session = Pool().get('ir.session.wizard') cls.check_access() return (Session.create([{}])[0].id, cls.start_state, cls.end_state)
class BedCreator(Wizard): 'Create Multiple Hospital Beds' __name__ = 'health_jamaica_hospital.create_beds' start = StateView('health_jamaica_hospital.create_beds.start', 'health_jamaica_hospital.create_bed_view', [ Button('Cancel', 'end', 'tryton-cancel'), Button('Ok', 'mover', default=True) ]) mover = StateTransition() def transition_mover(self): """determines the state to transition to when a selection is made""" start = self.start self.BedModel = Pool().get('gnuhealth.hospital.bed') num_bed = start.number_of_beds bed_total = self.BedModel.search_count([('ward', '=', start.ward) ]) + num_bed self.bed_on_ward = self.BedModel.search_count([('ward', '=', self.start.ward.id)]) if start.ward and bed_total > start.ward.number_of_beds: beds_left = self.start.ward.number_of_beds - self.bed_on_ward self.raise_user_error( "This ward's maximum capacity is %d beds\n" "There are currently %d beds on this ward\n" "You can only create %d more beds for this ward." % (self.start.ward.number_of_beds, self.bed_on_ward, beds_left)) def get_prod(bed_number): """Creates a bed product from the product template returned by get_prod_temp function""" #temp_lis = get_prod_temp() prod = [] #assert(len(temp_lis) > 0) Product = Pool().get('product.product') template_dict = dict(template=start.product_template, code="%s - %d" % (self.start.ward.wardcode, bed_number), is_bed=True, active=True) prod.append(template_dict) return Product.create(prod) def create_beds(num_bed): """Creates beds based on the argument num_bed and on the product returned from get_prod()""" beds = [] self.bed_on_ward = self.bed_on_ward + 1 for i in range(num_bed): prod_lis = get_prod(self.bed_on_ward + i) bed_dic = dict(name=prod_lis[0].id, ward=self.start.ward, bed_type=self.start.bed_type, institution=self.start.ward.institution, state='free', telephone_number=self.start.telephone, movable=self.start.bed_transferable) beds.append(bed_dic) self.BedModel.create(beds) create_beds(num_bed) return 'end'
def test_create_required_without_value(self): "Test create char required without value" Char = Pool().get('test.char_required') with self.assertRaises(UserError): Char.create([{}])
def create_move(self, date=None): """ Create the account move for the payment :param date: Optional date for the account move :return: Active record of the created move """ Currency = Pool().get('currency.currency') Period = Pool().get('account.period') Move = Pool().get('account.move') journal = self.gateway.journal date = date or self.date if not journal.debit_account: self.raise_user_error('missing_debit_account', (journal.rec_name, )) period_id = Period.find(self.company.id, date=date) amount_second_currency = second_currency = None amount = self.amount if self.currency != self.company.currency: amount = Currency.compute(self.currency, self.amount, self.company.currency) amount_second_currency = self.amount second_currency = self.currency refund = self.type == 'refund' lines = [{ 'description': self.rec_name, 'account': self.credit_account.id, 'party': self.party.id, 'debit': Decimal('0.0') if not refund else amount, 'credit': Decimal('0.0') if refund else amount, 'amount_second_currency': amount_second_currency, 'second_currency': second_currency, }, { 'description': self.rec_name, 'account': journal.debit_account.id, 'debit': Decimal('0.0') if refund else amount, 'credit': Decimal('0.0') if not refund else amount, 'amount_second_currency': amount_second_currency, 'second_currency': second_currency, }] move, = Move.create([{ 'journal': journal.id, 'period': period_id, 'date': date, 'lines': [('create', lines)], 'origin': '%s,%d' % (self.__name__, self.id), }]) Move.post([move]) # Set the move as the move of this transaction self.move = move self.save() return move
def test_create_required_without_value(self): "Test create numeric required without value" Numeric = Pool().get('test.numeric_required') with self.assertRaises(UserError): Numeric.create([{}])
def create_profit_loss(cls, Pricedata): for price_data in Pricedata: UserId = Pool().get('hrp_internal_delivery.test_straight') location_id = UserId.get_warehouse_frozen_id() price_content = Pool().get('hrp_report.price_profit_loss_content') UomCategory = Pool().get('product.category') Date = Pool().get('ir.date') today = str(Date.today()) product = Pool().get('product.product') content = [] for each in location_id: dict = {} with Transaction().set_context(stock_date_end=Date.today()): quantities = product.products_by_location( [each['warehouse']], [price_data.retrieve_the_code.id], with_childs=True) if quantities.values(): stock_level_warehouse = [ v for v in quantities.values() ][0] else: stock_level_warehouse = 0 with Transaction().set_context(stock_date_end=Date.today()): quantities = product.products_by_location( [each['freeze']], [price_data.retrieve_the_code.id], with_childs=True) if quantities.values(): stock_level_freeze = [v for v in quantities.values()][0] else: stock_level_freeze = 0 stock_level = stock_level_warehouse + stock_level_freeze party = price_data.retrieve_the_code.product_suppliers if party: party = party[0].party.name else: party = '' categories = [ i.id for i in price_data.retrieve_the_code.categories ] uom_category = UomCategory.search([('id', '=', categories[0])]) uom_name = uom_category[0].name if uom_name == u'西药': dict['drug_type'] = '00' if uom_name == u'中成药': dict['drug_type'] = '01' if uom_name == u'中草药': dict['drug_type'] = '02' if uom_name == u'颗粒中': dict['drug_type'] = '03' if uom_name == u'原料药': dict['drug_type'] = '04' if uom_name == u'敷药': dict['drug_type'] = '05' if uom_name == u'同位素': dict['drug_type'] = '07' dict['location'] = each['warehouse'] dict['code'] = price_data.product_code dict['product'] = price_data.product_name dict[ 'drug_specifications'] = price_data.drug_specifications dict['list_price'] = price_data.list_price dict['cost_price'] = price_data.cost_price dict['new_list_price'] = price_data.new_list_price dict['new_cost_price'] = price_data.new_cost_price dict['inventory'] = float(stock_level) dict['effective_date'] = today dict['party'] = party dict[ 'uom'] = price_data.retrieve_the_code.template.default_uom.id dict['price_profit_loss'] = decimal.Decimal( str(stock_level)) * ( decimal.Decimal(str(price_data.new_cost_price)) - price_data.cost_price) dict['price_list_profit_loss'] = decimal.Decimal( str(stock_level)) * ( decimal.Decimal(str(price_data.new_list_price)) - price_data.list_price) content.append(dict) price_content.create(content)
def create_using_ebay_data(cls, order_data): """ Create a sale from ebay data :param order_data: Order data from ebay Ref: http://developer.ebay.com/DevZone/XML/docs/\ Reference/eBay/GetOrders.html#Response :return: Active record of record created """ Party = Pool().get('party.party') Currency = Pool().get('currency.currency') SaleChannel = Pool().get('sale.channel') Uom = Pool().get('product.uom') ChannelException = Pool().get('channel.exception') ebay_channel = SaleChannel(Transaction().context['current_channel']) ebay_channel.validate_ebay_channel() currency, = Currency.search( [('code', '=', order_data['Total']['_currencyID'])], limit=1) # Transaction is similar to order lines # In the if..else below we fetch the first item from the array to # get the item which will be used to establish a relationship # between seller and buyer. transaction = order_data['TransactionArray']['Transaction'] if isinstance(transaction, dict): # If its a single line order, then the array will be dict item = transaction else: # In case of multi line orders, the transaction array will be # a list of dictionaries item = transaction[0] # Get an item ID so that ebay can establish a relationship between # seller and buyer. # eBay has a security feature which allows a seller # to fetch the information of a buyer via API only when there is # a seller-buyer relationship between both via some item. # If this item is not passed, then ebay would not return important # informations like eMail etc. item_id = item['Item']['ItemID'] party = Party.find_or_create_using_ebay_id(order_data['BuyerUserID'], item_id=item_id) party.add_phone_using_ebay_data(order_data['ShippingAddress']['Phone']) party_invoice_address = party_shipping_address = \ party.find_or_create_address_using_ebay_data( order_data['ShippingAddress'] ) unit, = Uom.search([('name', '=', 'Unit')]) sale_data = { 'reference': order_data['OrderID'], 'sale_date': dateutil.parser.parse(order_data['CreatedTime'].split()[0]).date(), 'party': party.id, 'currency': currency.id, 'invoice_address': party_invoice_address.id, 'shipment_address': party_shipping_address.id, 'ebay_order_id': order_data['OrderID'], 'lines': cls.get_item_line_data_using_ebay_data(order_data), 'channel': ebay_channel.id, } sale_data['lines'].append( cls.get_shipping_line_data_using_ebay_data(order_data)) # TODO: Handle Discounts # TODO: Handle Taxes sale, = cls.create([sale_data]) # Create channel exception if order total does not match if sale.total_amount != Decimal(order_data['Total']['value']): ChannelException.create([{ 'origin': '%s,%s' % (sale.__name__, sale.id), 'log': 'Order total does not match.', 'channel': sale.channel.id, }]) return sale # We import only completed orders, so we can confirm them all cls.quote([sale]) cls.confirm([sale]) # TODO: Process the order for invoice as the payment info is received return sale
def pos_add_product(self, product_ids, quantity, unit_price=None): """ Add product to sale from POS. This method is for POS, to add multiple products to cart in single call """ AccountTax = Pool().get('account.tax') SaleLine = Pool().get('sale.line') updated_lines = [] for product_id in product_ids: Transaction().set_context(product=product_id) try: if 'sale_line' in Transaction().context: sale_line = SaleLine( Transaction().context.get('sale_line')) else: sale_line, = SaleLine.search( self.pos_find_sale_line_domain()) except ValueError: sale_line = None delivery_mode = Transaction().context.get('delivery_mode', 'pick_up') if sale_line: values = { 'product': sale_line.product.id, '_parent_sale.currency': self.currency.id, '_parent_sale.party': self.party.id, '_parent_sale.price_list': (self.price_list.id if self.price_list else None), '_parent_sale.sale_date': self.sale_date, '_parent_sale.channel': self.channel, '_parent_sale.shipment_address': self.shipment_address, 'warehouse': self.warehouse, '_parent_sale.warehouse': self.warehouse, 'unit': sale_line.unit.id, 'quantity': quantity, 'type': 'line', 'delivery_mode': delivery_mode, } # Update the values by triggering an onchange which should # fill missing vals values.update(SaleLine(**values).on_change_quantity()) values.update(SaleLine(**values).on_change_delivery_mode()) values['unit_price'] = Decimal(unit_price) if unit_price else\ sale_line.unit_price new_values = {} for key, value in values.iteritems(): if '.' in key: continue if key == 'taxes': # Difficult to reach here unless taxes change when # quantities change. continue # pragma: no cover new_values[key] = value SaleLine.write([sale_line], new_values) else: values = { 'product': product_id, '_parent_sale.currency': self.currency.id, '_parent_sale.party': self.party.id, '_parent_sale.price_list': (self.price_list.id if self.price_list else None), '_parent_sale.sale_date': self.sale_date, '_parent_sale.channel': self.channel, '_parent_sale.shipment_address': self.shipment_address, 'warehouse': self.warehouse, '_parent_sale.warehouse': self.warehouse, 'sale': self.id, 'type': 'line', 'quantity': quantity, 'unit': None, 'description': None, 'delivery_mode': delivery_mode, } values.update(SaleLine(**values).on_change_product()) values.update(SaleLine(**values).on_change_quantity()) values.update(SaleLine(**values).on_change_delivery_mode()) new_values = {} for key, value in values.iteritems(): if '.' in key: continue if key == 'taxes': continue new_values[key] = value sale_line = SaleLine.create([new_values])[0] updated_lines.append(sale_line.id) if 'taxes' in values: sale_line.taxes = AccountTax.browse(values['taxes']) sale_line.save() # Now that the sale line is built, return a serializable response # which ensures that the client does not have to call again. res = { 'sale': self.serialize('pos'), 'updated_lines': updated_lines, } return res
def make_fedex_labels(self): """ Make labels for the given shipment :return: Tracking number as string """ Currency = Pool().get('currency.currency') Attachment = Pool().get('ir.attachment') Package = Pool().get('stock.package') Uom = Pool().get('product.uom') if self.state not in ('packed', 'done'): self.raise_user_error('invalid_state') if not self.carrier.carrier_cost_method == 'fedex': self.raise_user_error('wrong_carrier') if self.tracking_number: self.raise_user_error('tracking_number_already_present') fedex_credentials = self.carrier.get_fedex_credentials() ship_request = ProcessShipmentRequest(fedex_credentials) requested_shipment = ship_request.RequestedShipment requested_shipment.DropoffType = self.fedex_drop_off_type.value requested_shipment.ServiceType = self.fedex_service_type.value requested_shipment.PackagingType = self.fedex_packaging_type.value uom_pound, = Uom.search([('symbol', '=', 'lb')]) if len(self.packages) > 1: requested_shipment.TotalWeight.Units = 'LB' requested_shipment.TotalWeight.Value = Uom.compute_qty( self.weight_uom, self.weight, uom_pound ) # Shipper & Recipient requested_shipment.Shipper.AccountNumber = \ fedex_credentials.AccountNumber if not self.warehouse.address: self.raise_user_error('warehouse_address_required') self.warehouse.address.set_fedex_address(requested_shipment.Shipper) self.delivery_address.set_fedex_address(requested_shipment.Recipient) # Shipping Charges Payment shipping_charges = requested_shipment.ShippingChargesPayment shipping_charges.PaymentType = 'SENDER' shipping_charges.Payor.ResponsibleParty = requested_shipment.Shipper # Express Freight Detail fright_detail = requested_shipment.ExpressFreightDetail fright_detail.PackingListEnclosed = 1 # XXX fright_detail.ShippersLoadAndCount = 2 # XXX fright_detail.BookingConfirmationNumber = 'Ref-%s' % self.reference if self.is_international_shipping: # Customs Clearance Detail self.get_fedex_customs_details(ship_request) # Label Specification # Maybe make them as configurable items in later versions requested_shipment.LabelSpecification.LabelFormatType = 'COMMON2D' requested_shipment.LabelSpecification.ImageType = 'PNG' requested_shipment.LabelSpecification.LabelStockType = 'PAPER_4X6' requested_shipment.RateRequestTypes = ['ACCOUNT'] master_tracking_number = None for index, package in enumerate(self.packages, start=1): item = ship_request.get_element_from_type( 'RequestedPackageLineItem' ) item.SequenceNumber = index # TODO: some country needs item.ItemDescription item.Weight.Units = 'LB' item.Weight.Value = Uom.compute_qty( package.weight_uom, package.weight, uom_pound ) ship_request.RequestedShipment.RequestedPackageLineItems = [item] ship_request.RequestedShipment.PackageCount = len(self.packages) if master_tracking_number is not None: tracking_id = ship_request.get_element_from_type( 'TrackingId' ) tracking_id.TrackingNumber = master_tracking_number ship_request.RequestedShipment.MasterTrackingId = tracking_id try: response = ship_request.send_request(str(self.id)) except RequestError, error: self.raise_user_error('error_label', error_args=(error,)) package_details = response.CompletedShipmentDetail.CompletedPackageDetails # noqa tracking_number = package_details[0].TrackingIds[0].TrackingNumber if self.packages.index(package) == 0: master_tracking_number = tracking_number Package.write([package], { 'tracking_number': tracking_number, }) for id, image in enumerate(package_details[0].Label.Parts): Attachment.create([{ 'name': "%s_%s_Fedex.png" % (tracking_number, id), 'type': 'data', 'data': buffer(base64.decodestring(image.Image)), 'resource': '%s,%s' % (self.__name__, self.id) }])
def change_loan_installment(cls, records, values): """Change number of installments pending for loan""" cursor = Transaction().connection.cursor() LoanLine = Pool().get('computer.loan.line') amount = 0 for loan in records: cursor.execute('SELECT sum(amount) FROM computer_loan_line \ WHERE loan=%s AND status = %s', (loan.id, 'done')) total_amount = cursor.fetchone() if total_amount[0]: amount_value = min(loan.amount_required, loan.price) reschedule = amount_value - total_amount[0] cls.write(records, {'payout': total_amount[0], 'reschedule': reschedule}) amount = (reschedule/values['installment_no']) else: if 'installment_no' in values.keys(): amount_value = min(loan.amount_required, loan.price) amount = (amount_value/values['installment_no']) elif 'amount_required' in values.keys(): amount_value = min(values['amount_required'], loan.price) amount = (amount_value/loan.installment_no) elif 'price' in values.keys(): amount_value = min(loan.amount_required, values['price']) amount = (amount_value/loan.installment_no) elif 'installment_no' in values.keys() and 'price' in values.keys() and 'amount_required' in values.keys(): amount_value = min( values['amount_required'], values['price']) amount = (amount_value/values['installment_no']) elif 'installment_no' in values.keys() and 'price' in values.keys(): amount_value = min(loan.amount_required, values['price']) amount = (amount_value/values['installment_no']) elif 'installment_no' in values.keys() and 'amount_required' in values.keys(): amount_value = min(values['amount_required'], loan.price) amount = (amount_value/values['installment_no']) elif 'price' in values.keys() and 'amount_required' in values.keys(): amount_value = min( values['amount_required'], values['price']) amount = (amount_value/loan.installment_no) cursor.execute('delete FROM computer_loan_line WHERE loan=%s \ AND status != %s', (loan.id, 'done')) count = 0 installment_no = 0 if 'installment_no' in values.keys(): installment_no = values['installment_no'] else: installment_no = loan.installment_no for line in range(1, int(installment_no)+1): mydate = datetime.now().month if total_amount[0]: month = mydate else: month = mydate - 1 if month+line > 12: count += 1 if count > 12: count = 1 months = datetime(1900, count, 1).date().strftime('%B') else: months = datetime(1900, month+line, 1).date().strftime('%B') vals = { 'month': months, 'amount': amount, 'status': 'pending', 'loan': loan.id } line = LoanLine.create([vals])
def do_create_(self, action): Product = Pool().get('product.product') ProductQuantity = Pool().get('product_quantity') Purchase = Pool().get('purchase.purchase') Company = Pool().get('company.company') Date = Pool().get('ir.date') Move = Pool().get('stock.move') Lot = Pool().get('stock.lot') today = str(Date.today()) Config = Pool().get('purchase.configuration') config = Config(1) company = Company.search([('id', '=', Transaction().context['company']) ]) currency = company[0].currency Invoice = Pool().get('account.invoice') ShipmentIn = Pool().get('stock.shipment.in') PurchaseBills = Pool().get('purchase_bills') ShipmentInReturn = Pool().get('stock.shipment.in.return') data = {} for state_name, state in self.states.iteritems(): if isinstance(state, StateView): data[state_name] = getattr(self, state_name)._default_values message = '' for each in data['start']['stock_return_lines']: if each['ensure'] == True and data['start'][ 'order_category'] == 'return': shipmentinreturn = ShipmentInReturn.search([ ('id', '=', each['return_id']), ('state', '!=', 'done') ]) if not shipmentinreturn: message = u'该单号已被处理,请退出后重新查询。' continue whether_move = Move.assign_try( [Move(shipmentinreturn[0].moves[0].id)], grouping=('product', 'lot')) if not whether_move: message += shipmentinreturn[0].moves[ 0].product.code + shipmentinreturn[0].moves[ 0].product.name + u'-批次:' + Lot( shipmentinreturn[0].moves[0].lot ).number + u'实际数量有变,请删除该行项目后重新输入\n' continue ShipmentInReturn.assign(shipmentinreturn) ShipmentInReturn.done(shipmentinreturn) if each['ensure'] == True and data['start'][ 'order_category'] == 'purchase': purchase_bills = PurchaseBills.search([('id', '=', each['purchase_id'])]) purchase = Purchase.search([ ('number', '=', purchase_bills[0].order_code) ]) # ,('state', '!=', 'processing') if not purchase: message = u'该单号已被处理,请退出后重新查询。' continue PurchaseBills.write(purchase_bills, {'state': 'done'}) Purchase.quote(purchase) Purchase.confirm(purchase) Purchase.process(purchase) moves = Move.search([ ('product', '=', purchase_bills[0].product.id), ('purchase', '=', purchase_bills[0].order_code), ('state', '=', 'draft') ]) Move.write( moves, { 'outgoing_audit': '02', 'lot': purchase_bills[0].lot.id, 'quantity': purchase_bills[0].shipment_quantity, 'move_type': '101' }) lv = {} if moves != []: lv['incoming_moves'] = [['add', [moves[0].id]]] lv['reference'] = '' lv['planned_date'] = today lv['return_shipment'] = purchase_bills[0].return_shipment lv['company'] = Transaction().context.get('company') lv['effective_date'] = None lv['cause'] = '00' lv['warehouse'] = config.warehouse.id lv['supplier'] = purchase_bills[0].party.id lv['inventory_moves'] = [] shipments = ShipmentIn.create([lv]) shipment = ShipmentIn.search([('id', '=', shipments[0].id)]) ShipmentIn.receive(shipment) ShipmentIn.done(shipment) invoices = Invoice.search([ ('state', '=', 'draft'), ('id', 'in', [ ids.id for ids in [i for i in [k.invoices for k in purchase]][0] ]) ]) Invoice.write( invoices, { 'invoice_date': purchase_bills[0].purchase_create_time, 'reference': purchase_bills[0].invoice_code, 'description': purchase_bills[0].return_shipment.number, 'amount': purchase_bills[0].amount_of_real_pay }) Invoice.validate_invoice(invoices) Invoice.validate_invoice(invoices) product_quantities = ProductQuantity.search( [('product', '=', purchase_bills[0].product.id)], order=[["sequence", "ASC"]]) move = { u'comment': u'', u'outgoing_audit': u'00', u'product': purchase_bills[0].product.id, u'from_location': config.warehouse.storage_location.id, u'invoice_lines': [], u'starts': u'05', u'move_type': '000', u'company': Transaction().context.get('company'), u'unit_price': purchase_bills[0].product.cost_price, u'currency': currency.id, u'reason': '00', u'lot': purchase_bills[0].lot.id, u'planned_date': today, u'uom': purchase_bills[0].product.default_uom.id, u'origin': None, # u'sale.line,-1', } move_quantity = purchase_bills[0].shipment_quantity for product_quantity in product_quantities: with Transaction().set_context( stock_date_end=Date.today()): # 查看具体库下面的批次对应的数量 warehouse_quant = Product.products_by_location( [product_quantity.location.id], [purchase_bills[0].product.id], with_childs=True) move['to_location'] = product_quantity.location.id warehouse_quantity = warehouse_quant[( product_quantity.location.id, purchase_bills[0].product.id)] if product_quantity.quantity - warehouse_quantity >= move_quantity: move['quantity'] = move_quantity if move['quantity'] < 0: self.raise_user_error(u'当前库存已超过最大库存!') moves = Move.create([move]) Move.do(moves) break else: move[ 'quantity'] = product_quantity.quantity - warehouse_quantity if move['quantity'] < 0: self.raise_user_error(u'当前库存已超过最大库存!') move_quantity = move_quantity + warehouse_quantity - product_quantity.quantity moves = Move.create([move]) Move.do(moves) if message: self.raise_user_error(message) return action, {}
def analizarDatos(self): #central cursor0 = Transaction().connection.cursor() st0 = "select central \ from oci_orden_trabajo \ group by 1" cursor0.execute(st0) for data in cursor0.fetchall(): Central = Pool().get('oci.central.telecom') central = Central.search([('name', '=', str(data[0]))]) if not central: central, = Central.create([{'name': str(data[0])}]) else: central = central[0] #ARMARIOS cursor1 = Transaction().connection.cursor() st1 = "select armario, armario_nombre_calle, armario_altura, armario_nombre_edificio, armario_manzana, central \ from oci_orden_trabajo \ where state = 'pendiente' \ and armario_nombre_calle != 'null' \ and central = '%s'\ group by 1,2,3,4,5,6 \ order by 1" % (central.name) cursor1.execute(st1) for data1 in cursor1.fetchall(): Armario = Pool().get('oci.armario') armario = Armario.search([('name', '=', data1[0]), ('central', '=', central.id)]) if not armario: armario, = Armario.create([{ 'name': str(data1[0]), 'calle': str(data1[1]), 'altura': str(data1[2]), 'nombre_edificio': str(data1[3]), 'manzana': str(data1[4]), 'central': central.id, }]) else: armario = armario[0] #TERMINALES cursor2 = Transaction().connection.cursor() st2 = "select terminal, terminal_nombre_calle, terminal_altura, terminal_nombre_edificio, terminal_manzana \ from oci_orden_trabajo \ where state = 'pendiente' \ and armario = '%s' \ group by 1,2,3,4,5 \ order by 1" % (armario.name) cursor2.execute(st2) terminales = [] for data2 in cursor2.fetchall(): Terminal = Pool().get('oci.terminal') terminal = Terminal.search([('name', '=', data2[0]), ('armario', '=', armario.id)]) if not terminal: terminales.append({ 'name': str(data2[0]), 'calle': str(data2[1]), 'altura': str(data2[2]), 'nombre_edificio': str(data2[3]), 'manzana': str(data2[4]), 'armario': armario.id, }) Terminal.create(terminales)
def test_totp_get(self): TOTPLogin = Pool().get('res.user.login.totp') record, = TOTPLogin.create([{'user_id': 1}]) totp_login = TOTPLogin.get(1) self.assertEqual(record, totp_login)
def test_create_required_without_value(self): "Test create time required without value" Time = Pool().get('test.time_required') with self.assertRaises(UserError): Time.create([{}])
def do_create_(self, action): Date = Pool().get('ir.date') today = Date.today() UserId = Pool().get('hrp_internal_delivery.test_straight') to_location_id = UserId.get_user_id() Config = Pool().get('purchase.configuration') config = Config(1) # 库存地配置 internal = Pool().get('stock.shipment.internal') new_return = Pool().get('hrp_new_product.new_return') Product = Pool().get('product.product') data = {} for state_name, state in self.states.iteritems(): if isinstance(state, StateView): data[state_name] = getattr(self, state_name)._default_values lv = {} Move = data['start']['moves'] MOVE = Pool().get('hrp_new_product.new_return') UserId = Pool().get('hrp_internal_delivery.test_straight') from_location_id = UserId.get_user_id() list_now = [] scrap = [ ('examine', '=', '02'), ('from_location', '=', from_location_id), ] if data['start']['drug_type'] == '06': pass else: scrap.append(('drug_type', '=', data['start']['drug_type'])) mmm = MOVE.search(scrap) for i in mmm: dict = {} dict['product'] = i.product.id dict['return_quantity'] = i.can_return_quantity list_now.append(dict) now_data = sorted(list_now, key=lambda x: (x['product'], x['return_quantity']), reverse=False) UserId = Pool().get('hrp_internal_delivery.test_straight') list_compare = [] for each in Move: dict = {} dict['product'] = each['product'] dict['return_quantity'] = each['return_quantity'] list_compare.append(dict) # list_compare = UserId.get_default_moves_now() before_data = sorted(list_compare, key=lambda x: (x['product'], x['return_quantity']), reverse=False) product_id = [] for each in before_data: product_id.append(each['product']) a = {} for p_id in product_id: if product_id.count(p_id) > 1: a[p_id] = product_id.count(p_id) key_value = a.keys() productid = [] now_list = [] for each_ in before_data: if each_['product'] in key_value: dict = {} dict[each_['product']] = each_['return_quantity'] productid.append(dict) now_list.append(each_) expected = [l for l in before_data if l not in now_list] for pro in key_value: number = 0 dict_ = {} for i in productid: try: number += i[pro] except: pass dict_['product'] = pro dict_['return_quantity'] = number expected.append(dict_) expected_data = sorted(expected, key=lambda x: (x['product'], x['return_quantity']), reverse=False) if expected_data == now_data: list = [] for each in Move: get_apply_number = UserId.get_apply_number(to_location_id) lv['number'] = get_apply_number lv['starts'] = '01' lv['to_location'] = config.transfers.id # 中转库存地 lv['from_location'] = each['to_location'] lv['company'] = 1 # data['start']['company'] lv['state'] = data['start']['state'] lv['place_of_service'] = config.return_of.id # 到达库存地(中心药库冻结区) lv['drug_starts'] = data['start']['drug_type'] dict = {} if each['reason'] == '00': pass else: dict['origin'] = None dict['starts'] = data['start']['actives'] dict['product'] = each['product'] dict['planned_date'] = data['start']['planned_date'] dict['from_location'] = each['to_location'] dict['to_location'] = config.transfers.id # 中转库存地 dict['is_direct_sending'] = each['is_direct_sending'] dict['company'] = 1 dict['reason'] = each['reason'] dict['comment'] = each['comment'] dict['invoice_lines'] = () dict['unit_price'] = None # each['unit_price'] dict['lot'] = each['lot'] dict['uom'] = each['uom'] dict['quantity'] = each['return_quantity'] dict['real_number'] = each['return_quantity'] with Transaction().set_context( stock_date_end=today, stock_assign=True): # 查看具体库下面的批次对应的数量 warehouse_quant = Product.products_by_location( [each['to_location']], [each['product']], [each['lot']], grouping=('product', 'lot')) for key, value in warehouse_quant.items(): if value > each['return_quantity']: pass else: return self.raise_user_error( u'%s,数量不满足,请联系采购确认可退数量', each['product_name']) cost_prices = Product.search([('id', '=', each['product']) ])[0].cost_price list_prices = Product.search([('id', '=', each['product']) ])[0].list_price list_ = decimal.Decimal( str( float(list_prices * decimal.Decimal( str(each['return_quantity']))))) # 批发总价 cost_ = decimal.Decimal( str( float(cost_prices * decimal.Decimal( str(each['return_quantity']))))) # 零售总价 list_price = decimal.Decimal(-list_).quantize( decimal.Decimal('0.00')) cost_price = decimal.Decimal(-cost_).quantize( decimal.Decimal('0.00')) dict['list_price'] = list_price dict['cost_price'] = cost_price list.append(dict) lv['moves'] = [['create', list]] NewReturn = new_return.search([ ('product', '=', each['product']), ('from_location', '=', each['from_location']), ]) if NewReturn: write_dict = {} write_dict['examine'] = '01' write_dict['can_return_quantity'] = None new_return.write(NewReturn, write_dict) else: return self.raise_user_error(u'数据有所更新,请您退出该界面重新进行操作') internal.create([lv]) Internal = internal.search([ ('from_location', '=', data['start']['moves'][0]['to_location']) ]) internal.wait(Internal) internal.assign(Internal) internal.done(Internal) return action, {}