def finish_finishing(cls, quote_id, finishing_id):
     """Mark given finishing associated with quote as finished."""
     # get Quote_Finishing row associated with parameters
     try:
         q_finishing_row = Quote_Finishing.get(
             (Quote_Finishing.quote_id == quote_id) &
             (Quote_Finishing.finishing_id == finishing_id))
     except DoesNotExist:
         raise AttributeError(("Error: Quote_Finishing not found "
                               "for q:{}, f:{}").format(
                                   quote_id,
                                   finishing_id))
     else:
         # check that finishing is started and not finished
         if q_finishing_row.finishing_is_started is True:
             if q_finishing_row.finishing_is_finished is False:
                 # finish finishing
                 q_finishing_row.finishing_is_finished = True
                 # mark date finished
                 q_finishing_row.finishing_date_finished = (
                     datetime.datetime.now())
                 # display updates
                 print("[UPDATE finishing] Finished: {}, {}".format(
                     q_finishing_row.finishing_is_finished,
                     q_finishing_row.finishing_date_finished))
                 # prompt save
                 if input("Save? [Yn] ").lower() != 'n':
                     q_finishing_row.save()
                     print("> Finishing successfully finished.")
                 else:
                     print("> Finishing not finished.")
             else:
                 raise AttributeError("Error: Finishing already finished.")
         else:
             raise AttributeError("Error: Finishing not yet started.")
    def calculate_total_price(cls, quote_id, num_sheets):
        """
        Return the total price for all materials and finishings of a quote.
        """

        # Retrieve Quote_Material row associated with given quote number
        q_materials_rows = Quote_Material.select().where(
            Quote_Material.quote_id == quote_id)

        # Retrieve all of quote's materials prices
        total_materials_price = 0
        for q_material in q_materials_rows:
            logging.debug("Material: {}; Price: {}".format(
                q_material.material_id.material_name,
                q_material.material_id.material_price))
            # add material's price
            total_materials_price += q_material.material_id.material_price

        # Retrieve Quote_Finishing row associated with given quote number
        q_finishings_rows = Quote_Finishing.select().where(
            Quote_Finishing.quote_id == quote_id)

        # Retrieve all of quote's finishings prices
        total_finishings_price = 0
        for q_finishing in q_finishings_rows:
            logging.debug("Finishing: {}; Price: {}".format(
                q_finishing.finishing_id.finishing_name,
                q_finishing.finishing_id.finishing_price))
            # add finishing's price
            total_finishings_price += q_finishing.finishing_id.finishing_price

        # Retrieve paper associated with quote id
        q_paper_row = Quote_Paper.select().where(
            Quote_Paper.quote_id == quote_id)

        # Retrieve paper's price
        for paper in q_paper_row:
            paper_price = paper.paper_id.paper_price

        # log totals
        logging.debug(("Material price: {}; Finishing price: {}; "
                       "Paper price: {}").format(
            total_materials_price,
            total_finishings_price,
            paper_price))

        # multiply total price by number of sheets
        total_price = num_sheets * total_materials_price
        total_price += num_sheets * total_finishings_price
        total_price += num_sheets * paper_price

        # log total price
        logging.debug("Sheets: {}; Total price: {}".format(
            num_sheets,
            total_price))

        return total_price
    def get_finishings(cls, quote_id, is_started, is_finished):
        """Return the finishing(s) associated with the given quote id."""
        q_finishing_rows = Quote_Finishing.select().where(
            Quote_Finishing.quote_id == quote_id).order_by(
                Quote_Finishing.finishing_id)

        if is_started is not None and is_finished is not None:
            q_finishing_rows = q_finishing_rows.where(
                (Quote_Finishing.finishing_is_started == is_started) &
                (Quote_Finishing.finishing_is_finished == is_finished)).order_by(
                    Quote_Finishing.finishing_id)

        return q_finishing_rows
示例#4
0
def read_ops(filename):
    """Read data from given file to create Orders."""
    try:
        with open(filename, newline="") as file:
            # stores all the read lines
            reader = csv.DictReader(file, fieldnames=FIELDS)
            # stores all the skipped lines
            skipped_lines = []
            # connect to database
            db.connect()

            # init successful quote and order counter
            quotes_made = 0
            orders_made = 0
            # total lines
            total_lines = 0
            for row in reader:
                # update total lines
                total_lines += 1
                # skip if empty row
                if row["cliente"] == "" or row["cliente"] == "CLIENTE":
                    skipped_lines.append(row)
                else:
                    # materials list
                    materials_list = []
                    # finishings list
                    finishings_list = []
                    # printing sides and colors
                    sides = 0
                    colors_front = 0
                    colors_back = 0
                    # loop through items
                    for key, val in row.items():
                        # check materials
                        if key in MATERIALS.keys():
                            # print("### material ### ", end='')
                            if val == "X":
                                materials_list.append(MATERIALS[key])
                                if key == "impresion_t":
                                    sides = 1
                                    colors_front = 4
                                elif key == "impresion_tr":
                                    sides = 2
                                    colors_front = 4
                                    colors_back = 4
                        # check finishings
                        elif key in FINISHINGS.keys():
                            # print("%%% finishing %%% ", end='')
                            if val == "X":
                                finishings_list.append(FINISHINGS[key])

                        elif key == "cliente":
                            logging.debug("=== cliente === {}: {}".format(key, val))
                        elif key == "orden":
                            orden = val
                            logging.debug("=== OP === {}: {}".format(key, orden))
                        elif key == "cantidad":
                            num_copies = val.replace(",", "")
                            num_copies = int(num_copies)
                            logging.debug("=== Num copies === {}: {}".format(key, num_copies))
                        elif key == "material":
                            product = val
                            logging.debug("=== Pdct Type === {}: {}".format(key, product))
                        elif key == "fecha_entrega":
                            # date comes in format: dd/mm/yyyy
                            day, month, year = val.split("/")
                            # convert to integers
                            day = int(day)
                            month = int(month)
                            year = int(year)
                            # create date instance
                            due_date = datetime.date(year, month, day)
                            logging.debug("=== Due Date === {}: {}".format(key, due_date))
                        else:
                            logging.debug("/// {}: {}".format(key, val))

                    # check that only T/R is added if T is in materials list
                    if 1 in materials_list and 2 in materials_list:
                        materials_list.remove(1)
                    if 3 in materials_list and 4 in materials_list:
                        materials_list.remove(3)
                    if 7 in materials_list and 8 in materials_list:
                        materials_list.remove(7)
                    if 9 in materials_list and 10 in materials_list:
                        materials_list.remove(9)
                    if 13 in materials_list and 14 in materials_list:
                        materials_list.remove(13)

                    # print lists
                    logging.debug("### Materials = {}".format(materials_list))
                    logging.debug("### Finishings = {}".format(finishings_list))

                    logging.debug("Sides = {}".format(sides))
                    logging.debug("Colors (f, b): {}, {}".format(colors_front, colors_back))

                    # used to determine if rollback or commit
                    errors = False
                    with db.atomic() as txn:
                        # create Quote instance
                        try:
                            quote = Quote.create(
                                quote_name="Orden {}".format(orden),
                                quote_due_date=due_date,
                                quote_copies=num_copies,
                                quote_product_name=product,
                                quote_dimention_length=DEFAULT_LENGTH,
                                quote_dimention_width=DEFAULT_WIDTH,
                                quote_printing_bleed=DEFAULT_BLEED,
                                quote_printing_sides=sides,
                                quote_printing_colors_front=colors_front,
                                quote_printing_colors_back=colors_back,
                            )
                        except IntegrityError as err:
                            errors = True  # rollback transaction
                            logging.debug("> Quote error: {}".format(err))
                        else:
                            quotes_made += 1
                            logging.debug("> Quote created successfully.")
                            # create Quote_Client instance
                            try:
                                Quote_Client.create(quote_id=quote.quote_id, client_id=DEFAULT_CLIENT)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> Quote_Client error: {}".format(err))
                            else:
                                logging.debug(("> Quote_Client created " "successfully."))
                            # create Quote_Executive instance
                            try:
                                Quote_Executive.create(quote_id=quote.quote_id, executive_id=DEFAULT_EXECUTIVE)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> Quote_Executive error: {}".format(err))
                            else:
                                logging.debug(("> Quote_Executive created " "successfully."))
                            # create Quote_Finishing instance(s)
                            for finishing in finishings_list:
                                try:
                                    Quote_Finishing.create(quote_id=quote.quote_id, finishing_id=finishing)
                                except IntegrityError as err:
                                    errors = True  # rollback transaction
                                    logging.debug("> Quote_Finishing error: {}".format(err))
                                else:
                                    logging.debug(("> Quote_Finishing created " "successfully."))
                            # create Quote_Material instance(s)
                            for material in materials_list:
                                try:
                                    Quote_Material.create(quote_id=quote.quote_id, material_id=material)
                                except IntegrityError as err:
                                    errors = True  # rollback transaction
                                    logging.debug("> Quote_Material error: {}".format(err))
                                else:
                                    logging.debug(("> Quote_Material created " "successfully."))
                            # create Quote_Paper instance
                            try:
                                Quote_Paper.create(quote_id=quote.quote_id, paper_id=DEFAULT_PAPER)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> Quote_Paper error: {}".format(err))
                            else:
                                logging.debug(("> Quote_Paper created " "successfully."))
                            # create AuthorizedQuote instance
                            try:
                                auth_quote = AuthorizedQuote.create(quote_id=quote.quote_id)
                            except IntegrityError as err:
                                errors = True  # rollback transaction
                                logging.debug("> AuthorizedQuote error: {}".format(err))
                            else:
                                # authorize quote
                                quote.quote_is_authorized = True
                                # set total price
                                quote.quote_total_price = DEFAULT_PRICE
                                # set imposing
                                quote.quote_imposing_per_sheet = DEFAULT_IMPOSING
                                # save quote
                                quote.save()
                                logging.debug(("> Quote authorized " "successfully."))
                                # create ApprovedQuote instance
                                try:
                                    appr_quote = ApprovedQuote.create(
                                        authorized_quote_id=auth_quote.authorized_quote_id
                                    )
                                except IntegrityError as err:
                                    errors = True  # rollback transaction
                                    logging.debug("> ApprovedQuote error: {}".format(err))
                                else:
                                    # approve quote
                                    quote.quote_is_approved = True
                                    quote.save()
                                    # packaging
                                    # address to deliver
                                    # notes
                                    logging.debug(("> Quote approved " "successfully."))
                                    # create Order instance
                                    try:
                                        Order.create(approved_quote_id=appr_quote.approved_quote_id)
                                    except IntegrityError as err:
                                        errors = True  # rollback transaction
                                        logging.debug("> Order error: {}".format(err))
                                    else:
                                        # only if Quote made correctly
                                        if errors is False:
                                            orders_made += 1
                                        logging.debug(("> Order created " "successfully."))
                        # rollback if errors ocurred
                        if errors is True:
                            txn.rollback()

            # report quotes and orders made
            print("> Total lines: {}".format(total_lines))
            print("> Quotes made: {}".format(quotes_made))
            print("> Orders made: {}".format(orders_made))
            print("> Skipped {} lines.".format(len(skipped_lines)))
    except FileNotFoundError as err:
        print("> Error: {}".format(err))