def execute_atomic_purchase_write(self, mother_write_query, daughters_write_queries_attributes: [{}],
                                   other_update_stoke_queries: [], other_update_basket_queries: []):
     if not self.has_real_subject():
         return ret(False, self.__real_doesnt_exist_error_msg)
     if not self.__realSubject.is_connected():
         return ret(False, self.__real_doesnt_exist_error_msg)
     return self.__realSubject.execute_atomic_purchase_write(mother_write_query, daughters_write_queries_attributes,
                                                             other_update_stoke_queries, other_update_basket_queries)
 def execute(self, queries: []):
     with database.atomic() as transaction:  # Opens new transaction.
         try:
             for query in queries:
                 query.execute()
             return ret(True, "Successful.")
         except Exception as e:
             transaction.rollback()
             # print(e)
             return ret(False, "Failed.")
    def execute_atomic_purchase_write(self, mother_write_query, daughters_write_queries_attributes: [{}],
                                      other_update_stoke_queries: [], other_update_basket_queries: []):
        with database.atomic() as transaction:  # Opens new transaction.
            try:
                purchase_id = mother_write_query.execute()
                daughters_write_queries = []
                for query_args in daughters_write_queries_attributes:
                    query_args['purchase_id'] = purchase_id
                    daughters_write_queries.insert(len(daughters_write_queries), ProductsInPurchase.insert(query_args))

                queries = []
                for i in range(len(daughters_write_queries)):
                    queries.insert(len(queries), (other_update_stoke_queries[i], daughters_write_queries[i],
                                                  other_update_basket_queries[i]))
                for query in queries:
                    query[0].execute()
                    query[1].execute()
                    query[2].execute()
                return ret(True, "Successful.")
            except Exception as e:
                transaction.rollback()
                # print(e)
                return ret(False, "Failed.")
 def delete(self, tbl, where_expr: Expression):
     if not self.has_real_subject():
         return ret(False, self.__real_doesnt_exist_error_msg)
     if not self.__realSubject.is_connected():
         return ret(False, self.__real_doesnt_exist_error_msg)
     return self.__realSubject.delete(tbl, where_expr)
 def update(self, tbl, attributes_as_dictionary: {}, where_expr: Expression):
     if not self.has_real_subject():
         return ret(False, self.__real_doesnt_exist_error_msg)
     if not self.__realSubject.is_connected():
         return ret(False, self.__real_doesnt_exist_error_msg)
     return self.__realSubject.update(tbl, attributes_as_dictionary, where_expr)
 def write(self, tbl, attributes_as_dictionary: {}):
     if not self.has_real_subject():
         return ret(False, self.__real_doesnt_exist_error_msg)
     if not self.__realSubject.is_connected():
         return ret(False, self.__real_doesnt_exist_error_msg)
     return self.__realSubject.write(tbl, attributes_as_dictionary)
 def is_connected(self) -> bool:
     if not self.has_real_subject():
         return ret(False, self.__real_doesnt_exist_error_msg)
     return self.__realSubject.is_connected()
 def disconnect(self):
     if not self.has_real_subject():
         return ret(False, self.__real_doesnt_exist_error_msg)
     return self.__realSubject.disconnect()
 def execute(self, queries):
     if not self.has_real_subject():
         return ret(False, self.__real_doesnt_exist_error_msg)
     if not self.__realSubject.is_connected():
         return ret(False, self.__real_doesnt_exist_error_msg)
     return self.__realSubject.execute(queries)
    def init_system():
        # Getting the file path
        abs_path = os.path.dirname(os.path.abspath(__file__))
        # rel_path = os.path.join(abs_path, 'init_sys_file_v3.txt')
        rel_path = os.path.join(abs_path, 'init_sys_file_v4.txt')
        if rel_path.split(".")[1] != "txt":
            print("Wrong format.")
            exit(1)
        rel_path = rel_path

        # init important vars
        delimiter = "//"
        funcs_as_dictionary = {
            "register":
            GuestRole.register,
            "login":
            GuestRole.login,
            "logout":
            SubscriberRole.logout,
            "display_stores":
            GuestRole.display_stores,
            "add_system_manager":
            SystemManagerRole.add_system_manager,
            "open_store":
            TradeControlService.open_store,
            # "open_store": SubscriberRole.open_store,
            "add_products":
            StoreOwnerOrManagerRole.add_products,
            "appoint_store_manager":
            StoreOwnerOrManagerRole.appoint_store_manager,
            # Todo: test the below funcs.
            "display_stores_or_products_info":
            GuestRole.display_stores_or_products_info,
            "search_products_by":
            GuestRole.search_products_by,
            "filter_products_by":
            GuestRole.filter_products_by,
            "save_products_to_basket":
            GuestRole.save_products_to_basket,
            "view_shopping_cart":
            GuestRole.view_shopping_cart,
            "update_shopping_cart":
            GuestRole.update_shopping_cart,
            "purchase_products":
            GuestRole.purchase_products,
            "purchase_basket":
            GuestRole.purchase_basket,
            "confirm_payment":
            GuestRole.confirm_payment,
            "remove_products":
            StoreOwnerOrManagerRole.remove_products,
            "edit_product":
            StoreOwnerOrManagerRole.edit_product,
            "appoint_additional_owner":
            StoreOwnerOrManagerRole.appoint_additional_owner,
            "remove_owner":
            StoreOwnerOrManagerRole.remove_owner,
            "get_manager_permissions":
            StoreOwnerOrManagerRole.get_manager_permissions,
            "get_appointees":
            StoreOwnerOrManagerRole.get_appointees,
            "remove_manager":
            StoreOwnerOrManagerRole.remove_manager,
            "display_store_purchases":
            StoreOwnerOrManagerRole.display_store_purchases,
            "close_store":
            StoreOwnerOrManagerRole.close_store,
            "get_purchase_operator":
            StoreOwnerOrManagerRole.get_purchase_operator,
            "set_purchase_operator":
            StoreOwnerOrManagerRole.set_purchase_operator,
            "get_policies":
            StoreOwnerOrManagerRole.get_policies,
            "update_purchase_policy":
            StoreOwnerOrManagerRole.update_purchase_policy,
            "define_purchase_policy":
            StoreOwnerOrManagerRole.define_purchase_policy,
            "update_discount_policy":
            StoreOwnerOrManagerRole.update_discount_policy,
            "define_discount_policy":
            StoreOwnerOrManagerRole.define_discount_policy,
            "define_composite_policy":
            StoreOwnerOrManagerRole.define_composite_policy,
            "get_discount_policy":
            StoreOwnerOrManagerRole.get_discount_policy,
            "delete_policy":
            StoreOwnerOrManagerRole.delete_policy,
            "get_managed_stores":
            StoreOwnerOrManagerRole.get_managed_stores,
            "view_user_purchase_history":
            SystemManagerRole.view_user_purchase_history,
            "view_personal_purchase_history":
            SubscriberRole.view_personal_purchase_history,
            "view_store_purchases_history":
            SystemManagerRole.view_store_purchases_history
        }

        types_lst = [
            literal_eval, TradeControlService.convert_to_datetime, int, float,
            str
        ]

        # Open file for validation of functions.
        file = open(rel_path, "rt")
        for line in file:
            func_blueprints = line.split(delimiter)
            if func_blueprints[0].replace(
                    "\n", "").lower() not in funcs_as_dictionary.keys():
                return ret(
                    False,
                    "Action doesn't exist. Please check the input format.")
        file.close()

        # Open file for executing the commands
        file = open(rel_path, "rt")
        try:
            for unedited_line in file:
                line = unedited_line.replace("\n", "")
                # Separating func_name, arg1, arg2...
                func_blueprints = line.split(delimiter)
                func = funcs_as_dictionary[func_blueprints[0].lower()]
                # Two strategies - if function have arguments, and if doesn't
                if len(func_blueprints) > 1:
                    # Getting the list of args
                    args = []
                    for j in range(1, len(func_blueprints)):
                        args.insert(len(args), func_blueprints[j])
                    # Converting str args to correct type
                    args_after_validating = []
                    for arg in args:
                        for typ in types_lst:
                            try:
                                arg_after_validation = typ(arg)
                                args_after_validating.insert(
                                    len(args_after_validating),
                                    arg_after_validation)
                                break
                            except Exception:
                                pass
                    # Execute the func
                    func_return_value = func(*(tuple(args_after_validating)))
                    # If failed, return false/None and msg.
                    if type(func_return_value['response']) is bool:
                        if not func_return_value['response']:
                            file.close()
                            return func_return_value
                    else:
                        if func_return_value['response'] is None:
                            file.close()
                            return func_return_value
                else:
                    # If the func doesn't have args, just execute it.
                    func_return_value = func()
                    # If failed, return false/None and msg.
                    if type(func_return_value['response']) is bool:
                        if not func_return_value['response']:
                            file.close()
                            return func_return_value
                    else:
                        if func_return_value['response'] is None:
                            file.close()
                            return func_return_value
        except Exception as ex:
            # print(ex)
            file.close()
            # TODO - THE BUG
            return ret(
                False,
                "An unknown error has occurred. Please check the input file arguments."
            )

        # connecting to external systems.
        if not DeliveryProxy.get_instance().is_connected():
            return {
                'response': False,
                'msg':
                "Init system failed! connection to delivery system failed"
            }
        if not PaymentProxy.get_instance().is_connected():
            return {
                'response': False,
                'msg':
                "Init system failed! connection to delivery system failed"
            }

        file.close()
        return ret(True, "Init Done. Welcome to the new Amazon!")