def mutate(self, info, **kwargs): customer = validate_customer_fields(Profile(), **kwargs) user = info.context.user outlet_currency_id = get_user_outlet_currency_id(user) currency = get_model_object(Currency, "id", outlet_currency_id) with SaveContextManager(customer, model=Profile) as customer: customer_credit = CustomerCredit(customer=customer, credit_currency=currency) with SaveContextManager(customer_credit, model=CustomerCredit): pass return CreateCustomer( message=SUCCESS_RESPONSES["creation_success"].format("Customer"), customer=customer)
def notify(users, subject, body, event_name=None, html_subject=None, html_body=None): ''' Function to notify the appropriate user ''' notifications = [] for user in users: notification = Notification(subject=str(subject), user=user, event_name=event_name or Notification().event_name) with SaveContextManager(notification) as notification: notification_meta = NotificationMeta.objects.create( notification_id=notification.id, body=str(body)) notification.notification_meta = notification_meta notifications.append(notification) if html_subject and html_body: send_email_notifications(html_subject, user, html_body) return notifications
def mutate(cls, root, info, **kwargs): edit_request = Suppliers() id = kwargs.get('id') contacts = kwargs.get('contacts') or None meta = kwargs.get('meta') or None supplier = get_model_object(Suppliers, 'id', id) if not supplier.is_approved: msg = ORDERS_ERROR_RESPONSES[ "supplier_edit_proposal_validation_error"] raise GraphQLError(msg) fields = cls.validate_fields(info, supplier, kwargs) for (key, value) in fields.items(): if key is not None: setattr(edit_request, key, value) with SaveContextManager(edit_request, model=Suppliers) as edit_request: name = supplier.name msg = ORDERS_SUCCESS_RESPONSES[ "supplier_edit_request_success"].format(name) if contacts: contacts['supplier_id'] = id contacts['edit_request_id'] = edit_request.id EditSupplierContacts.mutate(root, info, **contacts) if meta: meta['supplier_id'] = id meta['edit_request_id'] = edit_request.id EditSupplierMeta.mutate(root, info, **meta) return cls(edit_request, msg)
def notify(users, **kwargs): '''Function to notify the users through email notifications ''' despatch = {} despatch_queues = [] for user in users: despatch_queue = DespatchQueue.objects.create( recipient=user, due_date=kwargs.get('due_date')) with SaveContextManager(despatch_queue, model=DespatchQueue)\ as d_queue: body = kwargs.get('body') subject = kwargs.get('subject') for (key, value) in kwargs.items(): if key != 'due_date': despatch = Despatch_Meta(dataKey=key, dataValue=value, despatch=d_queue) despatch.save() if is_same_date( remove_seconds(d_queue.due_date), timezone.localtime( remove_seconds(remove_microseconds(timezone.now())))): thread = threading.Thread(target=send_email_notifications( subject, user, body, d_queue)) thread.start() despatch_queues.append(d_queue) return despatch_queues
def create_suppliers_order_details(order, supplier=None): """ function to generate supplier order details for an order Args: order(obj): order whose supplier order details are to be generated Returns: list: suppliers order details of a particular order """ order_details = order.orderdetails_set.all().order_by('supplier') order_details_by_suppliers = [ list(result) for key, result in groupby( order_details, key=lambda order_detail: order_detail.supplier) ] suppliers_order_details = [] for order_details_per_supplier in order_details_by_suppliers: supplier_name = order_details_per_supplier[0].supplier check_duplicate = SupplierOrderDetails.objects.filter( order=order, supplier=supplier_name).exists() supplier_order_details = SupplierOrderDetails( order=order, supplier=order_details_per_supplier[0].supplier) if not check_duplicate: with SaveContextManager( supplier_order_details, model=SupplierOrderDetails) as supplier_order_details: suppliers_order_details.append(supplier_order_details) else: current_supplier_detail = SupplierOrderDetails.objects.get( order=order, supplier=supplier_name) suppliers_order_details.append(current_supplier_detail) return suppliers_order_details
def mutate(self, info, **kwargs): user = info.context.user customer_consultation_id = kwargs.get('customer_consultation_id') customer_consultation = get_model_object(CustomerConsultation, 'id', customer_consultation_id) outlet = customer_consultation.outlet if customer_consultation.paid: raise GraphQLError(SALES_ERROR_RESPONSES["already_marked_as_paid"]) price = customer_consultation.consultation_type.price_per_session new_sale = Sale(sales_person=user, customer=customer_consultation.customer, outlet=outlet, amount_to_pay=price) del kwargs['customer_consultation_id'] for (key, value) in kwargs.items(): setattr(new_sale, key, value) with SaveContextManager(new_sale, model=Sale) as new_sale: pass customer_consultation.paid = True customer_consultation.sale_record = new_sale customer_consultation.save() new_receipt = Receipt() receipt = new_receipt.create_receipt(new_sale, outlet.id) return ConsultationPayment(sale=new_sale, receipt=receipt, message='message')
def mutate(self, info, **kwargs): product_ids = kwargs.get('product_ids') titles = kwargs.get('prompt_titles') prompt_descriptions = kwargs.get('descriptions') outlet_ids = kwargs.get('outlet_ids') sales_prompt_count = 0 valid_list = all( len(product_ids) == len(list_inputs) for list_inputs in [titles, prompt_descriptions, outlet_ids]) if not valid_list or len(product_ids) < 1: raise GraphQLError(SALES_ERROR_RESPONSES["incomplete_list"]) for title, description in zip(titles, prompt_descriptions): if title.strip() == "" or description.strip() == "": raise GraphQLError(SALES_ERROR_RESPONSES["title_error"]) created_prompts = [] for index, title in enumerate(titles, 0): params = {'model': SalesPrompt} sales_prompt = SalesPrompt( prompt_title=title.title(), description=prompt_descriptions[index], product_id=get_model_object(Product, 'id', product_ids[index]).id, outlet_id=get_model_object(Outlet, 'id', outlet_ids[index]).id) with SaveContextManager(sales_prompt, **params) as sales_prompt: created_prompts.append(sales_prompt) sales_prompt_count += 1 return CreateSalesPrompts( sales_prompts=created_prompts, message=SUCCESS_RESPONSES["creation_success"].format( "Sales prompt " + str(sales_prompt_count)))
def mutate(self, info, id, **kwargs): customer = get_model_object( Profile, "id", id, message=CUSTOMER_ERROR_RESPONSES["customer_profile_not_found"]) existing_fields = model_to_dict(customer) if "city_id" in kwargs: kwargs["city"] = kwargs.pop("city_id") if "country_id" in kwargs: kwargs["country"] = kwargs.pop("country_id") # add fields with changed values to new dictionary changed_fields = { key: kwargs.get(key) for key, value in existing_fields.items() if key in kwargs and value != kwargs.get(key) } if not changed_fields: return EditCustomerBasicProfile( message=CUSTOMER_ERROR_RESPONSES["unchanged_edits"], customer=customer) if "city" in changed_fields: changed_fields["city_id"] = changed_fields.pop("city") if "country" in changed_fields: changed_fields["country_id"] = changed_fields.pop("country") customer = validate_customer_fields(customer, **changed_fields) with SaveContextManager(customer, model=Profile) as customer: message = SUCCESS_RESPONSES["update_success"].format( customer.first_name + "'s basic profile") return EditCustomerBasicProfile(message=message, customer=customer)
def mutate(cls, root, info, id, **kwargs): outlet_ids = kwargs.pop('outlet_ids') supplier_note = get_model_object(SupplierNote, "id", id) if info.context.user != supplier_note.user: raise GraphQLError( ORDERS_ERROR_RESPONSES["supplier_note_update_validation_error"] ) for key, value in kwargs.items(): if key in ["note"]: special_cahracter_validation(value) if len(value.split()) < 2: raise GraphQLError( ORDERS_ERROR_RESPONSES["supplier_note_length_error"]) setattr(supplier_note, key, value) if outlet_ids: outlets = [ get_model_object(Outlet, 'id', outlet_id) for outlet_id in outlet_ids ] supplier_note.outlet.clear() supplier_note.outlet.add(*outlets) with SaveContextManager(supplier_note) as supplier_note: return cls(success=SUCCESS_RESPONSES["update_success"].format( "Supplier's note"), supplier_note=supplier_note)
def mutate(self, info, **kwargs): customer_id = kwargs.get("customer_id") customer = get_model_object( Profile, "id", customer_id) if CustomerCredit.objects.filter(customer_id=customer_id).exists(): raise GraphQLError( CUSTOMER_ERROR_RESPONSES[ "customer_credit_double_creation_error" ]) user = info.context.user outlet_currency_id = get_user_outlet_currency_id(user) currency = get_model_object( Currency, "id", outlet_currency_id, message=PREFERENCE_ERROR_RESPONSES["invalid_currency"].format( outlet_currency_id)) customer_credit = CustomerCredit( customer=customer, credit_currency=currency) with SaveContextManager(customer_credit, model=CustomerCredit): return CreateCustomerCredit( message=SUCCESS_RESPONSES[ "creation_success"].format("Customer's credit account"), customer_credit=customer_credit)
def mutate(self, info, **kwargs): user = info.context.user customer_id = kwargs['customer_id'] credit = kwargs['store_credit'] customer_credit = get_model_object( CustomerCredit, 'customer_id', customer_id) if credit <= 0: raise GraphQLError( CUSTOMER_ERROR_RESPONSES['wrong_amount'] ) previous_value = customer_credit.store_credit customer_credit.store_credit = ( float(previous_value) + float(credit)) customer_credit.save() credit_wallet = StoreCreditWalletHistory( sales_person=user, credit=credit, current_store_credit=previous_value, customer_account=customer_credit) with SaveContextManager( credit_wallet, model=StoreCreditWalletHistory) as credit_wallet: pass return EditCustomerWallet(message=SUCCESS_RESPONSES[ "update_success"].format("Credit"), customer=customer_credit)
def mutate(cls, root, info, **kwargs): supplier_meta = SuppliersMeta() supplier_id = kwargs.get('supplier_id') meta_id = kwargs.get('meta_id') meta = get_model_object(SuppliersMeta, 'id', meta_id) if \ meta_id else \ SuppliersMeta.objects.filter(supplier_id=supplier_id).first() supplier = get_model_object(Suppliers, 'id', supplier_id) if not supplier.is_approved: msg = ORDERS_ERROR_RESPONSES['supplier_edit_validation_error'] raise GraphQLError(msg) fields = cls.validate_fields(meta, kwargs) for (key, value) in fields.items(): if key is not None: setattr(supplier_meta, key, value) with SaveContextManager(supplier_meta, model=SuppliersMeta) as supplier_meta: name = supplier.name supplier.supplier_meta = supplier_meta supplier_meta.parent_id = meta.id if meta else supplier_meta.id supplier_meta.save() msg = SUCCESS_RESPONSES["update_success"].format( f"Supplier '{name}'") return cls(supplier, msg)
def mutate(self, info, **kwargs): user = info.context.user country_name = kwargs.get('country') city_name = kwargs.get('city_name') outlet_name = kwargs.get('name') business_id = kwargs.get('business_id') find_outlets = \ Outlet.objects.filter(name=outlet_name) for outlet in find_outlets: if business_id == outlet.business_id: raise GraphQLError('This business already has' ' an outlet with that name') outlet = Outlet() for (key, value) in kwargs.items(): setattr(outlet, key, value) role_instance = get_model_object(Role, 'id', user.role_id) if country_name and city_name: outlet.city = get_city(country_name, city_name) with SaveContextManager(outlet, model=Outlet) as outlet: add_outlet_metadata(outlet, kwargs.items()) OutletUser.objects.create(user=user, outlet=outlet, is_active_outlet=True, role=role_instance) return CreateOutlet( outlet=outlet, success=SUCCESS_RESPONSES["creation_success"].format("Outlet"))
def mutate(self, info, **kwargs): user = info.context.user outlet = check_user_has_an_active_outlet(user) order_id = kwargs.get('order_id') order = get_model_object(Order, 'id', order_id) invoice_document = kwargs.get('invoice_file') validate_empty_field('Invoice file', invoice_document) invoice_exist = \ Invoice.objects.filter(order_id=order_id).exists() if invoice_exist: raise GraphQLError( ORDERS_ERROR_RESPONSES["duplicate_upload_error"]) # check if order belongs to an outlet if order.destination_outlet_id != outlet.id: raise GraphQLError( ORDERS_ERROR_RESPONSES["initiation_invoice_upload_error"]) image_url = cloudinary.uploader.upload(invoice_document).get('url') invoice = Invoice(order_id=order.id, outlet_id=outlet.id, image_url=image_url) with SaveContextManager(invoice) as invoice: return UploadInvoice( invoice=invoice, message=SUCCESS_RESPONSES["upload_success"].format("Invoice"))
def create_promotion(products, title, discount, outlet): ''' Create promotion for products about to expiry ''' promotion = Promotion.objects.filter(title=title).first() products_added = True if promotion: products_added = not all(product in products for product in promotion.products.all()) promotion.products.add(*products) else: promotion_type, _ = PromotionType.objects.get_or_create(name='expiry') description = 'Products about to expire.' promotion = Promotion(title=title, promotion_type=promotion_type, description=description, discount=discount, is_approved=False, outlet=outlet) with SaveContextManager(promotion, model=Promotion) as promotion: promotion.products.add(*products) if products_added: users = outlet.active_outlet_users roles = ('Master Admin', 'Manager') users = [user for user in users if str(user.role) in roles] message = f'Products have been added to promotion {title}.' notify(users=users, subject='Products about to expire.', body=message)
def mutate(self, info, **kwargs): template_instance = get_model_object(StockCountTemplate, 'id', kwargs.get('template_id')) template_fields = stock_counts.get_template_fields(**kwargs) stock_tempalate = stock_counts.add_fields_to_template( template_instance, **template_fields) to_email = stock_tempalate.assigned_users.values_list('email', flat=True) email_stock_template = 'email_alerts/stocks/stock_email.html' subject = 'Stock counts template updated' context = { 'schedule_time': datetime.strftime(stock_tempalate.schedule_time.start_date, "%d-%b-%Y"), 'by': str(info.context.user.email), 'template_type': 'Stock counts', 'small_text_detail': 'Hello, stock counts schedule has \ been modified' } params = {'model': StockCountTemplate} with SaveContextManager(stock_tempalate, **params) as stock_tempalate: send_mail = SendMail(email_stock_template, context, subject, to_email) send_mail.send() message = SUCCESS_RESPONSES["edit_success"].format( "Stock count template") return EditStockCountTemplate(stock_template=stock_tempalate, success=message)
def mutate(self, info, **kwargs): user = info.context.user batch_n = kwargs.get('batch_no') quantity = kwargs.pop('quantity') kwargs['date_received'] = parse_date(kwargs.get('date_received')) kwargs['expiry_date'] = parse_date(kwargs.get('expiry_date')) datetime_str = sub('[-]', '', str(kwargs['date_received'])) batch_no_auto = f'BN{datetime_str}' batch_info = BatchInfo(user=user) if not batch_n: kwargs['batch_no'] = batch_no_auto batch_ = BatchInfo.objects.filter(batch_no=kwargs.get('batch_no')) batch__l = list( map(lambda batch__: batch__.quantity == quantity, batch_)) if True in batch__l: raise GraphQLError(ERROR_RESPONSES[ 'batch_exist'].format(kwargs['batch_no'])) for key, value in kwargs.items(): setattr(batch_info, key, value) with SaveContextManager(batch_info, model=BatchInfo) as batch_info: quantity = Quantity( batch=batch_info, quantity_received=quantity, quantity_remaining=quantity, is_approved=True) quantity.save() generate_reorder_points_and_max(batch_info.product) message = SUCCESS_RESPONSES["creation_success"].format("Batch") return CreateBatchInfo(message=message, batch_info=batch_info)
def mutate(self, info, **kwargs): name = kwargs.get('name') validate_empty_field('name', name) suppliers = kwargs.get('suppliers') products = kwargs.get('products') created_by = info.context.user outlet = get_model_object(Outlet, 'id', kwargs.get('outlet_id')) survey_instance = Survey(created_by=created_by, outlet=outlet, name=name) params = {'model': Survey} # Save the survey instance along with the products and suppliers with SaveContextManager(survey_instance, **params) as survey_instance: for supplier_id in suppliers: supplier = get_model_object(Suppliers, 'supplier_id', supplier_id) for product_id in products: price_check_survey = PriceCheckSurvey() price_check_survey.supplier = supplier product = get_model_object(Product, 'id', product_id) price_check_survey.product = product price_check_survey.save() price_check_survey.survey.add(survey_instance) success = SUCCESS_RESPONSES["creation_success"].format( "Master survey, " + name) return CreatePriceCheckSurvey(success=success, survey=survey_instance)
def mutate(root, info, input=None): success = True if input.name.strip() != "": role = Role(name=input.name) with SaveContextManager(role, model=Role): message = AUTH_SUCCESS_RESPONSES["create_role_success"].format( input.name) return CreateRole(success=success, role=role, message=message) raise GraphQLError(AUTH_ERROR_RESPONSES["empty_role_name"])
def mutate(self, info, name): params = {'model': 'EventType'} event_type = EventTypeModel(name=name) with SaveContextManager(event_type, **params) as event_type: success =\ SUCCESS_RESPONSES["creation_success"].format("Event type") return CreateEventType( success=success, event_type=event_type )
def mutate(cls, root, info, input=None): supplier_contacts = SuppliersContacts() fields = cls.validate_fields(input) for (key, value) in fields.items(): setattr(supplier_contacts, key, value) with SaveContextManager(supplier_contacts, model=SuppliersContacts) as supplier_contacts: return cls(supplier_contacts=supplier_contacts)
def mutate(self, info, **kwargs): id = kwargs.get('id') name = kwargs.get('name', '').strip().title() name = validate_fields.validate_name(name, 'country') country = get_model_object(Country, 'id', id) country.name = name with SaveContextManager(country, model=Country): success = SUCCESS_RESPONSES["update_success"].format("Country") return EditCountry(country=country, success=success)
def mutate(self, info, **kwargs): order_id = kwargs['order_id'] order = get_model_object(Order, 'id', order_id) for (key, value) in kwargs.items(): setattr(order, key, value) with SaveContextManager(order) as order: success = 'Order Edited Successfully!' return InitiateOrder(order=order, success=success)
def mutate(cls, root, info, input=None): supplier_meta = SuppliersMeta() fields = cls.validate_fields(input) for (key, value) in fields.items(): setattr(supplier_meta, key, value) with SaveContextManager(supplier_meta, model=SuppliersMeta) as supplier_meta: return cls(supplier_meta=supplier_meta)
def mutate(self, info, **kwargs): user = info.context.user update_consultation = get_model_object(CustomerConsultation, 'id', kwargs.get('consultation_id')) update_consultation.updated_by = user booking_date = kwargs.get('booking_date') if booking_date: booking_date = parser.parse(booking_date) kwargs['booking_date'] = make_aware(booking_date) for (key, value) in kwargs.items(): setattr(update_consultation, key, value) with SaveContextManager( update_consultation, model=CustomerConsultation) as update_consultation: # noqa pass if booking_date: new_date = update_consultation.booking_date event = get_model_object(Event, 'id', update_consultation.event_id) event_data = { 'start_date': new_date.date(), 'end_date': new_date.date(), 'start_time': new_date.time(), 'end_time': update_consultation.end_time.time() } for (key, value) in event_data.items(): setattr(event, key, value) with SaveContextManager(event, model=Event) as event: pass success =\ CONSULTATION_SUCCESS_RESPONSES["consultation_schedule_success"] return UpdateConsultation(update_consultation=update_consultation, success=success)
def mutate(root, info, id, input=None): success = False role_instance = get_model_object(Role, 'id', id) role_instance.name = input.name with SaveContextManager(role_instance, model=Role): success = True edit_success = SUCCESS_RESPONSES["update_success"] message = [edit_success.format(role_instance.name)] return EditRole( success=success, role=role_instance, message=message )
def mutate(self, info, **kwargs): name = kwargs.get('name') if name.strip() == "": raise GraphQLError(PRODUCTS_ERROR_RESPONSES["invalid_input_error"]) dispensing_size = DispensingSize(name=name) with SaveContextManager(dispensing_size, model=DispensingSize): message = [ SUCCESS_RESPONSES["creation_success"].format("Dispensing Size") ] return CreateDispensingSize(message=message, dispensing_size=dispensing_size)
def mutate(self, info, **kwargs): name = kwargs.get('name') if name.strip() == "": raise GraphQLError(SALES_ERROR_RESPONSES["promotion_type_error"]) params = {'model': PromotionTypeModel} promotion_type = PromotionTypeModel(name=name) with SaveContextManager(promotion_type, **params) as promotion_type: success = SUCCESS_RESPONSES["creation_success"].format( "Promotion Type") return CreatePromotionType(success=success, promotion_type=promotion_type)
def mutate(self, info, **kwargs): user = info.context.user add_notes = MedicalHistory(authorized_by=user) for (key, value) in kwargs.items(): setattr(add_notes, key, value) with SaveContextManager(add_notes, model=MedicalHistory) as add_notes: pass return AddMedicalNotes(add_notes=add_notes)
def mutate(self, info, **kwargs): outlet = get_model_object(Outlet, 'id', kwargs.get('destination_outlet')) order = Order(name=kwargs['name'], delivery_date=kwargs['delivery_date'], product_autofill=kwargs['product_autofill'], supplier_autofill=kwargs['supplier_autofill'], destination_outlet=outlet) with SaveContextManager(order) as order: success = ORDERS_SUCCESS_RESPONSES["order_initiation_success"] return InitiateOrder(order=order, success=success)