def __init__(self,
              payload_templates=None,
              app_configuraton=None,
              state="testing"):
     self.state = state
     self.payload_builder = PayloadBuilder(payload_templates,
                                           app_configuraton)
     self.available_companies = ParseConfiguration(app_configuraton) \
         .try_to_get_default_available_companies()
 def __init__(self, payload_templates=None, app_configuraton=None):
     self.configurator = ParseConfiguration(app_configuraton)
     self.default_company_id = self.configurator \
         .try_to_get_default_company_id()
     colppy_credentials = self.configurator \
         .get_colppy_credentials()
     self.payloads = PayloadBuilderConfigurator(payload_templates) \
         .get_configured_templates(colppy_credentials)
     self.session_key = None
 def __init__(self,
              spread,
              sheet=0,
              creds=None,
              create_sheet=False,
              conf_file=None):
     if creds:
         self.creds = creds
     else:
         credentials = ParseConfiguration(conf_file).get_google_creds()
         self.creds = get_creds(config=credentials)
     self.spread = Spread(spread,
                          sheet=sheet,
                          creds=self.creds,
                          create_sheet=create_sheet)
 def test_default_response_takes_default_file(self):
     explicit = ParseConfiguration("config/app_configuration.json")
     implicit = ParseConfiguration()
     self.assertEqual(explicit.config, implicit.config)
 def test_all_methods_run_on_normal_config(self):
     pc = ParseConfiguration("test/data/app_configuration_test.json")
     pc.try_to_get_default_company_id()
     pc.try_to_get_default_available_companies()
     pc.try_to_get_default_available_ccosts()
     pc.get_google_creds()
     pc.get_colppy_credentials()
 def test_no_available_ccosts(self):
     pc = ParseConfiguration("test/data/almost_empty_config.json")
     cc = pc.try_to_get_default_available_ccosts()
     self.assertEqual(cc, {})
 def test_no_company_id(self):
     pc = ParseConfiguration("test/data/almost_empty_config.json")
     id = pc.try_to_get_default_company_id()
     self.assertEqual(id, "")
 def test_raises_error_if_no_google_credentials(self):
     with self.assertRaises(KeyError):
         pc = ParseConfiguration("test/data/almost_empty_config.json")
         pc.get_google_creds()
 def test_raises_error_if_comp_id_incompatible_with_availables(self):
     with self.assertRaises(AssertionError):
         pc = ParseConfiguration("test/data/incompatible_company_config.json")
         pc.try_to_get_default_company_id()
 def test_raises_error_wrong_format_file(self):
     with self.assertRaises(ValueError):
         ParseConfiguration("test/data/file_with_format_error.json")
 def test_raises_error_non_existent_file_name(self):
     with self.assertRaises(FileNotFoundError):
         ParseConfiguration("test/data/non_existent.json")
class Caller():
    def __init__(self,
                 payload_templates=None,
                 app_configuraton=None,
                 state="testing"):
        self.state = state
        self.payload_builder = PayloadBuilder(payload_templates,
                                              app_configuraton)
        self.available_companies = ParseConfiguration(app_configuraton) \
            .try_to_get_default_available_companies()

    def get_invoices_for(self, dates_range=None, company_id=None):
        self.get_session_key()
        self.assert_company_is_available(company_id)
        invoices_payload_parameters = (dates_range, company_id,
                                       self.session_key)
        logger.info("Preparing invoices payload...")
        invoices_payload = self.payload_builder. \
            get_list_invoices_payload(*invoices_payload_parameters)
        logger.info("Payload ok.")
        logger.info("Getting invoices...")
        invoices_content = self.get_content_for_payload(invoices_payload)
        invoices_data = invoices_content["data"]
        logger.info("Got %d invoices." % len(invoices_data))
        return invoices_data

    def get_session_key(self):
        seconds_per_min = 60
        session_duration_in_mins = 25
        now = datetime.datetime.now()
        try:
            delta_mins = ((now - self.login_time).total_seconds() /
                          seconds_per_min)
            if delta_mins > session_duration_in_mins:
                self.login_and_set_session_key()
        except AttributeError:
            self.login_and_set_session_key()
        return self.session_key

    def login_and_set_session_key(self):
        open_session = self.login()
        self.session_key = open_session["data"]["claveSesion"]
        self.login_time = datetime.datetime.now()

    def login(self):
        login_payload = self.payload_builder.get_login_payload()
        logger.info("Trying to log into Colppy as %s..." % self.state)
        login_requester = RequestMaker(self.state)
        login_response = login_requester.get_response(login_payload,
                                                      request_type="post")
        login_content = ResponseParser(login_response).get_response_content()
        logger.info("Login OK.")
        return login_content

    def assert_company_is_available(self, company_id):
        if company_id:
            try:
                assert company_id in self.available_companies.values()
            except AssertionError:
                logger.info("Company not found in default available \
                            companies.")
                self.update_available_companies_and_recheck(company_id)

    def update_available_companies_and_recheck(self, company_id):
        logger.info("Updating companies to re-check...")
        self.update_available_companies()
        try:
            assert company_id in self.available_companies.values()
        except AssertionError:
            logger.exception("Company ID not in available companies.")
            logger.error("Available companies:")
            logger.error(self.available_companies)
            raise AssertionError

    def update_available_companies(self):
        self.available_companies = {}
        logger.info("Updating caller available companies...")
        try:
            for company in self.get_companies():
                company_id = company["IdEmpresa"]
                company_name = company["razonSocial"]
                self.available_companies[company_name] = company_id
            logger.info("Availables companies updated.")
        except KeyError:
            self.available_companies["Query Error"] = None
            logger.exception("Got these companies:")
            logger.error(self.available_companies)
            logger.error("Check keys for company id and name")

    def get_companies(self):
        self.get_session_key()
        logger.info("Preparing companies payload...")
        companies_payload = self.payload_builder \
            .get_list_companies_payload(self.session_key)
        logger.info("Payload ok.")
        logger.info("Getting companies...")
        companies_content = self.get_content_for_payload(companies_payload)
        companies_data = companies_content["data"]
        logger.info("Got %d companies." % len(companies_data))
        return companies_data

    def get_content_for_payload(self, payload):
        requester = RequestMaker(self.state)
        response = requester.get_response(payload)
        content = ResponseParser(response).get_response_content()
        return content

    def get_diary_for(self, dates_range=None, company_id=None):
        self.get_session_key()
        self.assert_company_is_available(company_id)
        diary_payload_parameters = (dates_range, company_id, self.session_key)
        logger.info("Preparing diary payload...")
        diary_payload = self.payload_builder \
            .get_list_diary_payload(*diary_payload_parameters)
        logger.info("Payload ok.")
        logger.info("Getting diary...")
        diary_content = self.get_content_for_payload(diary_payload)
        diary_data = diary_content["movimientos"]
        logger.info("Got %d diary movements." % len(diary_data))
        return diary_data

    def get_inventory_for(self, company_id=None):
        self.get_session_key()
        self.assert_company_is_available(company_id)
        inventory_payload_parameters = (company_id, self.session_key)
        logger.info("Preparing inventory payload...")
        inventory_payload = self.payload_builder \
            .get_list_inventory_payload(*inventory_payload_parameters)
        logger.info("Payload ok.")
        logger.info("Getting inventory...")
        inventory_content = self.get_content_for_payload(inventory_payload)
        inventory_data = inventory_content["data"]
        logger.info("Got %d items." % len(inventory_data))
        return inventory_data

    def get_deposits_stock_for(self, item_id, company_id=None):
        self.get_session_key()
        self.assert_company_is_available(company_id)
        deposit_payload_parameters = (item_id, company_id, self.session_key)
        logger.info("Preparing deposit payload...")
        deposit_payload = self.payload_builder \
            .get_list_deposits_stock_for_item_payload(*deposit_payload_parameters)
        logger.info("Payload ok.")
        logger.info("Getting deposits for %s..." % item_id)
        deposit_content = self.get_content_for_payload(deposit_payload)
        deposit_data = deposit_content["data"]
        logger.info("Got deposits.")
        return deposit_data

    def get_ccosts_for_type(self, ccost_type_1_or_2, company_id=None):
        self.get_session_key()
        self.assert_company_is_available(company_id)
        ccost_payload_parameters = (ccost_type_1_or_2, company_id,
                                    self.session_key)
        logger.info("Preparing ccost payload...")
        ccost_payload = self.payload_builder \
            .get_list_ccost_payload(*ccost_payload_parameters)
        logger.info("Payload ok.")
        logger.info("Getting dccost for type number %d..." % ccost_type_1_or_2)
        ccost_content = self.get_content_for_payload(ccost_payload)
        ccost_data = ccost_content["data"]
        logger.info("Got ccosts.")
        return ccost_data