def create_and_upload_pdfs(self, delete_original=True): ack_filename, production_filename, label_filename, qc_filename = self.create_pdfs() ack_key = "acknowledgement/{0}/Acknowledgement-{0}.pdf".format(self.id) #confirmation_key = "acknowledgement/{0}/Confirmation-{0}.pdf".format(self.id) production_key = "acknowledgement/{0}/Production-{0}.pdf".format(self.id) label_key = "acknowledgement/{0}/Label-{0}.pdf".format(self.id) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack_filename, ack_key, bucket, delete_original=delete_original) #confirmation_pdf = S3Object.create(confirmation_filename, confirmation_key, bucket, delete_original=delete_original) prod_pdf = S3Object.create(production_filename, production_key, bucket, delete_original=delete_original) label_pdf = S3Object.create(label_filename, label_key, bucket, delete_original=delete_original) # Create QC key and upload and add to files try: qc_key = "acknowledgment/{0}/Quality_Control-{0}.pdf".format(self.id) qc_pdf = S3Object.create(qc_filename, qc_key, bucket, delete_original=delete_original) # Add qc file to the File.objects.create(file=qc_pdf, acknowledgement=self) except Exception as e: logger.warn(e) # Save references for files self.label_pdf = label_pdf self.acknowledgement_pdf = ack_pdf #self.confirmation_pdf = confirmation_pdf self.production_pdf = prod_pdf self.save()
def update(self, data=None, employee=None): """"Updates the acknowledgement Updates the acknowledgement with the new data and creates a new pdf for acknowledgement and production """ self.current_employee = employee try: self.delivery_date = data["delivery_date"] self.save() except: pass self.calculate_totals() ack_filename, production_filename = self.create_pdfs() ack_key = "acknowledgement/Acknowledgement-{0}-revision.pdf".format(self.id) production_key = "acknowledgement/Production-{0}-revision.pdf".format(self.id) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack_filename, ack_key, bucket) prod_pdf = S3Object.create(production_filename, production_key, bucket) self.acknowledgement_pdf = ack_pdf self.production_pdf = prod_pdf self.save()
def update(self, data=None, employee=None): """"Updates the acknowledgement Updates the acknowledgement with the new data and creates a new pdf for acknowledgement and production """ self.current_employee = employee try: self.delivery_date = data["delivery_date"] self.save() except: pass self.calculate_totals() ack_filename, production_filename = self.create_pdfs() ack_key = "acknowledgement/Acknowledgement-{0}-revision.pdf".format( self.document_number) production_key = "acknowledgement/Production-{0}-revision.pdf".format( self.document_number) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack_filename, ack_key, bucket) prod_pdf = S3Object.create(production_filename, production_key, bucket) self.acknowledgement_pdf = ack_pdf self.production_pdf = prod_pdf self.save()
def create(cls, user, **kwargs): """Creates the acknowledgement This method accept data to set and then creates an accompanying PDF and logs the event. A User Object is required to authorize certain data """ acknowledgement = cls() # Get Customer and create in TRCloud if necessary acknowledgement.customer = Customer.objects.get(id=kwargs['customer']['id']) try: if not acknowledgement.customer.trcloud_id == 0: acknowledgement.customer.create_in_trcloud() except Exception as e: logger.warn(e) acknowledgement.employee = user acknowledgement.delivery_date = dateutil.parser.parse(kwargs['delivery_date']) acknowledgement.status = 'ACKNOWLEDGED' try: acknowledgement.vat = int(kwargs["vat"]) except KeyError: acknowledgement.vat = 0 try: acknowledgement.po_id = kwargs["po_id"] except KeyError: raise AttributeError("Missing Purchase Order number.") try: acknowledgement.remarks = kwargs["remarks"] except KeyError: pass #Create the products without saving acknowledgement.items = [Item.create(acknowledgement=acknowledgement, commit=False, **product_data) for product_data in kwargs['products']] acknowledgement.calculate_totals(acknowledgement.items) #Save the ack and by overriden method, the items acknowledgement.save() #Create the order PDFs ack, production = acknowledgement._create_pdfs() ack_key = "acknowledgement/Acknowledgement-{0}.pdf".format(acknowledgement.id) production_key = "acknowledgement/Production-{0}.pdf".format(acknowledgement.id) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack, ack_key, bucket, encrypt_key=True) prod_pdf = S3Object.create(production, production_key, bucket, encrypt_key=True) acknowledgement.acknowledgement_pdf = ack_pdf acknowledgement.production_pdf = prod_pdf acknowledgement.original_acknowledgement_pdf = ack_pdf #Save Ack with pdf data acknowledgement.save() return acknowledgement
def create_and_upload_pdf(self): """ Creates a pdf and uploads it to the S3 service """ filename, filename2 = self.create_pdf() key = "purchase_order/PO-{0}.pdf".format(self.id) self.pdf = S3Object.create(filename, key, 'document.dellarobbiathailand.com') auto_key = "purchase_order/PO-{0}-auto.pdf".format(self.id) self.auto_print_pdf = S3Object.create(filename2, auto_key, 'document.dellarobbiathailand.com') self.save()
def acknowledgement_file(request): try: file = request.FILES['image'] except Exception: file = request.FILES['file'] filename = file.name #Save file with open(filename, 'wb+' ) as destination: for chunk in file.chunks(): destination.write(chunk) credentials = request.user.aws_credentials key = credentials.access_key_id secret = credentials.secret_access_key obj = S3Object.create(filename, u"acknowledgement/files/{0}".format(filename), u"media.dellarobbiathailand.com", key, secret) response = HttpResponse(json.dumps({'id': obj.id, 'filename': filename, 'type': filename.split('.')[-1], 'url': obj.generate_url(key, secret)}), content_type="application/json") response.status_code = 201 return response
def product_image(request): if request.method == "POST": credentials = request.user.aws_credentials key = credentials.access_key_id secret = credentials.secret_access_key try: filename = request.FILES["file"].name except MultiValueDictKeyError: filename = request.FILES["image"].name filename = save_upload(request, filename=filename) logger.debug(filename) obj = S3Object.create( filename, "acknowledgement/item/image/{0}_{1}".format(time.time(), filename.split("/")[-1]), "media.dellarobbiathailand.com", key, secret, ) logger.debug(obj.__dict__) response = HttpResponse( json.dumps({"id": obj.id, "url": obj.generate_url(key, secret)}), content_type="application/json" ) response.status_code = 201 return response
def invoice_item_image(request, ack_id=None): if request.method.lower() == "post": try: credentials = request.user.aws_credentials key = credentials.access_key_id secret = credentials.secret_access_key except AttributeError as e: logger.error(e) key = '' secret = '' filename = save_upload(request) if ack_id: key = u"invoice/{0}/item/image/{1}".format(ack_id, filename.split('/')[-1]) else: key = u"invoice/item/image/{0}".format(filename.split('/')[-1]) obj = S3Object.create(filename, key, 'media.dellarobbiathailand.com', key, secret) serializer = S3ObjectSerializer(obj) response = HttpResponse(JSONRenderer().render(serializer.data), content_type="application/json") response.status_code = 201 return response # If any method other than POST else: response = HttpResponse('{"message": "Not Allowed"}', content_type='application/json; charset=utf-8') response.status_code = 405 return response
def acknowledgement_file(request): try: file = request.FILES['image'] except MultiValueDictKeyError: file = request.FILES['file'] filename = file.name #Save file with open(filename, 'wb+' ) as destination: for chunk in file.chunks(): destination.write(chunk) obj = S3Object.create(filename, "acknowledgement/files/{0}".format(filename), "media.dellarobbiathailand.com") response = HttpResponse(json.dumps({'id': obj.id, 'filename': filename, 'type': filename.split('.')[-1], 'url': obj.generate_url()}), content_type="application/json") response.status_code = 201 return response
def dehydrate(self, bundle): """ Implements the dehydrate method to manipulate data before it is returned to the client """ #Checks if the country is set bundle = self._set_country(bundle) #Adds the quantity to the data field bundle.data['quantity'] = bundle.obj.quantity #Replaces custom-type with type after supply creation if "custom-type" in bundle.data: bundle.data['type'] = bundle.obj.type del bundle.data['custom-type'] #Dehydrates the suppliers information if #requesting a single resource, if creating a new resource #or updating a single resource if re.search("api/v1/supply/(w+\-)?\d+", bundle.request.path) or bundle.request.method == 'POST' or bundle.request.method == 'PUT': bundle.data['suppliers'] = [self.dehydrate_supplier(bundle, supplier) for supplier in bundle.obj.suppliers.all()] if not bundle.obj.sticker: sticker_page = StickerPage(code="DRS-{0}".format(bundle.obj.id), description=bundle.obj.description) filename = sticker_page.create("DRS-{0}".format(bundle.obj.id)) stickers = S3Object.create(filename, "supplies/stickers/{0}".format(filename), 'document.dellarobbiathailand.com', encrypt_key=True) bundle.obj.sticker = stickers bundle.obj.save() bundle.data['sticker'] = {'url':bundle.obj.sticker.generate_url()} #If getting a list else: bundle.data['suppliers'] = [{'name': supplier.name, 'id': supplier.id} for supplier in bundle.obj.suppliers.all()] #Merging product data from a supplier with the resource #if gettings supplies for a single supplier if bundle.request.GET.has_key('supplier_id'): #Set the supply's supplier to using #objects internals to get info bundle.obj.supplier = Supplier.objects.get(pk=bundle.request.GET.get('supplier_id')) bundle.data.update({'purchasing_units': bundle.obj.purchasing_units, 'cost': bundle.obj.cost, 'reference': bundle.obj.reference, 'lead_time': bundle.obj.lead_time, 'upc': bundle.obj.upc}) if bundle.obj.image: try: bundle.data['image'] = {'id': bundle.obj.image.id, 'url': bundle.obj.image.generate_url(3600)} except (AttributeError, KeyError) as e: logger.warn(e) logger.debug(bundle.data) return bundle
def create_and_upload_pdf(self): """ Creates a pdf and uploads it to the S3 service """ filename, filename2 = self.create_pdf() key = "purchase_order/{0}/PO-{0}.pdf".format(self.id) self.pdf = S3Object.create(filename, key, 'document.dellarobbiathailand.com') auto_key = "purchase_order/{0}/PO-{0}-auto.pdf".format(self.id) self.auto_print_pdf = S3Object.create(filename2, auto_key, 'document.dellarobbiathailand.com') self.save()
def create_and_upload_pdfs(self, delete_original=True): ack_filename, production_filename, label_filename, qc_filename = self.create_pdfs( ) ack_key = "acknowledgement/{0}/Acknowledgement-{0}.pdf".format( self.document_number) #confirmation_key = "acknowledgement/{0}/Confirmation-{0}.pdf".format(self.document_number) production_key = "acknowledgement/{0}/Production-{0}.pdf".format( self.document_number) label_key = "acknowledgement/{0}/Label-{0}.pdf".format( self.document_number) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack_filename, ack_key, bucket, delete_original=delete_original) #confirmation_pdf = S3Object.create(confirmation_filename, confirmation_key, bucket, delete_original=delete_original) prod_pdf = S3Object.create(production_filename, production_key, bucket, delete_original=delete_original) label_pdf = S3Object.create(label_filename, label_key, bucket, delete_original=delete_original) # Create QC key and upload and add to files try: qc_key = "acknowledgment/{0}/Quality_Control-{0}.pdf".format( self.document_number) qc_pdf = S3Object.create(qc_filename, qc_key, bucket, delete_original=delete_original) # Add qc file to the File.objects.create(file=qc_pdf, acknowledgement=self) except Exception as e: logger.warn(e) # Save references for files self.label_pdf = label_pdf self.acknowledgement_pdf = ack_pdf #self.confirmation_pdf = confirmation_pdf self.production_pdf = prod_pdf self.save()
def create_and_upload_pdfs(self, delete_original=True): ack_filename, production_filename, label_filename = self.create_pdfs() ack_key = "acknowledgement/Acknowledgement-{0}.pdf".format(self.id) #confirmation_key = "acknowledgement/Confirmation-{0}.pdf".format(self.id) production_key = "acknowledgement/Production-{0}.pdf".format(self.id) label_key = "acknowledgement/Label-{0}.pdf".format(self.id) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack_filename, ack_key, bucket, delete_original=delete_original) #confirmation_pdf = S3Object.create(confirmation_filename, confirmation_key, bucket, delete_original=delete_original) prod_pdf = S3Object.create(production_filename, production_key, bucket, delete_original=delete_original) #label_pdf = S3Object.create(label_filename, label_key, bucket, delete_original=delete_original) #self.label_pdf = label_pdf self.acknowledgement_pdf = ack_pdf #self.confirmation_pdf = confirmation_pdf self.production_pdf = prod_pdf self.save()
def create_and_upload_pdf(self, delete_original=True): ack_filename = self.create_pdf() ack_key = "estimate/{0}/Quotation-{0}.pdf".format(self.id) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack_filename, ack_key, bucket, delete_original=delete_original) self.pdf = ack_pdf self.save()
def acknowledgement_item_image(request): if request.method == "POST": filename = save_upload(request) obj = S3Object.create(filename, "acknowledgement/item/image/{0}.jpg".format(time.time()), 'media.dellarobbiathailand.com') response = HttpResponse(json.dumps({'id': obj.id, 'url': obj.generate_url()}), content_type="application/json") response.status_code = 201 return response
def create_and_upload_pdf(self, delete_original=True): invoice_filename = self.create_pdf() invoice_key = "invoice/{0}/Invoice-{0}.pdf".format(self.id) bucket = "document.dellarobbiathailand.com" invoice_pdf = S3Object.create(invoice_filename, invoice_key, bucket, delete_original=delete_original) # Save references for files self.pdf = invoice_pdf self.save()
def setUp(self): self.equipment = Equipment(**base_equipment) self.equipment.save() self.employee = Employee(first_name="John", last_name="Smith", department="Carpentry") self.employee.save() self.image = S3Object() self.image.save()
def setUp(self): """ Sets up for tests """ customer_data = copy.deepcopy(base_customer) del customer_data['addresses'] self.customer = Customer.objects.create(**customer_data) self.customer.save() self.project = Project.objects.create(codename="Ladawan") self.room = Room.objects.create(description="Living Room", project=self.project) self.file1 = S3Object(key='test', bucket='test') self.file1.save()
def create_and_upload_pdf(self): """ Creates a pdf of the shipping manifest and uploads it to the S3 service """ filename = self.create_pdf() #Upload and return the url self.pdf = S3Object.create(filename, "shipping/Shipping-{0}.pdf".format(self.id), 'document.dellarobbiathailand.com') self.save() return self.pdf
def create_and_upload_shipping_label(self): """ Creates a shipping Label pdf and uploads to S3 service """ products = self.items.all().order_by('id') label_pdf = ShippingLabelPDF(customer=self.customer, ack=self, products=products) label_filename = label_pdf.create() label_key = "acknowledgement/Label-{0}.pdf".format(self.id) bucket = "document.dellarobbiathailand.com" label_pdf = S3Object.create(label_filename, label_key, bucket) self.label_pdf = label_pdf self.save()
def create_stickers(self, key, secret): sticker_page = StickerPage(code="DRS-{0}".format(self.id), description=self.description) filename = sticker_page.create() stickers = S3Object.create(filename, "supplies/stickers/{0}".format(filename), 'document.dellarobbiathailand.com', key, secret, encrypt_key=True, ) self.sticker = stickers self.save()
def create_and_upload_pdf(self, delete_original=True): receipt_filename = self.create_pdf() receipt_key = "receipt/{0}/Receipt-{0}.pdf".format(self.id) bucket = "document.dellarobbiathailand.com" receipt_pdf = S3Object.create(receipt_filename, receipt_key, bucket, delete_original=delete_original) # Save references for files self.pdf = receipt_pdf self.save()
def create_stickers(self, key, secret): sticker_page = StickerPage(code="DRS-{0}".format(self.id), description=self.description) filename = sticker_page.create() stickers = S3Object.create( filename, "supplies/stickers/{0}".format(filename), 'document.dellarobbiathailand.com', key, secret, encrypt_key=True, ) self.sticker = stickers self.save()
def process_image(self, request, **kwargs): """ Receives an image and processes it """ filename = save_upload(request) image = S3Object.create(filename, "user/image/{0}.jpg".format(time.time()), "media.dellarobbiathailand.com") #set Url, key and bucket data = {'url': image.generate_url(), "id": image.id, 'key': image.key, 'bucket': image.bucket} return self.create_response(request, data)
def create_and_upload_shipping_label(self): """ Creates a shipping Label pdf and uploads to S3 service """ products = self.items.all().order_by('id') label_pdf = ShippingLabelPDF(customer=self.customer, ack=self, products=products) label_filename = label_pdf.create() label_key = "acknowledgement/Label-{0}.pdf".format( self.document_number) bucket = "document.dellarobbiathailand.com" label_pdf = S3Object.create(label_filename, label_key, bucket) self.label_pdf = label_pdf self.save()
def create(cls, user=None, override_id=False, **kwargs): data = kwargs shipping = cls() if override_id and 'id' in kwargs: shipping.id = kwargs['id'] #Set the data from the shippping shipping.acknowledgement = Acknowledgement.objects.get( id=data["acknowledgement"]['id']) try: shipping.customer = Customer.objects.get(id=data['customer']['id']) except KeyError: shipping.customer = shipping.acknowledgement.customer shipping.employee = user try: shipping.delivery_date = data["delivery_date"] except KeyError: shipping.delivery_date = shipping.acknowledgement.delivery_date if "comments" in data: shipping.comments = data["comments"] else: shipping.comments = shipping.acknowledgement.remarks shipping.save() try: shipping.process_items(kwargs['items']) except: shipping.process_items([{ 'id': item.id } for item in shipping.acknowledgement.items.all()]) #shipping.update_acknowledgement_data() #Initialize and create pdf pdf = ShippingPDF(customer=shipping.customer, shipping=shipping, products=shipping.item_set.all().order_by('id')) shipping_filename = pdf.create() #Upload and return the url shipping.pdf = S3Object.create( shipping_filename, "shipping/Shipping-{0}.pdf".format(shipping.id), 'document.dellarobbiathailand.com') shipping.save() return shipping
def process_image(self, request, **kwargs): """ Receives an image and processes it """ filename = save_upload(request) image = S3Object.create(filename, "user/image/{0}.jpg".format(time.time()), "media.dellarobbiathailand.com") #set Url, key and bucket data = { 'url': image.generate_url(), "id": image.id, 'key': image.key, 'bucket': image.bucket } return self.create_response(request, data)
def acknowledgement_item_image(request): if request.method == "POST": credentials = request.user.aws_credentials key = credentials.access_key_id secret = credentials.secret_access_key filename = save_upload(request) obj = S3Object.create(filename, "acknowledgement/item/image/{0}.jpg".format(time.time()), 'media.dellarobbiathailand.com', key, secret) response = HttpResponse(json.dumps({'id': obj.id, 'url': obj.generate_url(key, secret)}), content_type="application/json") response.status_code = 201 return response
def create(cls, user=None, override_id=False, **kwargs): data = kwargs shipping = cls() if override_id and 'id' in kwargs: shipping.id = kwargs['id'] #Set the data from the shippping shipping.acknowledgement = Acknowledgement.objects.get(id=data["acknowledgement"]['id']) try: shipping.customer = Customer.objects.get(id=data['customer']['id']) except KeyError: shipping.customer = shipping.acknowledgement.customer shipping.employee = user try: shipping.delivery_date = data["delivery_date"] except KeyError: shipping.delivery_date = shipping.acknowledgement.delivery_date if "comments" in data: shipping.comments = data["comments"] else: shipping.comments = shipping.acknowledgement.remarks shipping.save() try: shipping.process_items(kwargs['items']) except: shipping.process_items([{'id':item.id} for item in shipping.acknowledgement.items.all()]) #shipping.update_acknowledgement_data() #Initialize and create pdf pdf = ShippingPDF(customer=shipping.customer, shipping=shipping, products=shipping.item_set.all().order_by('id')) shipping_filename = pdf.create() #Upload and return the url shipping.pdf = S3Object.create(shipping_filename, "shipping/Shipping-{0}.pdf".format(shipping.id), 'document.dellarobbiathailand.com') shipping.save() return shipping
def product_image(request): if request.method == "POST": try: filename = request.FILES['file'].name except MultiValueDictKeyError: filename = request.FILES['image'].name filename = save_upload(request, filename=filename) obj = S3Object.create(filename, "acknowledgement/item/image/{0}_{1}".format(time.time(), filename.split('/')[-1]), 'media.dellarobbiathailand.com') response = HttpResponse(json.dumps({'id': obj.id, 'url': obj.generate_url(), 'key': obj.key, 'bucket':obj.bucket}), content_type="application/json") response.status_code = 201 return response
def estimate_file(request, q_id=None): if request.method == "POST": try: credentials = request.user.aws_credentials key = credentials.access_key_id secret = credentials.secret_access_key except AttributeError as e: logger.error(e) key = '' secret = '' filename = save_upload(request) if q_id: key = u"estimate/{0}/files/{1}".format(q_id, filename.split('/')[-1]) else: key = u"estimate/files/{0}".format(filename.split('/')[-1]) obj = S3Object.create(filename, key, u"document.dellarobbiathailand.com", key, secret) serializer = S3ObjectSerializer(obj) response = HttpResponse(JSONRenderer().render(serializer.data), content_type="application/json") response.status_code = 201 return response # If any method other than POST else: response = HttpResponse('{"message": "Not Allowed"}', content_type='application/json; charset=utf-8') response.status_code = 405 return response
def po_file(request, po_id=None): if request.method == "POST": try: credentials = request.user.aws_credentials key = credentials.access_key_id secret = credentials.secret_access_key except AttributeError as e: logger.error(e) key = '' secret = '' filename = save_upload(request) if po_id: key = u"purchase_order/{0}/files/{1}".format( po_id, filename.split('/')[-1]) else: key = u"purchase_order/files/{0}".format(filename.split('/')[-1]) obj = S3Object.create(filename, key, u"document.dellarobbiathailand.com", key, secret) serializer = S3ObjectSerializer(obj) response = HttpResponse(JSONRenderer().render(serializer.data), content_type="application/json") response.status_code = 201 return response # If any method other than POST else: response = HttpResponse('{"message": "Not Allowed"}', content_type='application/json; charset=utf-8') response.status_code = 405 return response
def dehydrate(self, bundle): """ Implements the dehydrate method to manipulate data before it is returned to the client """ #Checks if the country is set bundle = self._set_country(bundle) #Adds the quantity to the data field bundle.data['quantity'] = bundle.obj.quantity #Replaces custom-type with type after supply creation if "custom-type" in bundle.data: bundle.data['type'] = bundle.obj.type del bundle.data['custom-type'] #Dehydrates the suppliers information if #requesting a single resource, if creating a new resource #or updating a single resource if re.search( "api/v1/supply/(w+\-)?\d+", bundle.request.path ) or bundle.request.method == 'POST' or bundle.request.method == 'PUT': bundle.data['suppliers'] = [ self.dehydrate_supplier(bundle, supplier) for supplier in bundle.obj.suppliers.all() ] if not bundle.obj.sticker: sticker_page = StickerPage(code="DRS-{0}".format( bundle.obj.id), description=bundle.obj.description) filename = sticker_page.create("DRS-{0}".format(bundle.obj.id)) stickers = S3Object.create( filename, "supplies/stickers/{0}".format(filename), 'document.dellarobbiathailand.com', encrypt_key=True) bundle.obj.sticker = stickers bundle.obj.save() bundle.data['sticker'] = {'url': bundle.obj.sticker.generate_url()} #If getting a list else: bundle.data['suppliers'] = [{ 'name': supplier.name, 'id': supplier.id } for supplier in bundle.obj.suppliers.all()] #Merging product data from a supplier with the resource #if gettings supplies for a single supplier if bundle.request.GET.has_key('supplier_id'): #Set the supply's supplier to using #objects internals to get info bundle.obj.supplier = Supplier.objects.get( pk=bundle.request.GET.get('supplier_id')) bundle.data.update({ 'purchasing_units': bundle.obj.purchasing_units, 'cost': bundle.obj.cost, 'reference': bundle.obj.reference, 'lead_time': bundle.obj.lead_time, 'upc': bundle.obj.upc }) if bundle.obj.image: try: bundle.data['image'] = { 'id': bundle.obj.image.id, 'url': bundle.obj.image.generate_url(3600) } except (AttributeError, KeyError) as e: logger.warn(e) logger.debug(bundle.data) return bundle
def create(cls, user, **kwargs): """Creates the acknowledgement This method accept data to set and then creates an accompanying PDF and logs the event. A User Object is required to authorize certain data """ acknowledgement = cls() # Get Customer and create in TRCloud if necessary acknowledgement.customer = Customer.objects.get( id=kwargs['customer']['id']) try: if not acknowledgement.customer.trcloud_id == 0: acknowledgement.customer.create_in_trcloud() except Exception as e: logger.warn(e) acknowledgement.employee = user acknowledgement.delivery_date = dateutil.parser.parse( kwargs['delivery_date']) acknowledgement.status = 'ACKNOWLEDGED' try: acknowledgement.vat = int(kwargs["vat"]) except KeyError: acknowledgement.vat = 0 try: acknowledgement.po_id = kwargs["po_id"] except KeyError: raise AttributeError("Missing Purchase Order number.") try: acknowledgement.remarks = kwargs["remarks"] except KeyError: pass #Create the products without saving acknowledgement.items = [ Item.create(acknowledgement=acknowledgement, commit=False, **product_data) for product_data in kwargs['products'] ] acknowledgement.calculate_totals(acknowledgement.items) #Save the ack and by overriden method, the items acknowledgement.save() #Create the order PDFs ack, production = acknowledgement._create_pdfs() ack_key = "acknowledgement/Acknowledgement-{0}.pdf".format( acknowledgement.document_number) production_key = "acknowledgement/Production-{0}.pdf".format( acknowledgement.document_number) bucket = "document.dellarobbiathailand.com" ack_pdf = S3Object.create(ack, ack_key, bucket, encrypt_key=True) prod_pdf = S3Object.create(production, production_key, bucket, encrypt_key=True) acknowledgement.acknowledgement_pdf = ack_pdf acknowledgement.production_pdf = prod_pdf acknowledgement.original_acknowledgement_pdf = ack_pdf #Save Ack with pdf data acknowledgement.save() return acknowledgement
def hydrate(self, bundle): """ Implements the hydrate function """ #Set the country, in order to retrieve the correct quantity bundle = self._set_country(bundle) #Takes supplier and add to supplier list in data if "supplier" in bundle.data: try: suppliers = bundle.data['suppliers'] except KeyError: bundle.data['suppliers'] = [] suppliers = [] if bundle.data['supplier']['id'] not in [ s['id'] for s in suppliers ]: bundle.data['suppliers'].append(bundle.data['supplier']) del bundle.data['supplier'] #Adds new types try: if bundle.data['type'].lower() == 'custom': bundle.obj.type = bundle.data['custom-type'] del bundle.data['custom-type'] else: bundle.obj.type = bundle.data['type'] bundle.data['type'] = bundle.obj.type except KeyError as e: logger.warn(e) #Adds the quantity try: logger.debug("{0} : {1}".format(bundle.obj.quantity, bundle.data['quantity'])) logger.debug(bundle.obj.id) logger.debug( bool( Decimal(str(bundle.obj.quantity)) != Decimal( bundle.data['quantity']) and bundle.obj.quantity != None)) if Decimal(str(bundle.obj.quantity)) != Decimal( bundle.data['quantity']) and bundle.obj.quantity != None: action = "ADD" if float(bundle.data['quantity'] ) > bundle.obj.quantity else "SUBTRACT" diff = abs( Decimal(str(bundle.obj.quantity)) - Decimal(bundle.data['quantity'])) bundle.obj.quantity = float(bundle.data['quantity']) log = Log(supply=bundle.obj, action=action, quantity=diff, message=u"{0}ed {1}{2} {3} {4}".format( action.capitalize(), diff, bundle.obj.units, "to" if action == "ADD" else "from", bundle.obj.description)) log.save() except KeyError: pass #Adds the image if "image" in bundle.data: try: bundle.obj.image = S3Object.objects.get( pk=bundle.data['image']['id']) except KeyError: #Create a new S3object for the image s3_obj = S3Object() s3_obj.key = bundle.data['image']['key'] s3_obj.bucket = bundle.data['image']['bucket'] s3_obj.save() bundle.obj.image = s3_obj except S3Object.DoesNotExist: raise """ #Change the quantity if "quantity" in bundle.data and bundle.obj.pk: #Equalize the 2 quantities so that #they are easier to work with and compare client_quantity = float(bundle.data['quantity']) server_quantity = float(bundle.obj.quantity) difference = abs(client_quantity - server_quantity) #Get the description description = bundle.obj.description purchasing_units = bundle.obj.purchasing_units #Checks if quantity is added if client_quantity > server_quantity: if bundle.request.user.has_perm('supplies.add_quantity'): bundle.obj.quantity = client_quantity logger.info("Added {0}{1} to {2} inventory".format(difference, purchasing_units, description)) else: bundle.data['quantity'] = server_quantity bundle.data['quantity'] = server_quantity warning = "{0} is not authorized to add to the quantity of Fabric {1}".format(bundle.request.user.username, bundle.obj.description) logger.warn(warning) #raise Unauthorized("User does not have authorization to add to inventory.") #Checks if quantity was subtracted elif client_quantity < server_quantity: if bundle.request.user.has_perm('supplies.subtract_quantity'): bundle.obj.quantity = client_quantity logger.info("Subtracted {0}{1} from {2} inventory".format(difference, purchasing_units, description)) else: bundle.data['quantity'] = server_quantity warning = "{0} is not authorized to subtract from the quantity of Fabric {1}".format(bundle.request.user.username, bundle.obj.description) logger.warn(warning) #raise Unauthorized("User does not have authorization to subtract from inventory.") """ return bundle
filename = "{0} Col: {1}".format(fabric.pattern, fabric.color) fabric.description = filename fabric.save() print fabric.id, fabric.description try: product = Product.objects.get(supply=fabric, supplier=supplier) except Product.DoesNotExist: product = Product(supply=fabric, supplier=supplier) product.purchasing_units = 'yd' try: product.cost = Decimal(fabric.grade) * Decimal('1.10') except Exception: product.cost = 0 product.save() if 'image' in f: f['image'].save(filename + ".jpg") image = S3Object.create( filename + ".jpg", "supply/image/{0}-{1}.jpg".format(fabric.pattern, fabric.color), 'media.dellarobbiathailand.com') fabric.image = image fabric.save()
fabric.save() filename = "{0} Col: {1}".format(fabric.pattern, fabric.color) fabric.description = filename fabric.save() print fabric.id, fabric.description try: product = Product.objects.get(supply=fabric, supplier=supplier) except Product.DoesNotExist: product = Product(supply=fabric, supplier=supplier) product.purchasing_units = 'yd' try: product.cost = Decimal(fabric.grade) * Decimal('1.10') except Exception: product.cost = 0 product.save() if 'image' in f: f['image'].save(filename + ".jpg") image = S3Object.create(filename + ".jpg", "supply/image/{0}-{1}.jpg".format(fabric.pattern, fabric.color), 'media.dellarobbiathailand.com') fabric.image = image fabric.save()
def setUp(self): """ Set up for the Estimate Test Objects created: -User -Customer -Supplier -Address -product -2 fabrics After Creating all the needed objects for the Estimate, test that all the objects have been made. """ super(EstimateResourceTest, self).setUp() # Set Base URL self.base_url = '{0}'.format('/api/v1/estimate/') self.ct = ContentType(app_label="estimates") self.ct.save() #Create the user self.username = '******' self.password = '******' self.user = User.objects.create_user(self.username, '*****@*****.**', self.password) p = Permission(content_type=self.ct, codename="change_estimate") p.save() p2 = Permission(content_type=self.ct, codename="add_estimate") p2.save() self.user.user_permissions.add(p) self.user.user_permissions.add(p2) self.user.save() self.setup_client() #Create supplier, customer and addrss customer = copy.deepcopy(base_customer) del customer['id'] self.customer = Customer(**customer) self.customer.save() self.supplier = Supplier(**base_supplier) self.supplier.save() self.address = Address(address1="Jiggle", contact=self.customer) self.address.save() #Create a product to add self.product = Product.create(self.user, **base_product) self.product.save() #Create custom product self.custom_product = Product() self.custom_product.id = 10436 self.custom_product.save() self.fabric = Fabric.create(**base_fabric) self.fabric.quantity = 26 self.fabric.save() f_data = base_fabric.copy() f_data["pattern"] = "Stripe" self.fabric2 = Fabric.create(**f_data) #Create custom product self.custom_product = Product.create(self.user, description="Custom Custom", id=10436, width=0, depth=0, height=0, price=0, wholesale_price=0, retail_price=0) self.custom_product.id = 10436 self.custom_product.save() self.image = S3Object(key='test', bucket='test') self.image.save() #Create acknowledgement ack_data = base_ack.copy() del ack_data['customer'] del ack_data['items'] del ack_data['employee'] del ack_data['project'] self.ack = Estimate(**ack_data) self.ack.customer = self.customer self.ack.employee = self.user self.ack.save() #Create an item item_data = { 'id': 1, 'quantity': 1, 'is_custom_size': True, 'width': 1500, "fabric": { "id": 1 } } self.item = Item.create(estimate=self.ack, **item_data) item_data = { 'is_custom': True, 'description': 'F-04 Sofa', 'quantity': 3 } self.item2 = Item.create(estimate=self.ack, **item_data) #Create fake S3Objects to test files attached to acknowledgements self.file1 = S3Object(key='test1', bucket='test') self.file2 = S3Object(key='test2', bucket='test') self.file1.save() self.file2.save()