def setUpClass(cls): cls.domain = 'supply-point-dbaccessors' cls.locations = [ Location(domain=cls.domain), Location(domain=cls.domain), Location(domain=cls.domain), ] Location.get_db().bulk_save(cls.locations) cls.supply_points = [ CommCareCase(domain=cls.domain, type='supply-point', location_id=cls.locations[0]._id), CommCareCase(domain=cls.domain, type='supply-point', location_id=cls.locations[1]._id), CommCareCase(domain=cls.domain, type='supply-point', location_id=cls.locations[2]._id), ] locations_by_id = { location._id: location for location in cls.locations } cls.location_supply_point_pairs = [ (locations_by_id[supply_point.location_id], supply_point) for supply_point in cls.supply_points ] CommCareCase.get_db().bulk_save(cls.supply_points)
def sync_facilities(request, domain): commtrack_settings = request.project.commtrack_settings # create Facility Registry and Facility LocationTypes if they don't exist if not any(lt.name == 'Facility Registry' for lt in commtrack_settings.location_types): commtrack_settings.location_types.extend([ LocationType(name='Facility Registry', allowed_parents=['']), LocationType(name='Facility', allowed_parents=['Facility Registry']) ]) commtrack_settings.save() registry_locs = dict( (l.external_id, l) for l in Location.filter_by_type(domain, 'Facility Registry')) # sync each registry and add/update Locations for each Facility for registry in FacilityRegistry.by_domain(domain): registry.sync_with_remote() try: registry_loc = registry_locs[registry.url] except KeyError: registry_loc = Location(domain=domain, location_type='Facility Registry', external_id=registry.url) registry_loc.name = registry.name registry_loc.save() registry_loc._seen = True facility_locs = dict( (l.external_id, l) for l in Location.filter_by_type(domain, 'Facility', registry_loc)) for facility in registry.get_facilities(): uuid = facility.data['uuid'] try: facility_loc = facility_locs[uuid] except KeyError: facility_loc = Location(domain=domain, location_type='Facility', external_id=uuid, parent=registry_loc) facility_loc.name = facility.data.get('name', 'Unnamed Facility') facility_loc.save() facility_loc._seen = True for id, f in facility_locs.iteritems(): if not hasattr(f, '_seen'): f.delete() for id, r in registry_locs.iteritems(): if not hasattr(r, '_seen'): r.delete() return HttpResponse('OK')
def sync_ilsgateway_location(domain, endpoint, ilsgateway_location): location = Location.view('commtrack/locations_by_code', key=[domain, ilsgateway_location.code.lower()], include_docs=True).first() if not location: if ilsgateway_location.parent: loc_parent = SupplyPointCase.view('hqcase/by_domain_external_id', key=[domain, str(ilsgateway_location.parent)], reduce=False, include_docs=True).first() if not loc_parent: parent = endpoint.get_location(ilsgateway_location.parent) loc_parent = sync_ilsgateway_location(domain, endpoint, Loc.from_json(parent)) else: loc_parent = loc_parent.location location = Location(parent=loc_parent) else: location = Location() location.lineage = [] location.domain = domain location.name = ilsgateway_location.name if ilsgateway_location.groups: location.metadata = {'groups': ilsgateway_location.groups} if ilsgateway_location.latitude: location.latitude = float(ilsgateway_location.latitude) if ilsgateway_location.longitude: location.longitude = float(ilsgateway_location.longitude) location.location_type = ilsgateway_location.type location.site_code = ilsgateway_location.code location.external_id = str(ilsgateway_location.id) location.save() if not SupplyPointCase.get_by_location(location): SupplyPointCase.create_from_location(domain, location) else: location_dict = { 'name': ilsgateway_location.name, 'latitude': float(ilsgateway_location.latitude) if ilsgateway_location.latitude else None, 'longitude': float(ilsgateway_location.longitude) if ilsgateway_location.longitude else None, 'type': ilsgateway_location.type, 'site_code': ilsgateway_location.code.lower(), 'external_id': str(ilsgateway_location.id), } case = SupplyPointCase.get_by_location(location) if apply_updates(location, location_dict): location.save() if case: case.update_from_location(location) else: SupplyPointCase.create_from_location(domain, location)
def location_edit(request, domain, loc_id=None): parent_id = request.GET.get('parent') if loc_id: try: location = Location.get(loc_id) except ResourceNotFound: raise Http404() else: location = Location(domain=domain, parent=parent_id) if request.method == "POST": form = LocationForm(location, request.POST) if form.is_valid(): form.save() messages.success(request, 'Location saved!') return HttpResponseRedirect('%s?%s' % ( reverse('manage_locations', kwargs={'domain': domain}), urllib.urlencode({'selected': form.location._id}) )) else: form = LocationForm(location) context = { 'domain': domain, 'api_root': reverse('api_dispatch_list', kwargs={'domain': domain, 'resource_name': 'location', 'api_name': 'v0.3'}), 'location': location, 'hierarchy': location_hierarchy_config(domain), 'form': form, } return render(request, 'locations/manage/location.html', context)
def testDoesntDuplicate(self): location = Location(name="Location", domain=self.domain, location_type="type") location.save() self.assertEqual(location.site_code, 'location') location = Location(name="Location", domain=self.domain, location_type="type") location.save() self.assertEqual(location.site_code, 'location1')
def _create_data(self, domain_name, i): product = Product(domain=domain_name, name='test-{}'.format(i)) product.save() location = Location(domain=domain_name, site_code='testcode-{}'.format(i), name='test-{}'.format(i), location_type='facility') location.save() report = StockReport.objects.create( type='balance', domain=domain_name, form_id='fake', date=datetime.utcnow(), server_date=datetime.utcnow(), ) StockTransaction.objects.create( report=report, product_id=product.get_id, sql_product=SQLProduct.objects.get(product_id=product.get_id), section_id='stock', type='stockonhand', case_id=location.linked_supply_point().get_id, stock_on_hand=100) SMS.objects.create(domain=domain_name) Call.objects.create(domain=domain_name) SQLLastReadMessage.objects.create(domain=domain_name) ExpectedCallback.objects.create(domain=domain_name) PhoneNumber.objects.create(domain=domain_name, is_two_way=False, pending_verification=False) event = MessagingEvent.objects.create( domain=domain_name, date=datetime.utcnow(), source=MessagingEvent.SOURCE_REMINDER, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED) MessagingSubEvent.objects.create( parent=event, date=datetime.utcnow(), recipient_type=MessagingEvent.RECIPIENT_CASE, content_type=MessagingEvent.CONTENT_SMS, status=MessagingEvent.STATUS_COMPLETED) SelfRegistrationInvitation.objects.create( domain=domain_name, phone_number='999123', token=uuid.uuid4().hex, expiration_date=datetime.utcnow().date(), created_date=datetime.utcnow()) backend = SQLMobileBackend.objects.create(domain=domain_name, is_global=False) SQLMobileBackendMapping.objects.create( domain=domain_name, backend_type=SQLMobileBackend.SMS, prefix=str(i), backend=backend) MobileBackendInvitation.objects.create(domain=domain_name, backend=backend)
def sync_facility_to_supply_point(domain, facility): supply_point = get_supply_point(domain, facility) facility_dict = { 'domain': domain, 'location_type': facility.type, 'external_id': facility.code, 'name': facility.name, 'site_code': facility.code, # todo: do they have a human readable code? 'latitude': facility.latitude, 'longitude': facility.longitude, } parent_sp = None if facility.parent_id: parent_sp = get_supply_point(domain, facility.parent_id) if not parent_sp: raise BadParentException('No matching supply point with code %s found' % facility.parent_id) if supply_point is None: if parent_sp: facility_dict['parent'] = parent_sp.location facility_loc = Location(**facility_dict) facility_loc.save() return make_supply_point(domain, facility_loc) else: facility_loc = supply_point.location if parent_sp and facility_loc.parent_id != parent_sp.location._id: raise BadParentException('You are trying to move a location. This is currently not supported.') should_save = apply_updates(facility_loc, facility_dict) if should_save: facility_loc.save() return supply_point
def create_test_locations(domain): country = Location(name='national', site_code='ghana', location_type='country', domain=domain) country.save() crms = Location(name='Central Regional Medical Store', site_code='crms', location_type='country', domain=domain) crms.save() test_region = Location(name='Test Region', site_code='testregion', location_type='region', domain=domain, parent=country) test_region.save() test_region2 = Location(name='Test Region2', site_code='testregion2', location_type='region', domain=domain, parent=country) test_region2.save() rsp = Location(name='Test Regional Medical Store', site_code='rsp', location_type='Regional Medical Store', domain=domain, parent=test_region2) rsp.save() assign_products_to_locations(rsp, ["ad", "al", "mc", "ng", "mg"]) rsp2 = Location(name='Test Regional Medical Store', site_code='rsp2', location_type='Regional Medical Store', domain=domain, parent=test_region2) rsp2.save() assign_products_to_locations(rsp2, ["ad", "al"]) test_district = Location(name='Test District', site_code='testdistrict', location_type='district', domain=domain, parent=test_region) test_district.save() test_facility = Location(name='Active Test hospital', site_code='tsactive', location_type='Hospital', domain=domain, parent=test_district) test_facility.save() assign_products_to_locations(test_facility, ["ad", "al"])
def setUpClass(cls): super(IntraHealthTestCase, cls).setUpClass() cls.session_helper = connection_manager.get_session_helper(settings.SQL_REPORTING_DATABASE_URL) cls.engine = cls.session_helper.engine cls.domain = create_domain(TEST_DOMAIN) cls.region_type = LocationType.objects.create(domain=TEST_DOMAIN, name=u'Région') cls.district_type = LocationType.objects.create(domain=TEST_DOMAIN, name=u'District') cls.pps_type = LocationType.objects.create(domain=TEST_DOMAIN, name=u'PPS') cls.region = Location(domain=TEST_DOMAIN, name='Test region', location_type=u'Région') cls.region.save() cls.district = Location( domain=TEST_DOMAIN, name='Test district', location_type=u'District', parent=cls.region ) cls.district.save() cls.pps = Location(domain=TEST_DOMAIN, name='Test PPS', location_type=u'PPS', parent=cls.district) cls.pps.save() cls.mobile_worker = create_mobile_worker( domain=TEST_DOMAIN, username='******', password='******', phone_number='777777' ) cls.mobile_worker.location_id = cls.pps.get_id cls.mobile_worker.save() cls.product = Product(_id=u'81457658bdedd663f8b0bdadb19d8f22', name=u'ASAQ Nourisson', domain=TEST_DOMAIN) cls.product2 = Product( _id=u'81457658bdedd663f8b0bdadb19d83d8', name=u'ASAQ Petit Enfant', domain=TEST_DOMAIN ) cls.product.save() cls.product2.save() cls.recap_table = RecapPassageFluff._table cls.intra_table = IntraHealthFluff._table cls.taux_rupt_table = TauxDeRuptureFluff._table cls.livraison_table = LivraisonFluff._table cls.taux_sat_table = TauxDeSatisfactionFluff._table cls.couverture_table = CouvertureFluff._table with cls.engine.begin() as connection: cls.recap_table.create(connection, checkfirst=True) cls.intra_table.create(connection, checkfirst=True) cls.taux_rupt_table.create(connection, checkfirst=True) cls.livraison_table.create(connection, checkfirst=True) cls.taux_sat_table.create(connection, checkfirst=True) cls.couverture_table.create(connection, checkfirst=True)
def testSimpleName(self): location = Location(name="Some Location", domain=self.domain, location_type="type") location.save() self.assertEqual(location.site_code, 'some_location')
def testOtherCharacters(self): location = Location(name=u"Somé$ #Location (Old)", domain=self.domain, location_type="type") location.save() self.assertEqual(location.site_code, 'some_location_old')
def setUpClass(cls): super(IntraHealthTestCase, cls).setUpClass() cls.session_helper = connection_manager.get_session_helper( settings.SQL_REPORTING_DATABASE_URL) cls.engine = cls.session_helper.engine cls.domain = create_domain(TEST_DOMAIN) cls.region_type = LocationType.objects.create(domain=TEST_DOMAIN, name=u'Région') cls.district_type = LocationType.objects.create(domain=TEST_DOMAIN, name=u'District') cls.pps_type = LocationType.objects.create(domain=TEST_DOMAIN, name=u'PPS') cls.region = Location(domain=TEST_DOMAIN, name='Test region', location_type=u'Région') cls.region.save() cls.district = Location(domain=TEST_DOMAIN, name='Test district', location_type=u'District', parent=cls.region) cls.district.save() cls.pps = Location(domain=TEST_DOMAIN, name='Test PPS', location_type=u'PPS', parent=cls.district) cls.pps.save() cls.mobile_worker = create_mobile_worker(domain=TEST_DOMAIN, username='******', password='******', phone_number='777777') cls.mobile_worker.location_id = cls.pps.get_id cls.mobile_worker.save() cls.product = Product(_id=u'81457658bdedd663f8b0bdadb19d8f22', name=u'ASAQ Nourisson', domain=TEST_DOMAIN) cls.product2 = Product(_id=u'81457658bdedd663f8b0bdadb19d83d8', name=u'ASAQ Petit Enfant', domain=TEST_DOMAIN) cls.product.save() cls.product2.save()
def testCreateVirtualFacility(self): loc = Location(site_code='1234', name='beavis', domain=self.domain, location_type='chw') loc.save() sp = make_supply_point(self.domain, loc) self.assertTrue(sync_supply_point_to_openlmis(sp, self.api)) self.assertTrue(sync_supply_point_to_openlmis(sp, self.api, False))
def _create_data(self, domain_name): product = Product(domain=domain_name, name='test-product') product.save() location = Location(domain=domain_name, site_code='testcode', name='test1', location_type='facility') location.save() self.locations[domain_name] = location.get_id DeliveryGroupReport.objects.create(location_id=location.get_id, quantity=1, message='test', delivery_group='A') SupplyPointWarehouseRecord.objects.create( supply_point=location.get_id, create_date=datetime.utcnow()) Alert.objects.create(text='test', expires=datetime.utcnow(), date=datetime.utcnow(), location_id=location.get_id) organization_summary = OrganizationSummary.objects.create( date=datetime.utcnow(), location_id=location.get_id) GroupSummary.objects.create(org_summary=organization_summary) ProductAvailabilityData.objects.create(product=product.get_id, date=datetime.utcnow(), location_id=location.get_id) SupplyPointStatus.objects.create(location_id=location.get_id, status_type='del_fac', status_value='received') HistoricalLocationGroup.objects.create( location_id=location.sql_location, group='A', date=datetime.utcnow().date()) ReportRun.objects.create(domain=domain_name, start=datetime.utcnow(), end=datetime.utcnow(), start_run=datetime.utcnow()) ILSNotes.objects.create(location=location.sql_location, domain=domain_name, user_name='test', date=datetime.utcnow(), text='test') SupervisionDocument.objects.create(domain=domain_name, document='test', data_type='test', name='test')
def make_loc(code, name, domain, type, parent=None): name = name or code sql_type, _ = LocationType.objects.get_or_create(domain=domain, name=type) loc = Location(site_code=code, name=name, domain=domain, location_type=type, parent=parent) loc.save() sql_location = loc.sql_location sql_location.products = [] sql_location.save() return loc
def make_loc(code, name, domain, type, metadata=None, parent=None): name = name or code LocationType.objects.get(domain=domain, name=type) loc = Location(site_code=code, name=name, domain=domain, location_type=type, parent=parent) loc.metadata = metadata or {} loc.save() return loc
def make_form(domain, parent, data, existing=None): """simulate a POST payload from the location create/edit page""" location = existing or Location(domain=domain, parent=parent) def make_payload(k, v): if hasattr(k, '__iter__'): prefix, propname = k prefix = 'props_%s' % prefix else: prefix, propname = 'main', k return ('%s-%s' % (prefix, propname), v) payload = dict(make_payload(k, v) for k, v in data.iteritems()) return LocationForm(location, payload)
def make_loc(code, name=None, domain=TEST_DOMAIN, type=TEST_LOCATION_TYPE, parent=None): name = name or code loc = Location(site_code=code, name=name, domain=domain, location_type=type, parent=parent) loc.save() return loc
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() SupplyPointCase.create_from_location(TEST_DOMAIN, l1) SupplyPointCase.create_from_location(TEST_DOMAIN, l2) 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 locations_fix(domain): locations = SQLLocation.objects.filter(domain=domain, location_type__in=['country', 'region', 'district']) for loc in locations: sp = Location.get(loc.location_id).linked_supply_point() if sp: sp.external_id = None sp.save() else: fake_location = Location( _id=loc.location_id, name=loc.name, domain=domain ) SupplyPointCase.get_or_create_by_location(fake_location)
def make_loc(code, name=None, domain=TEST_DOMAIN, type=TEST_LOCATION_TYPE, parent=None): name = name or code LocationType.objects.get_or_create(domain=domain, name=type) loc = Location(site_code=code, name=name, domain=domain, location_type=type, parent=parent) loc.save() return loc
def _create_data(self, domain_name): product = Product(domain=domain_name, name='test-product') product.save() location = Location(domain=domain_name, site_code='testcode', name='test1', location_type='facility') location.save() self.locations[domain_name] = location.sql_location user = CommCareUser.create(domain=domain_name, username='******'.format(domain_name), password='******') FacilityInCharge.objects.create(user_id=user.get_id, location=location.sql_location)
def make_loc(code, name=None, domain=TEST_DOMAIN, type=TEST_LOCATION_TYPE, parent=None): if not Domain.get_by_name(domain): raise AssertionError("You can't make a location on a fake domain") name = name or code LocationType.objects.get_or_create(domain=domain, name=type, defaults={'administrative': False}) loc = Location(site_code=code, name=name, domain=domain, location_type=type, parent=parent) loc.save() return loc
def save(self, instance=None, commit=True): if self.errors: raise ValueError('form does not validate') location = instance or self.location is_new = location._id is None for field in ('name', 'location_type'): setattr(location, field, self.cleaned_data[field]) location.lineage = Location( parent=self.cleaned_data['parent_id']).lineage for k, v in self.cleaned_data.iteritems(): if k.startswith('prop:'): prop_name = k[len('prop:'):] setattr(location, prop_name, v) orig_parent_id = self.cleaned_data.get('orig_parent_id') reparented = orig_parent_id is not None if reparented: location.flag_post_move = True location.previous_parents.append(orig_parent_id) # HACK # not sure where this is getting set, but it shouldn't be in the doc del location._doc['parent_id'] if commit: location.save() if is_new: location_created.send(sender='loc_mgmt', loc=location) else: location_edited.send(sender='loc_mgmt', loc=location, moved=reparented) if reparented: # post-location move processing here # (none for now; do it as a batch job) pass return location
def save(self, instance=None, commit=True): if self.errors: raise ValueError('form does not validate') location = instance or self.location is_new = location._id is None for field in ('name', 'location_type'): setattr(location, field, self.cleaned_data[field]) coords = self.cleaned_data['coordinates'] setattr(location, 'latitude', coords[0] if coords else None) setattr(location, 'longitude', coords[1] if coords else None) location.lineage = Location( parent=self.cleaned_data['parent_id']).lineage location.metadata = self.cleaned_data.get('metadata', {}) for k, v in self.cleaned_data.iteritems(): if k.startswith('prop:'): prop_name = k[len('prop:'):] setattr(location, prop_name, v) orig_parent_id = self.cleaned_data.get('orig_parent_id') reparented = orig_parent_id is not None if reparented: location.flag_post_move = True location.previous_parents.append(orig_parent_id) if commit: location.save() if is_new: location_created.send(sender='loc_mgmt', loc=location) else: location_edited.send(sender='loc_mgmt', loc=location, moved=reparented) if reparented: # post-location move processing here # (none for now; do it as a batch job) pass return location
def setUpClass(cls): super(UpdateLocationKeywordTest, cls).setUpClass() cls.domain = "opt-test" cls.domain_obj = Domain(name=cls.domain) cls.domain_obj.save() cls.setup_subscription(cls.domain_obj.name, SoftwarePlanEdition.ADVANCED) cls.backend, cls.backend_mapping = setup_default_sms_test_backend() cls.user = create_mobile_worker(cls.domain, 'test', '*****', '4444') cls.location_type = LocationType.objects.create(domain=cls.domain, name='test') cls.location = Location(domain=cls.domain, name='test', site_code='site_code', location_type='test') cls.location.save()
def _create_data(self, domain_name, i): product = Product(domain=domain_name, name='test-{}'.format(i)) product.save() location = Location(domain=domain_name, site_code='testcode-{}'.format(i), name='test-{}'.format(i), location_type='facility') location.save() SupplyPointCase.create_from_location(domain_name, location) report = StockReport.objects.create(type='balance', domain=domain_name, form_id='fake', date=datetime.utcnow()) StockTransaction.objects.create( report=report, product_id=product.get_id, sql_product=SQLProduct.objects.get(product_id=product.get_id), section_id='stock', type='stockonhand', case_id=location.linked_supply_point().get_id, stock_on_hand=100)
def location(self): return Location(domain=self.domain, parent=self.parent_id)
def _make_location(self, **kwargs): kwargs['domain'] = self.domain loc = Location(**kwargs) self.database.save_doc(loc.to_json()) return loc