Esempio n. 1
0
    def approve_sales_return(self, user, receipt, **kwargs):
        returned_sales = kwargs.get('returned_sales')
        sales_id = kwargs.get('sales_id')
        sales_return_id = kwargs.get('sales_return_id')

        sales_return = get_model_object(SaleReturn, 'id', sales_return_id)

        check_approved_sales(returned_sales, SaleReturnDetail)

        for returned_sale in returned_sales:
            returned_sale_detail = get_model_object(SaleReturnDetail, 'id',
                                                    returned_sale)
            batch_histories = BatchHistory.objects.\
                filter(sale_id=sales_id,
                       batch_info_id=returned_sale_detail.batch_id)

            returned_quantity = returned_sale_detail.quantity

            self.return_batch_quantity(batch_histories, receipt,
                                       returned_quantity, returned_sale_detail,
                                       sales_return_id, user)
        return sales_return
 def mutate(cls, root, info, **kwargs):
     supplier_id = kwargs.get("supplier_id")
     user = info.context.user
     outlet_ids = kwargs.get("outlet_ids")
     note = kwargs.get("note")
     validator.special_character_validation(note)
     if len(note.split()) < 2:
         raise GraphQLError(
             ORDERS_ERROR_RESPONSES["supplier_note_length_error"])
     supplier = get_model_object(Suppliers, "id", supplier_id)
     outlets = [
         get_model_object(Outlet, 'id', outlet_id)
         for outlet_id in outlet_ids
     ]
     supplier_note = SupplierNote(supplier=supplier, note=note, user=user)
     with SaveContextManager(supplier_note) as supplier_note:
         supplier_note.outlet.add(*outlets)
         supplier_note.save()
         return cls(supplier_note=supplier_note,
                    supplier=supplier,
                    message=SUCCESS_RESPONSES["creation_success"].format(
                        "Supplier's note"))
    def mutate(self, info, **kwargs):
        user = info.context.user

        validate.validate_fields(**kwargs)
        product_id = kwargs['product_id']
        batch_ids = kwargs['batch_ids']
        quantities = kwargs['quantities']

        product = get_model_object(Product, 'id', product_id)
        sending_outlet = check_user_has_an_active_outlet(user)
        destination_outlet = get_model_object(Outlet, 'id',
                                              kwargs['destination_outlet_id'])
        if str(sending_outlet) == str(destination_outlet):
            raise GraphQLError(
                STOCK_ERROR_RESPONSES["outlet_transfer_validation"])
        product_batch_ids = product.batch_info.values_list("id", flat=True)

        message = "Batch with ids {} do not exist in this product"
        check_validity_of_ids(batch_ids, product_batch_ids, message=message)
        product_batch_quantities = [
            product.batch_info.get(id=id).quantity for id in batch_ids
        ]

        check_validity_of_quantity(quantities, product_batch_quantities,
                                   batch_ids)

        stock_transfer = StockTransfer(product=product,
                                       sending_outlet=sending_outlet,
                                       destination_outlet=destination_outlet)

        with SaveContextManager(stock_transfer) as stock_transfer:
            for index, value in enumerate(batch_ids):
                stock_transfer_record = StockTransferRecord.objects.create(
                    quantity=quantities[index], batch_id=value)
                stock_transfer.stock_transfer_record.add(stock_transfer_record)

        success = [STOCK_SUCCESS_RESPONSES["stock_transfer_open_success"]]
        return OpenStockTransfer(stock_transfer=stock_transfer,
                                 success=success)
Esempio n. 4
0
 def mutate(root, info, **kwargs):
     user_id = kwargs.get('user_id')
     role_id = kwargs.get('role_id')
     user_instance = get_model_object(User, 'id', user_id)
     role_instance = get_model_object(Role, 'id', role_id)
     admin_instance = get_model_object(Role, 'name', 'Master Admin')
     business_users = User.objects.filter(business__user=user_instance)
     business_admin = business_users.filter(role=admin_instance).count()
     if user_instance.role == role_instance:
         role_error = AUTH_ERROR_RESPONSES["assigning_user_roles"]
         raise GraphQLError(role_error)
     if business_admin == 1 \
             and role_instance != admin_instance:
         downgrade_error = AUTH_ERROR_RESPONSES["downgrade_user"]
         raise GraphQLError(downgrade_error)
     user_instance.role = role_instance
     user_instance.save()
     message = [
         f"Successfully updated {user_instance}"
         f" to a {role_instance} role"
     ]
     return UpdateUserRole(user=user_instance, message=message)
Esempio n. 5
0
 def check_payment_method(self, **kwargs):
     payment_method = kwargs.get('payment_method').lower()
     outlet_id = kwargs.get('outlet_id')
     preferences = get_model_object(OutletPreference, 'outlet_id',
                                    outlet_id)
     message = SALES_ERROR_RESPONSES['invalid_payment']
     if preferences.payment_method == 'both' and \
             payment_method not in ['cash', 'card', 'credit']:
         raise GraphQLError(message)
     if preferences.payment_method != 'both' and \
             payment_method not in ['others', 'credit']:
         if preferences.payment_method != payment_method:
             raise GraphQLError(message)
Esempio n. 6
0
 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)
Esempio n. 7
0
    def mutate(self, info, **kwargs):
        user = info.context.user
        survey_id = kwargs.get("survey_id")
        validate_empty_field('Survey Id', survey_id)

        # get survey instance and unlink all its
        # price_check_survey instances
        survey = get_model_object(Survey, 'id', survey_id)
        survey.survey_price_checks.all().delete(user)
        survey.delete(user)
        message = PRODUCTS_SUCCESS_RESPONSES["survey_deletion_success"].format(
            survey_id)
        return DeletePriceCheckSurvey(success=message)
Esempio n. 8
0
    def mutate(self, info, **kwargs):
        product_id = kwargs.get('product_id')
        request_id = kwargs.get('edit_request_id')
        message = PRODUCTS_ERROR_RESPONSES["inexistent_proposed_edit"].format(
            request_id)

        product = get_model_object(Product, 'id', product_id)
        product.approve_proposed_edit(request_id)

        message = [
            SUCCESS_RESPONSES["approval_success"].format("Edit request")
        ]
        return ApproveProposedEdits(product=product, message=message)
Esempio n. 9
0
    def mail_receipt(receipt_id):
        """
        Sends a digital copy of a sales receipt to the customer

        Arguments:
            receipt_id: ID of receipt to send

        Returns:
            None
        """
        receipt = get_model_object(Receipt, 'id', receipt_id)
        sale_details = SaleDetail.objects.filter(sale_id=receipt.sale.id)
        receipt_product_info = [{
            'product_name':
            get_model_object(Product, 'id',
                             sold_item_detail.product_id).product_name,
            'quantity_bought':
            sold_item_detail.quantity,
            'price':
            sold_item_detail.price,
            'discount':
            sold_item_detail.discount
        } for sold_item_detail in sale_details]
        if not receipt.sale.customer:
            raise AttributeError(RECEIPT_ERROR_RESPONSES['mailer_no_customer'])
        if not receipt.sale.customer.email:
            raise AttributeError(RECEIPT_ERROR_RESPONSES['mailer_no_email'])
        mail_context = {
            'receipt': receipt,
            'receipt_product_info': receipt_product_info,
            'sale': receipt.sale
        }
        mail = SendMail(
            to_email=[receipt.sale.customer.email],
            subject=f"Purchase receipt from {receipt.sale.outlet.name}",
            template='email_alerts/receipts/sale_receipt.html',
            context=mail_context)
        mail.send()
 def mutate(self, info, **kwargs):
     outlet_id = kwargs.get('outlet_id')
     user = info.context.user
     check_user_is_active_in_outlet(user, outlet_id=outlet_id)
     today_date = datetime.now()
     twelve_month = today_date + relativedelta(months=+12)
     outlet = get_model_object(Outlet, 'id', outlet_id)
     near_expired_products = Product.objects \
         .for_business(outlet.business.id) \
         .filter(nearest_expiry_date__range=(today_date, twelve_month))
     promotion_set = set_recommended_promotion(Promotion,
                                               near_expired_products)
     return CreateRecommendedPromotion(
         success='Promotion set on {} product(s)'.format(promotion_set))
Esempio n. 11
0
 def mutate(self, info, **kwargs):
     country_id = kwargs.get('country_id', '')
     city_name = kwargs.get('city_name', '')
     city_name = validate_fields.validate_name(city_name, 'city')
     city_name = city_name.title()
     country = get_model_object(Country, 'id', country_id)
     cities = [city['name'] for city in list(country.city_set.values())]
     if city_name in cities:
         raise GraphQLError(
             OUTLET_ERROR_RESPONSES["city_double_creation_error"].format(
                 "City " + city_name))
     city = City(name=city_name, country=country)
     with SaveContextManager(city, model=City):
         return CreateCity(city=city)
Esempio n. 12
0
    def mutate(self, info, **kwargs):
        loyalty_value = kwargs.get("loyalty_value")
        if loyalty_value < 1:
            raise GraphQLError(
                PRODUCTS_ERROR_RESPONSES["loyalty_weight_error"])
        product_category_id = kwargs.get("product_category_id")
        products = ProductQuery().query_product_category(product_category_id)
        category = get_model_object(ProductCategory, 'id', product_category_id)
        for product in products:
            product.loyalty_weight = loyalty_value
            product.save()

        message = SUCCESS_RESPONSES["update_success"].format("Loyalty weight")
        return UpdateLoyaltyWeight(category=category, message=message)
Esempio n. 13
0
    def get(self, request, *args, **kwargs):
        supplier_order_detail_id = kwargs.get('supplier_order_detail_id')
        supplier_order_detail = get_model_object(SupplierOrderDetails, 'id',
                                                 supplier_order_detail_id)

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'filename=supplier_order_form.pdf'
        html = render_to_string('orders/supplier_order_form.html',
                                {'detail': supplier_order_detail})
        font_config = FontConfiguration()
        css = weasyprint.CSS(settings.STATIC_ROOT + "/css/order-pdf.css",
                             font_config=font_config)
        weasyprint.HTML(string=html).write_pdf(response, stylesheets=[css])
        return response
Esempio n. 14
0
    def mutate(self, info, email, password, mobile_number):
        mobile_number = mobile_number.replace(" ", "")
        validate_fields = ValidateUser().validate_user_fields(
            email, password, mobile_number)
        try:
            user = User.objects.create_user(**validate_fields)
            role = get_model_object(Role, 'name', 'Master Admin')
            user.set_password(password)
            user.role = role
            user.save()
            # account verification
            token = account_activation_token.make_token(user)
            uid = urlsafe_base64_encode(force_bytes(user.pk))
            to_email = [user.email]
            email_verify_template = \
                'email_alerts/authentication/verification_email.html'
            subject = 'Account Verification'
            context = {
                'template_type':
                'Verify your email',
                'small_text_detail':
                'Thank you for '
                'creating a HealthID account. '
                'Please verify your email '
                'address to set up your account.',
                'email':
                user.email,
                'domain':
                DOMAIN,
                'uid':
                uid,
                'token':
                token,
            }
            send_mail = SendMail(email_verify_template, context, subject,
                                 to_email)
            send_mail.send()
            registration_message =\
                AUTH_SUCCESS_RESPONSES["registration_success"]
            verification_message = AUTH_SUCCESS_RESPONSES["email_verification"]

            success = [registration_message + verification_message]
            verification_link = f"{DOMAIN}/healthid/activate/{uid}/{token}"
            return RegisterUser(success=success,
                                user=user,
                                verification_link=verification_link)
        except Exception as e:
            errors = ["Something went wrong: {}".format(e)]
            return RegisterUser(errors=errors)
Esempio n. 15
0
    def resolve_stock_transfer(self, info, **kwargs):
        """Method to retrieve a single stock transfer using its number
        """
        user = info.context.user
        outlet = check_user_has_an_active_outlet(user)
        validate.validate_transfer(kwargs['transfer_number'])
        stock_transfer = get_model_object(
            StockTransfer, 'id', kwargs['transfer_number'])
        sending_outlet = stock_transfer.sending_outlet
        destination_outlet = stock_transfer.destination_outlet

        if stock_transfer and (str(sending_outlet) == str(outlet)
                               or str(destination_outlet) == str(outlet)):
            return stock_transfer
        raise GraphQLError(STOCK_ERROR_RESPONSES["inexistent_stock_transfer"])
Esempio n. 16
0
    def mutate(cls, root, info, **kwargs):
        user_ids = kwargs.get('user_ids')
        subject = kwargs.get('subject')
        event_name = kwargs.get('event_name')
        body = kwargs.get('body')
        users = list(map(lambda user_id: get_model_object(
            User, 'id', user_id), user_ids))

        notifications = notify(
            users=users,
            subject=subject,
            event_name=event_name,
            body=body)

        return cls(notifications=notifications)
Esempio n. 17
0
 def mutate(cls, root, info, **kwargs):
     id = kwargs.get('id')
     proposed_edit = get_model_object(Suppliers, 'id', id)
     if proposed_edit.user != info.context.user:
         msg = ORDERS_ERROR_RESPONSES["edit_proposal_validation_error"]
         raise GraphQLError(msg)
     kwargs.pop('id')
     for (key, value) in kwargs.items():
         if key is not None:
             setattr(proposed_edit, key, value)
     params = {'model': Suppliers}
     with SaveContextManager(proposed_edit, **params) as edit_request:
         name = proposed_edit.parent.name
         msg = SUCCESS_RESPONSES["update_success"].format("Supplier" + name)
         return cls(edit_request, msg)
Esempio n. 18
0
 def mutate(self, info, **kwargs):
     id = kwargs.get('id')
     name = kwargs.get('name', '').strip().title()
     name = validate_fields.validate_name(name, 'city')
     city = get_model_object(City, 'id', id)
     country_cities = City.objects.filter(country=city.country).all()
     if name in [str(city) in country_cities]:
         raise GraphQLError(
             OUTLET_ERROR_RESPONSES["city_double_creation_error"].format(
                 "The city " + name))
     city.name = name
     city.save()
     return EditCity(
         city=city,
         success=SUCCESS_RESPONSES["update_success"].format("City"))
 def mutate(self, info, **kwargs):
     promotion_id = kwargs.pop('promotion_id')
     user = info.context.user
     promotion = get_model_object(Promotion, 'id', promotion_id)
     check_user_is_active_in_outlet(user, outlet=promotion.outlet)
     product_ids = \
         kwargs.pop('product_ids') if kwargs.get('product_ids') else []
     validate_fields(Promotion(), **kwargs)
     for (key, value) in kwargs.items():
         setattr(promotion, key, value)
     with SaveContextManager(promotion, model=Promotion) as promotion:
         promotion = add_products_to_promotion(promotion, product_ids)
         return UpdatePromotion(
             success=SUCCESS_RESPONSES["update_success"].format(
                 "Promotion"),
             promotion=promotion)
Esempio n. 20
0
    def mutate(cls, root, info, **kwargs):
        order_id = kwargs.get('order_id')
        products = kwargs.get('products')
        quantities = kwargs.get('quantities', None)
        cost_per_items = kwargs.get('cost_per_items', None)
        prices = kwargs.get('prices', None)
        suppliers = kwargs.get('suppliers', None)
        order = get_model_object(Order, 'id', order_id)

        if quantities and prices and cost_per_items:
            params = {'name1': 'Quantities', 'name2': 'Products'}
            params2 = {'name1': 'Prices', 'name2': 'Products'}
            params3 = {'name1': 'CostPerItems', 'name2': 'Products'}
            add_order_details.check_list_length(products, quantities, **params)
            add_order_details.check_list_length(products, prices, **params2)
            add_order_details.check_list_length(products, cost_per_items,
                                                **params3)
            quantity = iter(quantities)
            price = iter(prices)
            cost_per_item = iter(cost_per_items)
            object_list = add_order_details.get_order_details(
                kwargs, order, quantity, price, cost_per_item)
        elif quantities:
            params = {'name1': 'Quantities', 'name2': 'Products'}
            add_order_details.check_list_length(products, quantities, **params)
            quantity = iter(quantities)
            object_list = add_order_details.get_order_details(
                kwargs, order, quantity)
        else:
            object_list = \
                add_order_details.get_order_details(kwargs, order)

        if suppliers:
            params = {'name1': 'Suppliers', 'name2': 'Products'}
            add_order_details.check_list_length(products, suppliers, **params)
            supplier = iter(suppliers)
            order_details = add_order_details.add_supplier(
                kwargs, supplier, object_list)
        else:
            order_details = add_order_details.supplier_autofill(
                kwargs, object_list)

        message = ORDERS_SUCCESS_RESPONSES["order_addition_success"]
        suppliers_order_details = create_suppliers_order_details(order)
        return cls(order_details=order_details,
                   message=message,
                   suppliers_order_details=suppliers_order_details)
Esempio n. 21
0
def check_approved_sales(returned_sales, sales_return_detail):
    is_valid = []
    approved_returns_ids = []
    for returned_sale in returned_sales:
        returned_sale_detail = get_model_object(
            sales_return_detail, 'id', returned_sale)
        if returned_sale_detail.is_approved:
            approved_returns_ids.append(returned_sale_detail.id)
            is_valid.append(False)
    if not all(is_valid):
        invalid_items = list(
            compress(approved_returns_ids,
                     [not item for item in is_valid]))
        message = SALES_ERROR_RESPONSES[
            "already_approved_sales_returns"].format(
            ",".join(map(str, invalid_items)))
        raise GraphQLError(message)
Esempio n. 22
0
    def fetch(self):
        """Get Supplier Order Details

        Get all supplieer order details belong to provided order and match
        the provided ids.

        Returns:
            (Obj:) QuerySet object of supplier order details
        """
        order = get_model_object(Order, 'id', self.order_id)
        results = SupplierOrderDetails.objects.all()
        results = results.filter(id__in=self.supplier_order_details_ids,
                                 order=order)
        if not results:
            raise ValueError("No supplier Order Details found matching"
                             "provided ids and Order")
        return results
Esempio n. 23
0
 def mutate(self, info, **kwargs):
     id = kwargs.get('product_id')
     product = get_model_object(Product,
                                'id',
                                id,
                                manager_query=Product.all_products)
     if product.is_approved:
         raise GraphQLError(
             PRODUCTS_ERROR_RESPONSES["product_approval_duplication"].
             format(id))
     product.is_approved = True
     product.save()
     success = [
         'message',
         SUCCESS_RESPONSES["approval_success"].format("Product " + str(id))
     ]
     return ApproveProduct(success=success, product=product)
    def mutate(self, info, **kwargs):
        user = info.context.user
        id = kwargs.get('id')
        business = get_model_object(Business, 'id', id)

        if business.user != user:
            update_error = BUSINESS_ERROR_RESPONSES["business_update_error"]
            raise GraphQLError(update_error)
        for(key, value) in kwargs.items():
            if key is not None:
                setattr(business, key, value)
        msg = BUSINESS_ERROR_RESPONSES["existing_business_error"]
        with SaveContextManager(business, model=Business, message=msg):
            success =\
                [SUCCESS_RESPONSES[
                    "update_success"].format(business.legal_name)]
            return UpdateBusiness(business=business, success=success)
Esempio n. 25
0
    def mutate(self, info, **kwargs):
        request_user = info.context.user
        _id = kwargs['id']
        event = get_model_object(Event, 'id', _id)
        event_creator = event.user.first()
        if str(request_user.email) != str(event_creator.email):
            authorization_error =\
                EVENTS_ERROR_RESPONSES["event_update_validation_error"]
            raise GraphQLError(authorization_error)
        new_event = kwargs.items()

        for key, value in new_event:
            if key is not None:
                setattr(event, key, value)
        event.save()
        success = SUCCESS_RESPONSES["update_success"].format("Event")
        return UpdateEvent(event=event, success=success)
Esempio n. 26
0
def set_recommended_promotion(promotion_model, products):
    today_date = datetime.now()
    three_months = today_date + relativedelta(months=+3)
    one_month = today_date + relativedelta(months=+1)
    updated_items = 0
    for product in products:
        updated_items += 1
        expire_date = product.nearest_expiry_date
        if expire_date <= one_month.date():
            promotion_id = 3
        elif one_month.date() < expire_date <= three_months.date():
            promotion_id = 2
        else:
            promotion_id = 1
        promotion = get_model_object(promotion_model, 'id', promotion_id)
        promotion.products.add(product)
    return updated_items
Esempio n. 27
0
    def return_batch_quantity(self, batch_histories, receipt,
                              returned_quantity, returned_sale_detail,
                              sales_return_id, user):
        for batch_history in batch_histories:
            batch = get_model_object(BatchInfo, 'id',
                                     batch_history.batch_info.id)

            quantity = batch.batch_quantities.filter(is_approved=True).first()

            if returned_sale_detail.resellable:
                quantity.quantity_remaining += returned_quantity
                quantity.save()
            returned_sale_detail.is_approved = True
            returned_sale_detail.done_by = user
            returned_sale_detail.save()
        receipt.sales_return_id = sales_return_id
        receipt.save()
Esempio n. 28
0
    def mutate(self, info, **kwargs):
        sales_id = kwargs.get('sales_id')
        returned_sales = kwargs.get('returned_sales')

        if not returned_sales:
            raise GraphQLError(SALES_ERROR_RESPONSES["empty_sales_return"])

        receipt = get_model_object(Receipt, 'sale_id', sales_id)

        new_return = SaleReturn()
        sales_return = new_return.approve_sales_return(user=info.context.user,
                                                       receipt=receipt,
                                                       **kwargs)

        return ApproveSalesReturn(
            sales_return=sales_return,
            message=SALES_SUCCESS_RESPONSES["sales_return_approved"])
Esempio n. 29
0
    def check_product_exists(self, product_list):
        """
        checks that the product ids exist in the database

        Arguments:
            product_list(list): product ids

        Returns:
            list: product ids that exist in the database or raises an
                  error if there is one that doesn't exist in the
                  database
        """
        products = []
        for product_id in product_list:
            product = get_model_object(Product, 'id', product_id)
            products.append(product.id)
        return products
Esempio n. 30
0
    def get_order_details(cls,
                          kwargs,
                          order,
                          quantity=None,
                          price=None,
                          cost_per_item=None):
        """
        intitalizes order details for an order

        Arguments:
            kwargs(dict): contains products being ordered
            order(obj): whose order details will be intialized
            quantity: either an iterable for quantities of being
                      attached to order details or None if quantities
                      are being autofilled
            price: either an iterable for prices of being attached to
                    to order details or None if it is only creating
                    order detail without price

        Returns:
            list: objects of order details that have been initialized
        """
        products_list = kwargs.get('products')
        products = cls.check_product_exists(products_list)
        object_list = list()  # list to hold order details instances
        for product_id in products:
            product = \
                get_model_object(Product, 'id', product_id)
            order_details = OrderDetails()
            order_details.order = order
            order_details.product = product
            if not quantity:
                order_details.ordered_quantity = product.autofill_quantity
            else:
                order_details.ordered_quantity = next(quantity)
            if price:
                order_details.price = next(price)
            else:
                order_details.price = ""
            if cost_per_item:
                order_details.cost_per_item = next(cost_per_item)
            else:
                order_details.cost_per_item = ""
            object_list.append(order_details)
        return object_list