Beispiel #1
0
def ils_sync_stock_data(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    domain = config.domain
    endpoint = ILSGatewayEndpoint.from_config(config)
    apis = get_ilsgateway_data_migrations()
    stock_data_task.delay(domain, endpoint, apis, config, ILS_FACILITIES)
    return HttpResponse('OK')
Beispiel #2
0
def update_historical_data(domain, locations=None):
    """
    If we don't have a record of this supply point being updated, run
    through all historical data and just fill in with zeros.
    """
    org_summaries = OrganizationSummary.objects.order_by('date')
    if org_summaries.count() == 0:
        return

    start_date = org_summaries[0].date

    if locations is None:
        if not ILSGatewayConfig.for_domain(domain).all_stock_data:
            locations = _get_test_locations(domain)
        else:
            locations = Location.by_domain(domain)

    for sp in locations:
        try:
            SupplyPointWarehouseRecord.objects.get(supply_point=sp._id)
        except SupplyPointWarehouseRecord.DoesNotExist:
            # we didn't have a record so go through and historically update
            # anything we maybe haven't touched
            for year, month in months_between(start_date, sp.sql_location.created_at):
                window_date = datetime(year, month, 1)
                for cls in [OrganizationSummary, ProductAvailabilityData, GroupSummary]:
                    _init_warehouse_model(cls, sp, window_date)
            SupplyPointWarehouseRecord.objects.create(supply_point=sp._id,
                                                      create_date=datetime.utcnow())
Beispiel #3
0
def update_historical_data(domain, locations=None):
    """
    If we don't have a record of this supply point being updated, run
    through all historical data and just fill in with zeros.
    """
    org_summaries = OrganizationSummary.objects.order_by('date')
    if org_summaries.count() == 0:
        return

    start_date = org_summaries[0].date

    if locations is None:
        if not ILSGatewayConfig.for_domain(domain).all_stock_data:
            locations = _get_test_locations(domain)
        else:
            locations = Location.by_domain(domain)

    for sp in locations:
        try:
            SupplyPointWarehouseRecord.objects.get(supply_point=sp._id)
        except SupplyPointWarehouseRecord.DoesNotExist:
            # we didn't have a record so go through and historically update
            # anything we maybe haven't touched
            for year, month in months_between(start_date,
                                              sp.sql_location.created_at):
                window_date = datetime(year, month, 1)
                for cls in [
                        OrganizationSummary, ProductAvailabilityData,
                        GroupSummary
                ]:
                    _init_warehouse_model(cls, sp, window_date)
            SupplyPointWarehouseRecord.objects.create(
                supply_point=sp._id, create_date=datetime.utcnow())
Beispiel #4
0
def handle(verified_contact, text, msg=None):
    user = verified_contact.owner if verified_contact else None
    domain = user.domain

    if domain and not ILSGatewayConfig.for_domain(domain):
        return False

    args = text.split()
    if not args:
        return False
    keyword = args[0]
    args = args[1:]
    params = {
        'user': user,
        'domain': domain,
        'args': args,
        'msg': msg,
        'verified_contact': verified_contact
    }

    def not_function(word):
        if args and re.match("del", word):
            return NotDeliveredHandler
        elif args and re.match("sub", word):
            return NotSubmittedHandler
        return None

    handlers = {
        ('soh', 'hmk'): SOHHandler,
        ('submitted', 'nimetuma'): RandrHandler,
        ('delivered', 'dlvd', 'nimepokea'): DeliveredHandler,
        ('sijapokea',): NotDeliveredHandler,
        ('sijatuma',): NotSubmittedHandler,
        ('supervision', 'usimamizi'): SupervisionHandler,
        ('arrived', 'aliwasili'): ArrivedHandler,
        ('help', 'msaada'): HelpHandler,
        ('language', 'lang', 'lugha'): LanguageHandler,
        ('stop', 'acha', 'hapo'): StopHandler,
        ('yes', 'ndio', 'ndyo'): YesHandler,
        ('register', 'reg', 'join', 'sajili'): RegisterHandler,
        ('test',): MessageInitiatior,
        ('not',): not_function(args[0]) if args else None
    }

    def choose_handler(keyword):
        for k, v in handlers.iteritems():
            if keyword in k:
                return v
        return None

    handler_class = choose_handler(keyword)
    handler = handler_class(**params) if handler_class else None

    if handler:
        if args:
            handler.handle()
        else:
            handler.help()
    return False
Beispiel #5
0
def populate_report_data(start_date,
                         end_date,
                         domain,
                         runner,
                         locations=None,
                         strict=True):
    # first populate all the warehouse tables for all facilities
    # hard coded to know this is the first date with data
    start_date = max(start_date, default_start_date())

    # For QA purposes generate reporting data for only some small part of data.
    if not ILSGatewayConfig.for_domain(domain).all_stock_data:
        if locations is None:
            locations = _get_test_locations(domain)
        facilities = filter(
            lambda location: location.location_type == 'FACILITY', locations)
        non_facilities_types = ['DISTRICT', 'REGION', 'MSDZONE', 'MOHSW']
        non_facilities = []
        for location_type in non_facilities_types:
            non_facilities.extend(
                filter(
                    lambda location: location.location_type == location_type,
                    locations))
    else:
        facilities = Location.filter_by_type(domain, 'FACILITY')
        non_facilities = list(Location.filter_by_type(domain, 'DISTRICT'))
        non_facilities += list(Location.filter_by_type(domain, 'REGION'))
        non_facilities += list(Location.filter_by_type(domain, 'MSDZONE'))
        non_facilities += list(Location.filter_by_type(domain, 'MOHSW'))

    if runner.location:
        if runner.location.location_type.name.upper() != 'FACILITY':
            facilities = []
            non_facilities = itertools.dropwhile(
                lambda location: location.location_id != runner.location.
                location_id, non_facilities)
        else:
            facilities = itertools.dropwhile(
                lambda location: location.location_id != runner.location.
                location_id, facilities)

    facilities_chunked_list = chunked(facilities, 5)
    for chunk in facilities_chunked_list:
        res = chain(
            process_facility_warehouse_data.si(fac, start_date, end_date,
                                               runner) for fac in chunk)()
        res.get()

    non_facilities_chunked_list = chunked(non_facilities, 50)

    # then populate everything above a facility off a warehouse table
    for chunk in non_facilities_chunked_list:
        res = chain(
            process_non_facility_warehouse_data.si(
                org, start_date, end_date, runner, strict) for org in chunk)()
        res.get()

    runner.location = None
    runner.save()
Beispiel #6
0
 def page_context(self):
     context = super(ILSConfigView, self).page_context
     context['oneoff_tasks'] = OneOffTaskProgress.objects.filter(domain=self.domain)
     ils_config = ILSGatewayConfig.for_domain(self.domain)
     enabled = False
     if ils_config:
         enabled = ils_config.enabled
     context['form'] = ILSConfigForm(initial={'enabled': enabled})
     return context
Beispiel #7
0
 def page_context(self):
     context = super(ILSConfigView, self).page_context
     context['oneoff_tasks'] = OneOffTaskProgress.objects.filter(domain=self.domain)
     ils_config = ILSGatewayConfig.for_domain(self.domain)
     enabled = False
     if ils_config:
         enabled = ils_config.enabled
     context['form'] = ILSConfigForm(initial={'enabled': enabled})
     return context
Beispiel #8
0
    def settings_context(self):
        config = ILSGatewayConfig.for_domain(self.domain_object.name)

        if config:
            return {
                "source_config": config._doc,
            }
        else:
            return {"source_config": ILSGatewayConfig()._doc}
Beispiel #9
0
def fix_stock_data(domain):
    start_date = '2015-07-01'
    end_date = StockDataCheckpoint.objects.get(domain=domain).date.strftime('%Y-%m-%d')
    with connection.cursor() as c:
        c.execute(
            'DELETE FROM ilsgateway_supplypointstatus WHERE location_id IN '
            '(SELECT location_id FROM locations_sqllocation WHERE domain=%s) AND status_date BETWEEN %s AND %s',
            [domain, start_date, end_date]
        )

        c.execute(
            'DELETE FROM ilsgateway_deliverygroupreport WHERE location_id IN '
            '(SELECT location_id FROM locations_sqllocation WHERE domain=%s) AND report_date BETWEEN %s AND %s',
            [domain, start_date, end_date]
        )

        c.execute(
            "DELETE FROM ilsgateway_groupsummary WHERE org_summary_id IN "
            "(SELECT id FROM ilsgateway_organizationsummary WHERE location_id IN "
            "(SELECT location_id FROM locations_sqllocation WHERE domain=%s) AND date BETWEEN %s AND %s)",
            [domain, start_date, end_date]
        )

        c.execute(
            "DELETE FROM ilsgateway_organizationsummary WHERE location_id IN "
            "(SELECT location_id FROM locations_sqllocation WHERE domain=%s AND date BETWEEN %s AND %s)",
            [domain, start_date, end_date]
        )

    config = ILSGatewayConfig.for_domain(domain)
    endpoint = ILSGatewayEndpoint.from_config(config)

    filters = {'status_date__gte': start_date, 'status_date__lte': end_date}

    offset = 0
    _, statuses = endpoint.get_supplypointstatuses(domain, filters=filters, limit=1000, offset=offset)
    while statuses:
        for status in statuses:
            try:
                SupplyPointStatus.objects.get(external_id=status.external_id, location_id=status.location_id)
            except SupplyPointStatus.DoesNotExist:
                status.save()
        offset += 1000
        _, statuses = endpoint.get_supplypointstatuses(domain, filters=filters, limit=1000, offset=offset)

    filters = {'report_date__gte': start_date, 'report_date__lte': end_date}

    offset = 0
    _, reports = endpoint.get_deliverygroupreports(domain, filters=filters, limit=1000, offset=offset)
    while reports:
        for report in reports:
            try:
                DeliveryGroupReport.objects.get(external_id=report.external_id, location_id=report.location_id)
            except DeliveryGroupReport.DoesNotExist:
                report.save()
        offset += 1000
        _, reports = endpoint.get_deliverygroupreports(domain, filters=filters, limit=1000, offset=offset)
Beispiel #10
0
 def tearDownClass(cls):
     MobileBackend.load_by_name(TEST_DOMAIN, TEST_BACKEND).delete()
     CommCareUser.get_by_username('stella').delete()
     CommCareUser.get_by_username('bella').delete()
     CommCareUser.get_by_username('trella').delete()
     CommCareUser.get_by_username('msd_person').delete()
     for product in Product.by_domain(TEST_DOMAIN):
         product.delete()
     SQLProduct.objects.all().delete()
     ILSGatewayConfig.for_domain(TEST_DOMAIN).delete()
     DocDomainMapping.objects.all().delete()
     Location.by_site_code(TEST_DOMAIN, 'loc1').delete()
     Location.by_site_code(TEST_DOMAIN, 'loc2').delete()
     Location.by_site_code(TEST_DOMAIN, 'dis1').delete()
     Location.by_site_code(TEST_DOMAIN, 'reg1').delete()
     Location.by_site_code(TEST_DOMAIN, 'moh1').delete()
     SQLLocation.objects.all().delete()
     generator.delete_all_subscriptions()
     Domain.get_by_name(TEST_DOMAIN).delete()
Beispiel #11
0
 def tearDownClass(cls):
     MobileBackend.load_by_name(TEST_DOMAIN, TEST_BACKEND).delete()
     CommCareUser.get_by_username('stella').delete()
     CommCareUser.get_by_username('bella').delete()
     CommCareUser.get_by_username('trella').delete()
     CommCareUser.get_by_username('msd_person').delete()
     for product in Product.by_domain(TEST_DOMAIN):
         product.delete()
     SQLProduct.objects.all().delete()
     ILSGatewayConfig.for_domain(TEST_DOMAIN).delete()
     DocDomainMapping.objects.all().delete()
     Location.by_site_code(TEST_DOMAIN, 'loc1').delete()
     Location.by_site_code(TEST_DOMAIN, 'loc2').delete()
     Location.by_site_code(TEST_DOMAIN, 'dis1').delete()
     Location.by_site_code(TEST_DOMAIN, 'reg1').delete()
     Location.by_site_code(TEST_DOMAIN, 'moh1').delete()
     SQLLocation.objects.all().delete()
     generator.delete_all_subscriptions()
     Domain.get_by_name(TEST_DOMAIN).delete()
Beispiel #12
0
    def settings_context(self):
        config = ILSGatewayConfig.for_domain(self.domain_object.name)

        if config:
            return {
                "source_config": config._doc,
            }
        else:
            return {
                "source_config": ILSGatewayConfig()._doc
            }
Beispiel #13
0
def stock_data_task(domain):
    ilsgateway_config = ILSGatewayConfig.for_domain(domain)
    domain = ilsgateway_config.domain
    endpoint = ILSGatewayEndpoint.from_config(ilsgateway_config)
    commtrack_settings_sync(domain)
    for product in endpoint.get_products():
        sync_ilsgateway_product(domain, product)
    get_locations(domain, endpoint)
    get_product_stock(domain, endpoint)
    get_stock_transaction(domain, endpoint)
    get_supply_point_statuses(domain, endpoint)
    get_delivery_group_reports(domain, endpoint)
Beispiel #14
0
def populate_report_data(start_date, end_date, domain, runner, locations=None, strict=True):
    # first populate all the warehouse tables for all facilities
    # hard coded to know this is the first date with data
    start_date = max(start_date, default_start_date())

    # For QA purposes generate reporting data for only some small part of data.
    if not ILSGatewayConfig.for_domain(domain).all_stock_data:
        if locations is None:
            locations = _get_test_locations(domain)
        facilities = filter(lambda location: location.location_type == 'FACILITY', locations)
        non_facilities_types = ['DISTRICT', 'REGION', 'MSDZONE', 'MOHSW']
        non_facilities = []
        for location_type in non_facilities_types:
            non_facilities.extend(filter(lambda location: location.location_type == location_type, locations))
    else:
        facilities = Location.filter_by_type(domain, 'FACILITY')
        non_facilities = list(Location.filter_by_type(domain, 'DISTRICT'))
        non_facilities += list(Location.filter_by_type(domain, 'REGION'))
        non_facilities += list(Location.filter_by_type(domain, 'MSDZONE'))
        non_facilities += list(Location.filter_by_type(domain, 'MOHSW'))

    if runner.location:
        if runner.location.location_type.name.upper() != 'FACILITY':
            facilities = []
            non_facilities = itertools.dropwhile(
                lambda location: location._id != runner.location.location_id,
                non_facilities
            )
        else:
            facilities = itertools.dropwhile(
                lambda location: location._id != runner.location.location_id,
                facilities
            )

    facilities_chunked_list = chunked(facilities, 5)
    for chunk in facilities_chunked_list:
        res = chain(process_facility_warehouse_data.si(fac, start_date, end_date, runner) for fac in chunk)()
        res.get()

    non_facilities_chunked_list = chunked(non_facilities, 50)

    # then populate everything above a facility off a warehouse table
    for chunk in non_facilities_chunked_list:
        res = chain(
            process_non_facility_warehouse_data.si(org, start_date, end_date, runner, strict)
            for org in chunk
        )()
        res.get()
    runner.location = None
    runner.save()
    # finally go back through the history and initialize empty data for any
    # newly created facilities
    update_historical_data(domain)
Beispiel #15
0
def ils_sync_stock_data(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    domain = config.domain
    endpoint = ILSGatewayEndpoint.from_config(config)
    apis = (
        ('product_stock', get_product_stock),
        ('stock_transaction', get_stock_transaction),
        ('supply_point_status', get_supply_point_statuses),
        ('delivery_group', get_delivery_group_reports)
    )
    stock_data_task.delay(domain, endpoint, apis, ILS_FACILITIES)
    return HttpResponse('OK')
Beispiel #16
0
def ils_clear_stock_data_task(domain):
    assert ILSGatewayConfig.for_domain(domain)
    locations = SQLLocation.objects.filter(domain=domain)
    SupplyPointStatus.objects.filter(location_id__in=locations.values_list('location_id', flat=True)).delete()
    DeliveryGroupReport.objects.filter(location_id__in=locations.values_list('location_id', flat=True)).delete()
    products = Product.ids_by_domain(domain)
    StockState.objects.filter(product_id__in=products).delete()
    StockTransaction.objects.filter(
        case_id__in=locations.exclude(supply_point_id__isnull=True).values_list('supply_point_id', flat=True)
    ).delete()
    StockReport.objects.filter(domain=domain).delete()
    StockDataCheckpoint.objects.filter(domain=domain).delete()
    def handle(self, domain, *args, **options):
        if len(args) == 1:
            ilsgateway_id = args[0]
        else:
            ilsgateway_id = 1166  # defaults to bondenzi: http://ilsgateway.com/tz/facility/1166/

        # monkey patch the default start date to cover less data
        updater.default_start_date = lambda: datetime(2015, 1, 1)
        config = ILSGatewayConfig.for_domain(domain)
        assert config.enabled, 'ilsgateway sync must be configured for this domain'
        locations = _get_locations_from_ilsgateway_id(domain, ilsgateway_id)
        _clear_data(domain)
        report_run(domain, locations, strict=False)
Beispiel #18
0
    def post(self, request, *args, **kwargs):
        ils_config = ILSGatewayConfig.for_domain(self.domain)
        ils_config_form = ILSConfigForm(request.POST)
        if not ils_config_form.is_valid():
            return self.get(request, *args, **kwargs)

        enabled = ils_config_form.cleaned_data['enabled']
        if not ils_config and enabled:
            ils_config = ILSGatewayConfig(enabled=True, domain=self.domain)
            ils_config.save()
        elif ils_config and ils_config.enabled != enabled:
            ils_config.enabled = enabled
            ils_config.save()
        return self.get(request, *args, **kwargs)
Beispiel #19
0
    def post(self, request, *args, **kwargs):
        ils_config = ILSGatewayConfig.for_domain(self.domain)
        ils_config_form = ILSConfigForm(request.POST)
        if not ils_config_form.is_valid():
            return self.get(request, *args, **kwargs)

        enabled = ils_config_form.cleaned_data['enabled']
        if not ils_config and enabled:
            ils_config = ILSGatewayConfig(enabled=True, domain=self.domain)
            ils_config.save()
        elif ils_config and ils_config.enabled != enabled:
            ils_config.enabled = enabled
            ils_config.save()
        return self.get(request, *args, **kwargs)
    def handle(self, domain, *args, **options):
        if len(args) == 1:
            ilsgateway_id = args[0]
        else:
            ilsgateway_id = 1166  # defaults to bondenzi: http://ilsgateway.com/tz/facility/1166/

        # cleanup
        _cleanup_existing_data(domain, ilsgateway_id)

        # migrate
        config = ILSGatewayConfig.for_domain(domain)
        assert config.enabled, 'ilsgateway sync must be configured for this domain'
        endpoint = ILSGatewayEndpoint.from_config(config)
        stock_data_task(domain, endpoint, get_ilsgateway_data_migrations(), config,
                        test_facilities=[ilsgateway_id])
    def handle(self, domain, *args, **options):
        if len(args) == 1:
            ilsgateway_id = args[0]
        else:
            ilsgateway_id = 1166  # defaults to bondenzi: http://ilsgateway.com/tz/facility/1166/

        # cleanup
        _cleanup_existing_data(domain, ilsgateway_id)

        # migrate
        config = ILSGatewayConfig.for_domain(domain)
        assert config.enabled, 'ilsgateway sync must be configured for this domain'
        endpoint = ILSGatewayEndpoint.from_config(config)
        stock_data_task(domain, endpoint, get_ilsgateway_data_migrations(), config,
                        test_facilities=[ilsgateway_id])
Beispiel #22
0
def populate_report_data(start_date, end_date, domain, runner, locations=None, strict=True):
    # first populate all the warehouse tables for all facilities
    # hard coded to know this is the first date with data
    start_date = max(start_date, default_start_date())

    # For QA purposes generate reporting data for only some small part of data.
    if not ILSGatewayConfig.for_domain(domain).all_stock_data:
        if locations is None:
            locations = _get_test_locations(domain)
        facilities = filter(lambda location: location.location_type == "FACILITY", locations)
        non_facilities_types = ["DISTRICT", "REGION", "MSDZONE", "MOHSW"]
        non_facilities = []
        for location_type in non_facilities_types:
            non_facilities.extend(filter(lambda location: location.location_type == location_type, locations))
    else:
        facilities = Location.filter_by_type(domain, "FACILITY")
        non_facilities = list(Location.filter_by_type(domain, "DISTRICT"))
        non_facilities += list(Location.filter_by_type(domain, "REGION"))
        non_facilities += list(Location.filter_by_type(domain, "MSDZONE"))
        non_facilities += list(Location.filter_by_type(domain, "MOHSW"))

    if runner.location:
        if runner.location.location_type.name.upper() != "FACILITY":
            facilities = []
            non_facilities = itertools.dropwhile(
                lambda location: location.location_id != runner.location.location_id, non_facilities
            )
        else:
            facilities = itertools.dropwhile(
                lambda location: location.location_id != runner.location.location_id, facilities
            )

    facilities_chunked_list = chunked(facilities, 5)
    for chunk in facilities_chunked_list:
        res = chain(process_facility_warehouse_data.si(fac, start_date, end_date, runner) for fac in chunk)()
        res.get()

    non_facilities_chunked_list = chunked(non_facilities, 50)

    # then populate everything above a facility off a warehouse table
    for chunk in non_facilities_chunked_list:
        res = chain(
            process_non_facility_warehouse_data.si(org, start_date, end_date, runner, strict) for org in chunk
        )()
        res.get()

    runner.location = None
    runner.save()
Beispiel #23
0
    def tearDownClass(cls):
        delete_domain_phone_numbers(TEST_DOMAIN)
        if cls.sms_backend_mapping.id is not None:
            cls.sms_backend_mapping.delete()
        if cls.sms_backend.id is not None:
            cls.sms_backend.delete()
        users = get_user_docs_by_username([
            'stella',
            'bella',
            'trella',
            'msd_person',
        ])
        if users:
            CommCareUser.bulk_delete([
                CommCareUser.wrap_correctly(user)
                for user in users
            ])

        for product in Product.by_domain(TEST_DOMAIN):
            product.delete()
        SQLProduct.objects.all().delete()
        ils_gateway_config = ILSGatewayConfig.for_domain(TEST_DOMAIN)
        if ils_gateway_config:
            ils_gateway_config.delete()
        DocDomainMapping.objects.all().delete()
        for site_code in [
            'loc1',
            'loc2',
            'dis1',
            'reg1',
            'moh1',
        ]:
            location = cls.get_location_by_site_code(site_code)
            if location:
                location.delete()
        SQLLocation.objects.all().delete()
        test_domain = Domain.get_by_name(TEST_DOMAIN, strict=True)
        if test_domain:
            test_domain.delete()
        super(ILSTestScript, cls).tearDownClass()
Beispiel #24
0
    def tearDownClass(cls):
        delete_domain_phone_numbers(TEST_DOMAIN)
        if cls.sms_backend_mapping.id is not None:
            cls.sms_backend_mapping.delete()
        if cls.sms_backend.id is not None:
            cls.sms_backend.delete()
        users = get_user_docs_by_username([
            'stella',
            'bella',
            'trella',
            'msd_person',
        ])
        if users:
            CommCareUser.bulk_delete([
                CommCareUser.wrap_correctly(user)
                for user in users
            ])

        for product in Product.by_domain(TEST_DOMAIN):
            product.delete()
        SQLProduct.objects.all().delete()
        ils_gateway_config = ILSGatewayConfig.for_domain(TEST_DOMAIN)
        if ils_gateway_config:
            ils_gateway_config.delete()
        DocDomainMapping.objects.all().delete()
        for site_code in [
            'loc1',
            'loc2',
            'dis1',
            'reg1',
            'moh1',
        ]:
            location = cls.get_location_by_site_code(site_code)
            if location:
                location.delete()
        SQLLocation.objects.all().delete()
        test_domain = Domain.get_by_name(TEST_DOMAIN, strict=True)
        if test_domain:
            test_domain.delete()
        super(ILSTestScript, cls).tearDownClass()
Beispiel #25
0
 def tearDownClass(cls):
     delete_domain_phone_numbers(TEST_DOMAIN)
     if cls.sms_backend_mapping.id is not None:
         cls.sms_backend_mapping.delete()
     if cls.sms_backend.id is not None:
         cls.sms_backend.delete()
     for username in [
         'stella',
         'bella',
         'trella',
         'msd_person',
     ]:
         user = CommCareUser.get_by_username(username)
         if user:
             user.delete()
     for product in Product.by_domain(TEST_DOMAIN):
         product.delete()
     SQLProduct.objects.all().delete()
     ils_gateway_config = ILSGatewayConfig.for_domain(TEST_DOMAIN)
     if ils_gateway_config:
         ils_gateway_config.delete()
     DocDomainMapping.objects.all().delete()
     for site_code in [
         'loc1',
         'loc2',
         'dis1',
         'reg1',
         'moh1',
     ]:
         location = Location.by_site_code(TEST_DOMAIN, site_code)
         if location:
             location.delete()
     SQLLocation.objects.all().delete()
     generator.delete_all_subscriptions()
     test_domain = Domain.get_by_name(TEST_DOMAIN)
     if test_domain:
         test_domain.delete()
     super(ILSTestScript, cls).tearDownClass()
Beispiel #26
0
 def tearDownClass(cls):
     delete_domain_phone_numbers(TEST_DOMAIN)
     if cls.sms_backend_mapping.id is not None:
         cls.sms_backend_mapping.delete()
     if cls.sms_backend.id is not None:
         cls.sms_backend.delete()
     for username in [
         'stella',
         'bella',
         'trella',
         'msd_person',
     ]:
         user = CommCareUser.get_by_username(username)
         if user:
             user.delete()
     for product in Product.by_domain(TEST_DOMAIN):
         product.delete()
     SQLProduct.objects.all().delete()
     ils_gateway_config = ILSGatewayConfig.for_domain(TEST_DOMAIN)
     if ils_gateway_config:
         ils_gateway_config.delete()
     DocDomainMapping.objects.all().delete()
     for site_code in [
         'loc1',
         'loc2',
         'dis1',
         'reg1',
         'moh1',
     ]:
         location = Location.by_site_code(TEST_DOMAIN, site_code)
         if location:
             location.delete()
     SQLLocation.objects.all().delete()
     generator.delete_all_subscriptions()
     test_domain = Domain.get_by_name(TEST_DOMAIN)
     if test_domain:
         test_domain.delete()
     super(ILSTestScript, cls).tearDownClass()
Beispiel #27
0
def ils_sync_stock_data(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    domain = config.domain
    endpoint = ILSGatewayEndpoint.from_config(config)
    stock_data_task.delay(ILSStockDataSynchronization(domain, endpoint))
    return HttpResponse('OK')
Beispiel #28
0
def ils_resync_web_users(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    endpoint = ILSGatewayEndpoint.from_config(config)
    resync_web_users.delay(ILSGatewayAPI(domain=domain, endpoint=endpoint))
    return HttpResponse('OK')
Beispiel #29
0
 def all_stock_data(self):
     return ILSGatewayConfig.for_domain(self.domain).all_stock_data
Beispiel #30
0
def ils_sync_stock_data(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    domain = config.domain
    endpoint = ILSGatewayEndpoint.from_config(config)
    stock_data_task.delay(ILSStockDataSynchronization(domain, endpoint))
    return HttpResponse('OK')
Beispiel #31
0
def ils_bootstrap_domain_task(domain):
    ils_config = ILSGatewayConfig.for_domain(domain)
    return ils_bootstrap_domain(ILSGatewayAPI(domain, ILSGatewayEndpoint.from_config(ils_config)))
 def endpoint(self):
     return ILSGatewayEndpoint.from_config(ILSGatewayConfig.for_domain(self.domain))
Beispiel #33
0
def ils_bootstrap_domain_test_task(domain, endpoint):
    ils_config = ILSGatewayConfig.for_domain(domain)
    from custom.logistics.commtrack import bootstrap_domain
    return bootstrap_domain(ils_config, endpoint)
Beispiel #34
0
def bootstrap_domain_task(domain):
    ilsgateway_config = ILSGatewayConfig.for_domain(domain)
    return bootstrap_domain(ilsgateway_config)
Beispiel #35
0
 def all_stock_data(self):
     return ILSGatewayConfig.for_domain(self.domain).all_stock_data
Beispiel #36
0
def handle(verified_contact, text, msg):
    if verified_contact:
        user = verified_contact.owner
        domain = verified_contact.domain
    elif msg.domain:
        user = None
        domain = msg.domain
    else:
        return False

    if not ILSGatewayConfig.for_domain(domain):
        return False

    text = text.replace('\r', ' ').replace('\n', ' ').strip()
    args = text.split()
    if not args:
        return False
    keyword = args[0]

    if keyword.startswith('#'):
        return False

    args = args[1:]
    params = {
        'user': user,
        'domain': domain,
        'args': args,
        'msg': msg,
        'verified_contact': verified_contact
    }

    def not_function(word):
        if args and re.match("del", word):
            return NotDeliveredHandler
        elif args and re.match("sub", word):
            return NotSubmittedHandler
        return None

    handlers_for_unregistered_or_registered_users = {
        ('register', 'reg', 'join', 'sajili'): RegisterHandler,
    }

    handlers_for_registered_users = {
        ('help', 'msaada'): HelpHandler,
        ('language', 'lang', 'lugha'): LanguageHandler,
        ('stop', 'acha', 'hapo'): StopHandler,
        ('test', ): MessageInitiatior,
    }

    handlers_for_registered_users_with_location = {
        ('soh', 'hmk'): SOHHandler,
        ('delivered', 'dlvd', 'nimepokea'): DeliveredHandler,
        ('sijapokea', ): NotDeliveredHandler,
        ('sijatuma', ): NotSubmittedHandler,
        ('la', 'um'): LossAndAdjustment,
        ('stockout', 'hakuna'): StockoutHandler,
        ('not', ): not_function(args[0]) if args else None,
        ('trans', ): TransferHandler
    }

    if EMG_AND_REC_SMS_HANDLERS.enabled(domain):
        handlers_for_registered_users_with_location[(
            'emg', )] = EmergencyHandler
        handlers_for_registered_users_with_location[('rec', )] = ReceiptHandler

    handler_class = (choose_handler(
        keyword, handlers_for_unregistered_or_registered_users)
                     or choose_handler(keyword, handlers_for_registered_users)
                     or choose_handler(
                         keyword, handlers_for_registered_users_with_location))

    if (not user and handler_class not in list(
            handlers_for_unregistered_or_registered_users.values())):
        return True

    if (handler_class in list(
            handlers_for_registered_users_with_location.values())
            and (not user or not user.location_id)):
        return True

    handler = handler_class(**params) if handler_class else None
    if handler:
        if args:
            return handler.handle()
        else:
            return handler.help()
    elif keyword != 'l':
        with localize(verified_contact.owner.get_language_code()):
            send_sms_to_verified_number(verified_contact,
                                        six.text_type(CONTACT_SUPERVISOR))
        return True
Beispiel #37
0
def handle(verified_contact, text, msg=None):
    user = verified_contact.owner if verified_contact else None
    domain = user.domain

    if domain and not ILSGatewayConfig.for_domain(domain):
        return False

    text = text.replace('\r', ' ').replace('\n', ' ').strip()
    args = text.split()
    if not args:
        return False
    keyword = args[0]

    if keyword.startswith('#'):
        return False

    args = args[1:]
    params = {
        'user': user,
        'domain': domain,
        'args': args,
        'msg': msg,
        'verified_contact': verified_contact
    }

    def not_function(word):
        if args and re.match("del", word):
            return NotDeliveredHandler
        elif args and re.match("sub", word):
            return NotSubmittedHandler
        return None

    handlers = {
        ('arrived', 'aliwasili'): ArrivedHandler,
        ('help', 'msaada'): HelpHandler,
        ('language', 'lang', 'lugha'): LanguageHandler,
        ('stop', 'acha', 'hapo'): StopHandler,
        ('yes', 'ndio', 'ndyo'): YesHandler,
        ('register', 'reg', 'join', 'sajili'): RegisterHandler,
        ('test',): MessageInitiatior,
    }

    location_needed_handlers = {
        ('soh', 'hmk'): SOHHandler,
        ('submitted', 'nimetuma'): RandrHandler,
        ('delivered', 'dlvd', 'nimepokea'): DeliveredHandler,
        ('sijapokea',): NotDeliveredHandler,
        ('sijatuma',): NotSubmittedHandler,
        ('supervision', 'usimamizi'): SupervisionHandler,
        ('la', 'um'): LossAndAdjustment,
        ('stockout', 'hakuna'): StockoutHandler,
        ('not',): not_function(args[0]) if args else None,
        ('trans',): TransferHandler
    }

    if EMG_AND_REC_SMS_HANDLERS.enabled(domain):
        location_needed_handlers[('emg', )] = EmergencyHandler
        location_needed_handlers[('rec',)] = ReceiptHandler

    handler_class = choose_handler(keyword, location_needed_handlers)
    if handler_class and not user.location_id:
        return True

    if not handler_class:
        handler_class = choose_handler(keyword, handlers)

    handler = handler_class(**params) if handler_class else None
    if handler:
        if args:
            return handler.handle()
        else:
            return handler.help()
    elif keyword != 'l':
        with localize(verified_contact.owner.get_language_code()):
            send_sms_to_verified_number(verified_contact, unicode(CONTACT_SUPERVISOR))
        return True
Beispiel #38
0
def bootstrap_domain_task(domain):
    ilsgateway_config = ILSGatewayConfig.for_domain(domain)
    return bootstrap_domain(ilsgateway_config)
Beispiel #39
0
def handle(verified_contact, text, msg):
    if verified_contact:
        user = verified_contact.owner
        domain = verified_contact.domain
    elif msg.domain:
        user = None
        domain = msg.domain
    else:
        return False

    if not ILSGatewayConfig.for_domain(domain):
        return False

    text = text.replace('\r', ' ').replace('\n', ' ').strip()
    args = text.split()
    if not args:
        return False
    keyword = args[0]

    if keyword.startswith('#'):
        return False

    args = args[1:]
    params = {
        'user': user,
        'domain': domain,
        'args': args,
        'msg': msg,
        'verified_contact': verified_contact
    }

    def not_function(word):
        if args and re.match("del", word):
            return NotDeliveredHandler
        elif args and re.match("sub", word):
            return NotSubmittedHandler
        return None

    handlers_for_unregistered_or_registered_users = {
        ('register', 'reg', 'join', 'sajili'): RegisterHandler,
    }

    handlers_for_registered_users = {
        ('arrived', 'aliwasili'): ArrivedHandler,
        ('help', 'msaada'): HelpHandler,
        ('language', 'lang', 'lugha'): LanguageHandler,
        ('stop', 'acha', 'hapo'): StopHandler,
        ('yes', 'ndio', 'ndyo'): YesHandler,
        ('test',): MessageInitiatior,
    }

    handlers_for_registered_users_with_location = {
        ('soh', 'hmk'): SOHHandler,
        ('submitted', 'nimetuma'): RandrHandler,
        ('delivered', 'dlvd', 'nimepokea'): DeliveredHandler,
        ('sijapokea',): NotDeliveredHandler,
        ('sijatuma',): NotSubmittedHandler,
        ('supervision', 'usimamizi'): SupervisionHandler,
        ('la', 'um'): LossAndAdjustment,
        ('stockout', 'hakuna'): StockoutHandler,
        ('not',): not_function(args[0]) if args else None,
        ('trans',): TransferHandler
    }

    if EMG_AND_REC_SMS_HANDLERS.enabled(domain):
        handlers_for_registered_users_with_location[('emg',)] = EmergencyHandler
        handlers_for_registered_users_with_location[('rec',)] = ReceiptHandler

    handler_class = (
        choose_handler(keyword, handlers_for_unregistered_or_registered_users) or
        choose_handler(keyword, handlers_for_registered_users) or
        choose_handler(keyword, handlers_for_registered_users_with_location)
    )

    if (
        not user and
        handler_class not in list(handlers_for_unregistered_or_registered_users.values())
    ):
        return True

    if (
        handler_class in list(handlers_for_registered_users_with_location.values()) and
        (not user or not user.location_id)
    ):
        return True

    handler = handler_class(**params) if handler_class else None
    if handler:
        if args:
            return handler.handle()
        else:
            return handler.help()
    elif keyword != 'l':
        with localize(verified_contact.owner.get_language_code()):
            send_sms_to_verified_number(verified_contact, six.text_type(CONTACT_SUPERVISOR))
        return True
Beispiel #40
0
def ils_resync_passwords(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    endpoint = ILSGatewayEndpoint.from_config(config)
    resync_webusers_passwords_task.delay(config, endpoint)
    return HttpResponse('OK')
Beispiel #41
0
def handle(verified_contact, text, msg=None):
    user = verified_contact.owner if verified_contact else None
    domain = user.domain

    if domain and not ILSGatewayConfig.for_domain(domain):
        return False

    text = text.replace('\r', ' ').replace('\n', ' ').strip()
    args = text.split()
    if not args:
        return False
    keyword = args[0]

    if keyword.startswith('#'):
        return False

    args = args[1:]
    params = {
        'user': user,
        'domain': domain,
        'args': args,
        'msg': msg,
        'verified_contact': verified_contact
    }

    def not_function(word):
        if args and re.match("del", word):
            return NotDeliveredHandler
        elif args and re.match("sub", word):
            return NotSubmittedHandler
        return None

    handlers = {
        ('arrived', 'aliwasili'): ArrivedHandler,
        ('help', 'msaada'): HelpHandler,
        ('language', 'lang', 'lugha'): LanguageHandler,
        ('stop', 'acha', 'hapo'): StopHandler,
        ('yes', 'ndio', 'ndyo'): YesHandler,
        ('register', 'reg', 'join', 'sajili'): RegisterHandler,
        ('test',): MessageInitiatior,
    }

    location_needed_handlers = {
        ('soh', 'hmk'): SOHHandler,
        ('submitted', 'nimetuma'): RandrHandler,
        ('delivered', 'dlvd', 'nimepokea'): DeliveredHandler,
        ('sijapokea',): NotDeliveredHandler,
        ('sijatuma',): NotSubmittedHandler,
        ('supervision', 'usimamizi'): SupervisionHandler,
        ('la', 'um'): LossAndAdjustment,
        ('stockout', 'hakuna'): StockoutHandler,
        ('not',): not_function(args[0]) if args else None,
        ('trans',): TransferHandler
    }

    handler_class = choose_handler(keyword, location_needed_handlers)
    if handler_class and not user.location_id:
        return True

    if not handler_class:
        handler_class = choose_handler(keyword, handlers)

    handler = handler_class(**params) if handler_class else None

    if handler:
        if args:
            return handler.handle()
        else:
            return handler.help()
    elif keyword != 'l':
        with localize(verified_contact.owner.get_language_code()):
            send_sms_to_verified_number(verified_contact, unicode(CONTACT_SUPERVISOR))
        return True
Beispiel #42
0
def ils_sms_users_fix(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    endpoint = ILSGatewayEndpoint.from_config(config)
    sms_users_fix.delay(ILSGatewayAPI(domain=domain, endpoint=endpoint))
    return HttpResponse('OK')
Beispiel #43
0
 def endpoint(self):
     return ILSGatewayEndpoint.from_config(
         ILSGatewayConfig.for_domain(self.domain))
Beispiel #44
0
def ils_resync_web_users(request, domain):
    config = ILSGatewayConfig.for_domain(domain)
    endpoint = ILSGatewayEndpoint.from_config(config)
    resync_web_users.delay(ILSGatewayAPI(domain=domain, endpoint=endpoint))
    return HttpResponse('OK')
Beispiel #45
0
def handle(verified_contact, text, msg):
    if verified_contact:
        user = verified_contact.owner
        domain = verified_contact.domain
    elif msg.domain:
        user = None
        domain = msg.domain
    else:
        return False

    if not ILSGatewayConfig.for_domain(domain):
        return False

    text = text.replace("\r", " ").replace("\n", " ").strip()
    args = text.split()
    if not args:
        return False
    keyword = args[0]

    if keyword.startswith("#"):
        return False

    args = args[1:]
    params = {"user": user, "domain": domain, "args": args, "msg": msg, "verified_contact": verified_contact}

    def not_function(word):
        if args and re.match("del", word):
            return NotDeliveredHandler
        elif args and re.match("sub", word):
            return NotSubmittedHandler
        return None

    handlers_for_unregistered_or_registered_users = {("register", "reg", "join", "sajili"): RegisterHandler}

    handlers_for_registered_users = {
        ("arrived", "aliwasili"): ArrivedHandler,
        ("help", "msaada"): HelpHandler,
        ("language", "lang", "lugha"): LanguageHandler,
        ("stop", "acha", "hapo"): StopHandler,
        ("yes", "ndio", "ndyo"): YesHandler,
        ("test",): MessageInitiatior,
    }

    handlers_for_registered_users_with_location = {
        ("soh", "hmk"): SOHHandler,
        ("submitted", "nimetuma"): RandrHandler,
        ("delivered", "dlvd", "nimepokea"): DeliveredHandler,
        ("sijapokea",): NotDeliveredHandler,
        ("sijatuma",): NotSubmittedHandler,
        ("supervision", "usimamizi"): SupervisionHandler,
        ("la", "um"): LossAndAdjustment,
        ("stockout", "hakuna"): StockoutHandler,
        ("not",): not_function(args[0]) if args else None,
        ("trans",): TransferHandler,
    }

    if EMG_AND_REC_SMS_HANDLERS.enabled(domain):
        handlers_for_registered_users_with_location[("emg",)] = EmergencyHandler
        handlers_for_registered_users_with_location[("rec",)] = ReceiptHandler

    handler_class = (
        choose_handler(keyword, handlers_for_unregistered_or_registered_users)
        or choose_handler(keyword, handlers_for_registered_users)
        or choose_handler(keyword, handlers_for_registered_users_with_location)
    )

    if not user and handler_class not in handlers_for_unregistered_or_registered_users.values():
        return True

    if handler_class in handlers_for_registered_users_with_location.values() and (not user or not user.location_id):
        return True

    handler = handler_class(**params) if handler_class else None
    if handler:
        if args:
            return handler.handle()
        else:
            return handler.help()
    elif keyword != "l":
        with localize(verified_contact.owner.get_language_code()):
            send_sms_to_verified_number(verified_contact, unicode(CONTACT_SUPERVISOR))
        return True