コード例 #1
0
 def get_client(cls, quote_id):
     """Return the client associated with the given quote id."""
     return Quote_Client.get(Quote_Client.quote_id == quote_id)
コード例 #2
0
ファイル: read_ops.py プロジェクト: asapper/orders-project
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))