def setUp(self): self.endpoint = MockEndpoint('http://test-api.com/', 'dummy', 'dummy') self.stock_api_object = MockEWSStockDataSynchronization(TEST_DOMAIN, self.endpoint) self.datapath = os.path.join(os.path.dirname(__file__), 'data') initial_bootstrap(TEST_DOMAIN) self.api_object = EWSApi(TEST_DOMAIN, self.endpoint) self.api_object.prepare_commtrack_config() config = EWSGhanaConfig() config.domain = TEST_DOMAIN config.enabled = True config.all_stock_data = True config.password = '******' config.username = '******' config.url = 'http://test-api.com/' config.save() l1 = Location( name='Test location 1', external_id='3445', location_type='Hospital', domain=TEST_DOMAIN ) l2 = Location( name='Test location 2', external_id='4407', location_type='Hospital', domain=TEST_DOMAIN ) l1.save() l2.save() with open(os.path.join(self.datapath, 'sample_products.json')) as f: for product_json in json.loads(f.read()): self.api_object.product_sync(Product(product_json))
def tearDownClass(cls): delete_domain_phone_numbers(TEST_DOMAIN) CommCareUser.get_by_username('stella').delete() CommCareUser.get_by_username('super').delete() FacilityInCharge.objects.all().delete() LocationType.objects.all().delete() for product in Product.by_domain(TEST_DOMAIN): product.delete() SQLProduct.objects.all().delete() EWSGhanaConfig.for_domain(TEST_DOMAIN).delete() DocDomainMapping.objects.all().delete() Domain.get_by_name(TEST_DOMAIN).delete() super(EWSScriptTest, cls).tearDownClass()
def tearDownClass(cls): MobileBackend.load_by_name(TEST_DOMAIN, TEST_BACKEND).delete() CommCareUser.get_by_username('stella').delete() CommCareUser.get_by_username('super').delete() delete_all_locations() LocationType.objects.all().delete() for product in Product.by_domain(TEST_DOMAIN): product.delete() SQLProduct.objects.all().delete() EWSGhanaConfig.for_domain(TEST_DOMAIN).delete() DocDomainMapping.objects.all().delete() generator.delete_all_subscriptions() Domain.get_by_name(TEST_DOMAIN).delete()
def prepare_domain(domain_name): domain = create_domain(domain_name) domain.convert_to_commtrack() domain.default_sms_backend_id = TEST_BACKEND domain.save() def _make_loc_type(name, administrative=False, parent_type=None): return LocationType.objects.get_or_create( domain=domain_name, name=name, administrative=administrative, parent_type=parent_type, )[0] country = _make_loc_type(name="country", administrative=True) _make_loc_type(name="Central Medical Store", parent_type=country) _make_loc_type(name="Teaching Hospital", parent_type=country) region = _make_loc_type(name="region", administrative=True, parent_type=country) _make_loc_type(name="Regional Medical Store", parent_type=region) _make_loc_type(name="Regional Hospital", parent_type=region) district = _make_loc_type(name="district", administrative=True, parent_type=region) _make_loc_type(name="Clinic", parent_type=district) _make_loc_type(name="District Hospital", parent_type=district) _make_loc_type(name="Health Centre", parent_type=district) _make_loc_type(name="CHPS Facility", parent_type=district) _make_loc_type(name="Hospital", parent_type=district) _make_loc_type(name="Psychiatric Hospital", parent_type=district) _make_loc_type(name="Polyclinic", parent_type=district) _make_loc_type(name="facility", parent_type=district) generator.instantiate_accounting_for_tests() account = BillingAccount.get_or_create_account_by_domain( domain.name, created_by="automated-test", )[0] plan = DefaultProductPlan.get_default_plan_by_domain( domain, edition=SoftwarePlanEdition.ADVANCED ) subscription = Subscription.new_domain_subscription( account, domain.name, plan ) subscription.is_active = True subscription.save() ews_config = EWSGhanaConfig(enabled=True, domain=domain.name) ews_config.save() return domain
def tearDownClass(cls): CommCareUser.get_by_username("stella").delete() CommCareUser.get_by_username("super").delete() FacilityInCharge.objects.all().delete() delete_all_locations() LocationType.objects.all().delete() for product in Product.by_domain(TEST_DOMAIN): product.delete() SQLProduct.objects.all().delete() EWSGhanaConfig.for_domain(TEST_DOMAIN).delete() DocDomainMapping.objects.all().delete() generator.delete_all_subscriptions() cls.sms_backend_mapping.delete() cls.backend.delete() Domain.get_by_name(TEST_DOMAIN).delete()
def second_soh_reminder(): now = datetime.datetime.utcnow() date = now - datetime.timedelta(days=DAYS_UNTIL_LATE) domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): second_soh_process_user(user, date)
def second_soh_reminder(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): roles = user.user_data.get('role') if roles and IN_CHARGE_ROLE in roles: second_soh_process_user(user)
def on_going_non_reporting(): now = datetime.datetime.utcnow() date = now - datetime.timedelta(days=21) domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): try: user_location = SQLLocation.objects.get(domain=domain, location_id=user.location._id) except AttributeError: continue if user_location: facilities = [] if user_location.location_type == 'district': facilities = user_location.get_children() elif user_location.location_type == 'region': facilities = SQLLocation.objects.filter(domain=domain, parent__parent__location_id=user.location._id) fac = set() for facility in facilities: sp = facility.supply_point_id if sp and not StockTransaction.objects.filter( case_id=sp, type="stockonhand", report__date__gte=date).exists(): fac.add(str(facility.name)) if fac and user.get_verified_number(): message = ONGOING_NON_REPORTING % " \n".join(fac) send_sms_to_verified_number(user.get_verified_number(), message) if user.email: email = str(user.email) send_mail('ONGOING NON REPORTING', message, '*****@*****.**', [email])
def first_soh_reminder(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): role = user.user_data.get('role') if role and role != IN_CHARGE_ROLE: first_soh_process_user(user)
def handle(verified_contact, text, msg=None): user = verified_contact.owner if verified_contact else None domain = user.domain if not domain: return False if not EWSGhanaConfig.for_domain(domain): return False args = text.split() if not args: send_sms_to_verified_number(verified_contact, unicode(INVALID_MESSAGE)) return True 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 = { ('help', ): HelpHandler, ('stop', ): StopHandler, ('start', ): StartHandler, ('language', 'lang', 'lugha'): LanguageHandler, ('yes', 'no', 'y', 'n'): RequisitionHandler, ('undo', 'replace', 'revoke'): UndoHandler, ('soh',): AlertsHandler, ('not',): not_function(args[0]) if args else None, ('rec', 'receipts', 'received'): ReceiptsHandler } def choose_handler(keyword): for k, v in handlers.iteritems(): if keyword.lower() in k: return v return None handler_class = choose_handler(keyword) handler = handler_class(**params) if handler_class else None if handler: if args: return handler.handle() else: handler.help() return True else: return AlertsHandler(**params).handle()
def migration_task(): for config in EWSGhanaConfig.get_all_steady_sync_configs(): if config.enabled: endpoint = GhanaEndpoint.from_config(config) ews_bootstrap_domain(EWSApi(config.domain, endpoint)) apis = ( ('stock_transaction', sync_stock_transactions), ) stock_data_task.delay(config.domain, endpoint, apis, config, EWS_FACILITIES)
def ews_sync_stock_data(request, domain): apis = ( ('stock_transaction', sync_stock_transactions), ) config = EWSGhanaConfig.for_domain(domain) domain = config.domain endpoint = GhanaEndpoint.from_config(config) stock_data_task.delay(domain, endpoint, apis, config, EWS_FACILITIES) return HttpResponse('OK')
def ews_stock_data_task(domain): ewsghana_config = EWSGhanaConfig.for_domain(domain) domain = ewsghana_config.domain endpoint = GhanaEndpoint.from_config(ewsghana_config) commtrack_settings_sync(domain, LOCATION_TYPES) for product in endpoint.get_products(): sync_ilsgateway_product(domain, product) get_locations(domain, endpoint, EWS_FACILITIES) get_product_stock(domain, endpoint, EWS_FACILITIES) get_stock_transaction(domain, endpoint, EWS_FACILITIES)
def handle(verified_contact, text, msg=None): user = verified_contact.owner if verified_contact else None domain = user.domain if domain and not EWSGhanaConfig.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 = { ('language', 'lang', 'lugha'): LanguageHandler, ('reg', 'register'): RegistrationHandler, ('yes', 'no', 'y', 'n'): RequisitionHandler, ('undo', 'replace', 'revoke'): UndoHandler, ('soh'): AlertsHandler, ('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() if keyword == 'soh': return True return False
def fix_users_with_more_than_one_phone_number(domain): config = EWSGhanaConfig.for_domain(domain) endpoint = GhanaEndpoint.from_config(config) ews_api = EWSApi(domain, endpoint) offset = 0 _, smsusers = endpoint.get_smsusers(filters={'with_more_than_one_number': True}) while smsusers: for sms_user in smsusers: ews_api.sms_user_sync(sms_user) offset += 100 _, smsusers = endpoint.get_smsusers(filters={'with_more_than_one_number': True}, offset=offset)
def reminder_to_visit_website(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): if user.location and user.last_login < datetime.datetime.now() - datetime.timedelta(weeks=13) and\ user.get_verified_number() and \ (user.location.location_type == 'district' or user.location.location_type == 'region' or user.location.location_type == 'country'): message = WEB_REMINDER % user.name send_sms_to_verified_number(user.get_verified_number(), message) if user.email: email = str(user.email) send_mail('REMINDER TO VISIT WEBSITE', message, '*****@*****.**', [email])
def reminder_to_visit_website(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): thirteen_days_ago = datetime.datetime.utcnow() - datetime.timedelta(weeks=13) if user.location and user.last_login < thirteen_days_ago and user.get_verified_number()\ and user.location.location_type.name in ['district', 'region', 'country']: message = WEB_REMINDER % user.name verified_number = user.get_verified_number() send_sms_to_verified_number(verified_number, message) if can_receive_email(user, verified_number): email = str(user.email) send_mail('REMINDER TO VISIT WEBSITE', message, '*****@*****.**', [email])
def migrate_email_settings(domain): config = EWSGhanaConfig.for_domain(domain) endpoint = GhanaEndpoint.from_config(config) migrate_email = EmailSettingsSync(domain) for report in endpoint.get_daily_reports()[1]: migrate_email.daily_report_sync(report) for report in endpoint.get_weekly_reports()[1]: migrate_email.weekly_report_sync(report) for report in endpoint.get_monthly_reports()[1]: migrate_email.monthly_report_sync(report)
def report_reminder(): sp_ids = set() now = datetime.datetime.utcnow() date = now - datetime.timedelta(days=7) domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): if user.location: sp = SupplyPointCase.get_by_location(user.location) if sp and not StockTransaction.objects.filter( case_id=sp._id, type="stockonhand", report__date__gte=date).exists()\ and user.get_verified_number(): sp_ids.add(sp._id) message = REPORT_REMINDER % (user.name, user.location.name) send_sms_to_verified_number(user.get_verified_number(), message) if user.email: email = str(user.email) send_mail('REPORT REMINDER', message, '*****@*****.**', [email])
def urgent_stockout(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): try: user_location = SQLLocation.objects.get(domain=domain, location_id=user.location._id) except AttributeError: continue if user_location: facilities = [] if user_location.location_type == 'district': facilities = user_location.get_children() elif user_location.location_type == 'region': facilities = SQLLocation.objects.filter(domain=domain, parent__parent__location_id=user.location._id) elif user_location.location_type == 'country': facilities = SQLLocation.objects.filter(domain=domain, parent__parent__parent__location_id=user.location._id) stocked_out_products = set() fac = set() no_rep = 0 for facility in facilities: sp = facility.supply_point_id if sp: stocked_out = StockTransaction.objects.filter( case_id=sp, type="stockonhand", stock_on_hand=0) if stocked_out.exists(): no_rep += 1 fac.add(str(facility)) for product in stocked_out: stocked_out_products.add( SQLProduct.objects.get(product_id=product.product_id).name) if fac and no_rep >= len(facilities) / 2 and user.get_verified_number(): message = URGENT_STOCKOUT % (user_location.name, ", ".join(sorted( [str(product) for product in stocked_out_products]))) send_sms_to_verified_number(user.get_verified_number(), message) if user.email: email = str(user.email) send_mail('URGENT STOCKOUT', message, '*****@*****.**', [email])
def urgent_stockout(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: UrgentStockoutAlert(domain)
def urgent_non_reporting(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): urgent_non_reporting_process_user(user)
def handle(verified_contact, text, msg): domain = msg.domain if not domain: return False if not EWSGhanaConfig.for_domain(domain): return False if not verified_contact: return False user = verified_contact.owner if verified_contact.pending_verification: if not process_verification(verified_contact, msg, VERIFICATION_KEYWORDS): logged_event = MessagingEvent.get_current_verification_event( domain, verified_contact.owner_id, verified_contact.phone_number) send_verification(domain, user, verified_contact.phone_number, logged_event) return True args = text.split() if not args: send_sms_to_verified_number(verified_contact, unicode(INVALID_MESSAGE)) return True 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 = { ('help', ): HelpHandler, ('reminder', ): ReminderOnOffHandler, ('language', 'lang', 'lugha'): LanguageHandler, ('yes', 'no', 'y', 'n'): RequisitionHandler, ('undo', 'replace', 'revoke'): UndoHandler, ('soh', ): SOHHandler, ('not', ): not_function(args[0]) if args else None, ('rec', 'receipts', 'received'): ReceiptsHandler } def choose_handler(keyword): for k, v in handlers.iteritems(): if keyword.lower() in k: return v return None handler_class = choose_handler(keyword) handler = handler_class(**params) if handler_class else None if handler: if args: return handler.handle() else: handler.help() return True else: return SOHHandler(**params).handle()
def first_soh_reminder(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: FirstSOHReminder(domain).send()
def on_going_stockout(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): on_going_stockout_process_user(user)
def ews_resync_web_users(request, domain): config = EWSGhanaConfig.for_domain(domain) endpoint = GhanaEndpoint.from_config(config) resync_web_users.delay(EWSApi(domain=domain, endpoint=endpoint)) return HttpResponse('OK')
def report_reminder(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): report_reminder_process_user(user)
def urgent_stockout(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: UrgentStockoutAlert(domain).send()
def reminder_to_submit_rrirv(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: RRIRVReminder(domain).send()
def stockout_notification_to_web_supers(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: StockoutReminder(domain).send()
def third_soh_to_super(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: ThirdSOHReminder(domain).send()
def second_soh_reminder(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: SecondSOHReminder(domain).send()
def reminder_to_visit_website(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): visit_website_process_user(user)
def handle(verified_contact, text, msg): if not (verified_contact and verified_contact.verified): return False user = verified_contact.owner if verified_contact else None domain = user.domain if not domain: return False if not EWSGhanaConfig.for_domain(domain): return False args = text.split() if not args: send_sms_to_verified_number(verified_contact, unicode(INVALID_MESSAGE)) return True 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 = { ('help', ): HelpHandler, ('stop', ): StopHandler, ('start', ): StartHandler, ('language', 'lang', 'lugha'): LanguageHandler, ('yes', 'no', 'y', 'n'): RequisitionHandler, ('undo', 'replace', 'revoke'): UndoHandler, ('soh', ): SOHHandler, ('not', ): not_function(args[0]) if args else None, ('rec', 'receipts', 'received'): ReceiptsHandler } def choose_handler(keyword): for k, v in handlers.iteritems(): if keyword.lower() in k: return v return None handler_class = choose_handler(keyword) handler = handler_class(**params) if handler_class else None if handler: if args: return handler.handle() else: handler.help() return True else: return SOHHandler(**params).handle()
def urgent_non_reporting(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: UrgentNonReporting(domain).send()
def stockout_notification_to_web_supers(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): stockout_process_user(user)
def all_stock_data(self): return EWSGhanaConfig.for_domain(self.domain).all_stock_data
def ews_bootstrap_domain_task(domain): ews_config = EWSGhanaConfig.for_domain(domain) return bootstrap_domain( EWSApi(domain, GhanaEndpoint.from_config(ews_config)))
def ews_sync_stock_data(request, domain): config = EWSGhanaConfig.for_domain(domain) domain = config.domain endpoint = GhanaEndpoint.from_config(config) stock_data_task.delay(EWSStockDataSynchronization(domain, endpoint)) return HttpResponse('OK')
def migration_task(): for config in EWSGhanaConfig.get_all_steady_sync_configs(): if config.enabled: endpoint = GhanaEndpoint.from_config(config) ews_bootstrap_domain(EWSApi(config.domain, endpoint)) stock_data_task.delay(EWSStockDataSynchronization(config.domain, endpoint))
def ews_bootstrap_domain_task(domain): ews_config = EWSGhanaConfig.for_domain(domain) return bootstrap_domain(EWSApi(domain, GhanaEndpoint.from_config(ews_config)))
def on_going_stockout(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: OnGoingStockouts(domain).send() OnGoingStockoutsRMS(domain).send()
def _get_logistics_domains(self): from custom.ewsghana.models import EWSGhanaConfig return ILSGatewayConfig.get_all_enabled_domains( ) + EWSGhanaConfig.get_all_enabled_domains()
def reminder_to_submit_rrirv(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: for user in CommCareUser.by_domain(domain): rrirv_process_user(user)
def on_going_non_reporting(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: OnGoingNonReporting(domain).send()
def reminder_to_visit_website(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: VisitWebsiteReminder(domain).send()
def urgent_non_reporting(): domains = EWSGhanaConfig.get_all_enabled_domains() for domain in domains: UrgentNonReporting(domain)
def ews_add_products_to_locs(request, domain): config = EWSGhanaConfig.for_domain(domain) endpoint = GhanaEndpoint.from_config(config) add_products_to_loc.delay(EWSApi(domain=domain, endpoint=endpoint)) return HttpResponse('OK')
def handle(verified_contact, text, msg=None): user = verified_contact.owner if verified_contact else None domain = user.domain if not domain: return False if not EWSGhanaConfig.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 = { ('language', 'lang', 'lugha'): LanguageHandler, ('yes', 'no', 'y', 'n'): RequisitionHandler, # For now there is no easy way to fetch last report sent by user # ('undo', 'replace', 'revoke'): UndoHandler, ( 'soh', ): AlertsHandler, ('not', ): not_function(args[0]) if args else None, ('rec', 'receipts', 'received'): ReceiptsHandler } def choose_handler(keyword): for k, v in handlers.iteritems(): if keyword.lower() in k: return v return None handler_class = choose_handler(keyword) handler = handler_class(**params) if handler_class else None if handler: if args: return handler.handle() else: handler.help() return True else: return AlertsHandler(**params).handle()