Beispiel #1
0
    def load_user_data(self, callback: Optional[Callable] = None):

        if len(App.get_running_app().user_mapping) > 0:
            Logger.debug("StellaPayUI: Not loading user data again")
            return

        user_data = App.get_running_app().session_manager.do_get_request(url=Connections.get_users())

        Logger.debug("StellaPayUI: Loaded user data")

        App.get_running_app().user_mapping = {}

        if user_data and user_data.ok:
            # convert to json
            user_json = user_data.json()

            print(f"StellaPayUI: Loading user mapping on thread {threading.current_thread().name}")

            # append json to list and sort the list
            for user in user_json:
                # store all emails adressed in the sheet_menu
                App.get_running_app().user_mapping[user["name"]] = user["email"]

            # Sort items
            App.get_running_app().user_mapping = OrderedDict(
                sorted(App.get_running_app().user_mapping.items(), key=lambda x: x[0]))

            # Create dialog and its items on the main thread
            self.create_user_select_dialog(callback=callback)
        else:
            Logger.critical("StellaPayUI: Error: addresses could not be fetched from server")
            os._exit(1)
    def _start_app_as_slave(self):
        # from app::run
        if not self.mc.built:
            self.mc.load_config()
            self.mc.load_kv(filename=self.mc.kv_file)
            root = self.mc.build()
            if root:
                self.mc.root = root
        if self.mc.root:
            if not isinstance(self.mc.root, KivyWidget):
                Logger.critical('App.root must be an _instance_ of Kivy Widget')
                raise Exception('Invalid instance in App.root')
            from kivy.core.window import Window
            Window.add_widget(self.mc.root)

        # Check if the window is already created
        from kivy.base import EventLoop
        window = EventLoop.window
        if window:
            self.mc._app_window = window
            window.set_title(self.mc.get_application_name())
            icon = self.mc.get_application_icon()
            if icon:
                window.set_icon(icon)
            self.mc._install_settings_keys(window)
        else:
            Logger.critical("Application: No window is created."
                            " Terminating application run.")
            return

        self.mc.dispatch('on_start')
        runTouchApp(slave=True)  # change is here

        while not self.mc.is_init_done.is_set():
            EventLoop.idle()
Beispiel #3
0
    def load_categories_and_products(self):
        # Get all categories names
        response = App.get_running_app().session_manager.do_get_request(
            url=Connections.get_categories())

        Logger.debug("StellaPayUI: Loading product categories")

        # Check status response
        if response and response.ok:

            categories = response.json()

            Logger.debug(
                f"StellaPayUI: Retrieved {len(categories)} categories")

            # Load tab for each category
            for cat in categories:
                # Request products from category tab_text
                request = Connections.get_products() + cat['name']
                response = App.get_running_app(
                ).session_manager.do_get_request(request)

                Logger.debug(
                    f"StellaPayUI: Loading products for category '{cat['name']}'"
                )

                # Evaluate server response
                if response and response.ok:
                    # convert response to json
                    products_json = response.json()

                    self.products_per_category[cat['name']] = []

                    Logger.debug(
                        f"StellaPayUI: Retrieved {len(products_json)} products for category '{cat['name']}'"
                    )

                    # Create a product object for all
                    for product in products_json:
                        # Only add the product to the list if the product must be shown
                        if product['shown']:
                            p = Product().create_from_json(product)
                            self.products_per_category[cat['name']].append(p)
                else:
                    # Error in retrieving products from server
                    Logger.critical(
                        "StellaPayUI: Products could not be retrieved: " +
                        response.text)
                    os._exit(1)

            # If we loaded everything correctly, we can tell the startup screen we loaded correctly.
            screen_manager.get_screen(
                Screens.STARTUP_SCREEN.value).on_products_loaded()
        else:
            # Error
            Logger.critical(
                "StellaPayUI: Categories could not be retrieved: " +
                response.text)
            os._exit(1)
Beispiel #4
0
    def _start_app_as_slave(self):
        # from app::run
        if not self.mc.built:
            self.mc.load_config()
            self.mc.load_kv(filename=self.mc.kv_file)
            root = self.mc.build()
            if root:
                self.mc.root = root
        if self.mc.root:
            if not isinstance(self.mc.root, KivyWidget):
                Logger.critical(
                    'App.root must be an _instance_ of Kivy Widget')
                raise Exception('Invalid instance in App.root')
            from kivy.core.window import Window
            Window.add_widget(self.mc.root)

        # Check if the window is already created
        from kivy.base import EventLoop
        window = EventLoop.window
        if window:
            self.mc._app_window = window
            #window.set_title(self.mc.get_application_name() + self._testMethodName)
            icon = self.mc.get_application_icon()
            if icon:
                window.set_icon(icon)
            self.mc._install_settings_keys(window)
        else:
            Logger.critical("Application: No window is created."
                            " Terminating application run.")
            return

        self.mc.dispatch('on_start')
        runTouchApp(slave=True)  # change is here

        # Perform init process
        tries = 0
        while not self.mc.is_init_done.is_set(
        ) and not self.mc.thread_stopper.is_set():
            self.advance_time()
            sleep(.001)
            tries += 1
            if tries > 1000:
                self.fail("Test init took too long")

        # set a nice title
        window.set_title(self.__class__.__name__ + "::" + self._testMethodName)
Beispiel #5
0
    def create_static_database(self):
        # Connect to the database and return database connection object
        conn = None

        Logger.debug(f"StellaPayUI: Creating static fun fact database")

        # Create all tables and add the the database file
        try:
            conn = sqlite3.connect('db/static_fun_fact_database.db')
            print(sqlite3.version)

            # # SQLite command to create table with two fields, namely product and fun_fact
            static_fun_facts_table = "CREATE TABLE IF NOT EXISTS static_fun_facts(" \
                                     "product text NOT NULL, " \
                                     "fun_fact text PRIMARY KEY " \
                                     ");"
            #
            # one_day_fun_fact_table = "CREATE TABLE IF NOT EXISTS one_day_fun_fact(" \
            #                          "product text PRIMARY KEY " \
            #                          "fun_fact text PRIMARY KEY " \
            #                          ");"
            #
            # one_week_fun_fact_table = "CREATE TABLE IF NOT EXISTS one_week_fun_fact(" \
            #                           "product text PRIMARY KEY " \
            #                           "fun_fact text PRIMARY KEY " \
            #                           ");"
            #
            # one_month_fun_fact_table = "CREATE TABLE IF NOT EXISTS one_month_fun_fact(" \
            #                            "product text PRIMARY KEY " \
            #                            "fun_fact text PRIMARY KEY " \
            #                            ");"
            #

            # Create connection to the database and add the tables
            db_conn = conn.cursor()
            db_conn.execute(static_fun_facts_table)
            # db_conn.execute(one_day_fun_fact_table)
            # db_conn.execute(one_week_fun_fact_table)
            # db_conn.execute(one_month_fun_fact_table)

        except sqlite3.Error as e:
            Logger.critical("StellaPayUI: " + e)
            os._exit(1)

        self.connection = conn
Beispiel #6
0
    def on_confirm_payment(self, dt=None):
        print("OnClicked")
        # Serialize the shopping cart
        json_cart = self.shopping_cart.to_json()

        # use a POST-request to forward the shopping cart
        response = App.get_running_app().session_manager.do_post_request(
            url=Connections.create_transaction(), json_data=json_cart)

        if response and response.ok:
            # Reset instance variables
            self.end_user_session()

            if self.shopping_cart_dialog is not None:
                self.shopping_cart_dialog.dismiss()

            self.timeout_event.cancel()

            self.final_dialog = MDDialog(
                text="Gelukt! Je aankoop is geregistreerd",
                buttons=[
                    MDRaisedButton(text="Thanks", on_release=self.on_thanks),
                ])
            self.timeout_event = Clock.schedule_once(self.on_thanks, 5)
            self.final_dialog.open()
        elif not response.ok:
            # Reset instance variables
            self.end_user_session()

            if self.shopping_cart_dialog is not None:
                self.shopping_cart_dialog.dismiss()

            self.final_dialog = MDDialog(
                text=
                "Het is niet gelukt je aankoop te registreren. Herstart de app svp.",
                buttons=[
                    MDRaisedButton(text="Herstart", on_release=(os._exit(1))),
                ])
            self.final_dialog.open()
        else:
            Logger.critical("StellaPayUI: Payment could not be made: error: " +
                            response.content)
            os._exit(1)
Beispiel #7
0
    def enable_card_listener(self, card_type=AnyCardType()):
        # Check if resetting vars is required and if so, do so
        self.__reset_local_vars()

        try:
            # Setup a cardRequest: waiting infinitely for any card type
            self.__request = CardRequest(timeout=INFINITE, cardType=card_type)

            # Once a card is presented, initialize variables to setup connection
            self.__service = self.__request.waitforcard()
            self.__on_card_presented()
        except CardRequestTimeoutException as e:
            Logger.critical(
                "This should not happen: Timelimit reached for card presenting"
            )
            os._exit(1)
        except EstablishContextException as e2:
            # There is no smartcard reader found so we just ignore it.
            pass
    def register_card_mapping(self, selected_user_name,
                              selected_user_email: str):
        # Use a POST command to add connect this UID to the user
        request = App.get_running_app().session_manager.do_post_request(
            url=Connections.add_user_mapping(),
            json_data={
                'card_id': str(self.nfc_id),
                'email': selected_user_email
            })

        # If the users was added successfully ( status_code : 200), proceed to WelcomeScreen
        if request.ok:
            # Store the active user in the app so other screens can use it.
            App.get_running_app().active_user = selected_user_name
            self.manager.current = Screens.WELCOME_SCREEN.value
        else:
            # User could not be added succesfully, give error 2.
            Logger.critical(
                "StellaPayUI: Error " + str(request.status_code) +
                " occurred when trying to add the user: error message: " +
                request.text)
            os._exit(1)