def test_product_type_filter(self): """ Notifications will not be sent if the stockout is a product type does not interest the user. """ self.user.get_domain_membership(self.TEST_DOMAIN).program_id = self.program.get_id self.user.save() program = Program(domain=self.TEST_DOMAIN, name='Test Program 2') program.save() bootstrap_web_user( username='******', domain=self.TEST_DOMAIN, phone_number='+44445', location=self.district, password='******', email='*****@*****.**', user_data={}, program_id=program.get_id ) assign_products_to_location(self.facility, [self.product]) assign_products_to_location(self.other_facility, [self.product]) assign_products_to_location(self.last_facility, [self.product]) create_stock_report(self.facility, {'tp': 0}) create_stock_report(self.other_facility, {'tp': 0}) create_stock_report(self.last_facility, {'tp': 0}) generated = list(UrgentStockoutAlert(self.TEST_DOMAIN).get_notifications()) self.assertEqual(len(generated), 1) self.assertEqual(generated[0].user.get_id, self.user.get_id)
def test_product_type_filter(self): """ Notifications will not be sent if the stockout is a product type does not interest the user. """ self.user.get_domain_membership(self.TEST_DOMAIN).program_id = self.program.get_id self.user.save() program = Program(domain=self.TEST_DOMAIN, name='Test Program 2') program.save() other_user = bootstrap_web_user( username='******', domain=self.TEST_DOMAIN, phone_number='+44445', location=self.region, password='******', email='*****@*****.**', user_data={} ) assign_products_to_location(self.facility, [self.product]) assign_products_to_location(self.other_facility, [self.product]) assign_products_to_location(self.last_facility, [self.product]) generated = list(UrgentNonReporting(self.TEST_DOMAIN).get_notifications()) self.assertEqual(len(generated), 2) self.assertEqual({generated[0].user.get_id, generated[1].user.get_id}, {self.user.get_id, other_user.get_id})
def __init__(self, product, *args, **kwargs): self.product = product kwargs['initial'] = self.product._doc kwargs['initial']['code'] = self.product.code super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.label_class = 'col-sm-3 col-md-4 col-lg-2' self.helper.field_class = 'col-sm-4 col-md-5 col-lg-3' programs = Program.by_domain(self.product.domain, wrap=False) self.fields['program_id'].choices = tuple((prog['_id'], prog['name']) for prog in programs) # make sure to select default program if # this is a new product if not product._id: self.initial['program_id'] = Program.default_for_domain(self.product.domain)._id self.helper.layout = Layout( 'name', 'code', 'description', 'unit', 'program_id', 'cost' )
class SignalsTest(OpenLMISTestBase): requisitions_enabled = True program = None def createProgram(self): self.program = Program() self.program.domain = TEST_DOMAIN self.program.code = "QYZ" self.program.name = "hiv_program" self.program.save() def createProducts(self): with open(os.path.join(self.datapath, "sample_product_1.json")) as f: lmis_product_1 = json.loads(f.read()) with open(os.path.join(self.datapath, "sample_product_2.json")) as f: lmis_product_2 = json.loads(f.read()) lmis_product_1["program_id"] = self.program._id lmis_product_2["program_id"] = self.program._id product_1 = Product(lmis_product_1) product_2 = Product(lmis_product_2) product_1.save() product_2.save() self.products = [] self.products.append(product_1) self.products.append(product_2) def setUp(self): super(SignalsTest, self).setUp() self.datapath = os.path.join(os.path.dirname(__file__), "data") self.spps.clear() self.createProgram() self.createProducts() def fixmetestSyncStockRequisition(self): from corehq.apps.commtrack.stockreport import Requisition requisition_cases = [] config = self.domain.commtrack_settings for spp in self.spps.values(): transaction = Requisition( config=config, product_id=spp.product, case_id=spp._id, action_name=config.get_action_by_type(RequisitionActions.REQUEST).action_name, value=20, ) req = create_requisition(self.user._id, spp, transaction) requisition_cases.append(req) endpoint = MockOpenLMISSubmitEndpoint("uri://mock/lmis/endpoint", username="******", password="******") stock_data_submission(sender=None, cases=requisition_cases, endpoint=endpoint) for req in requisition_cases: self.assertEqual(req.external_id, "REQ_123")
def test_programs(self): self.domain = bootstrap_domain(TEST_DOMAIN) self.addCleanup(self.domain.delete) bootstrap_products(self.domain.name) self.products = sorted(Product.by_domain(self.domain.name), key=lambda p: p._id) self.default_program = Program.by_domain(self.domain.name, wrap=True).one() self.new_program = make_program( self.domain.name, 'new program', 'newprogram' ) self.assertTrue(self.default_program.default) self.assertFalse(self.new_program.default) with self.assertRaises(Exception) as context: self.default_program.delete() self.assertEqual(six.text_type(context.exception), 'You cannot delete the default program') # assign some product to the new program self.products[0].program_id = self.new_program._id self.products[0].save() # make sure start state is okay self.assertEqual( 2, len(Program.by_domain(self.domain.name)) ) self.assertEqual(2, self.default_program.get_products_count()) self.assertEqual(1, self.new_program.get_products_count()) self.assertEqual( self.new_program._id, self.products[0].program_id ) self.assertEqual( self.new_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id ) # stash the id before we delete new_program_id = self.new_program._id self.new_program.delete() with self.assertRaises(ResourceNotFound): Program.get(new_program_id) self.assertEqual(1, len(Program.by_domain(self.domain.name))) self.assertEqual(3, self.default_program.get_products_count()) self.assertEqual( self.default_program._id, Product.get(self.products[0]._id).program_id ) self.assertEqual( self.default_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id )
def test_delete(self): # assign some product to the new program self.products[0].program_id = self.new_program._id self.products[0].save() # make sure start state is okay self.assertEqual( 2, len(Program.by_domain(self.domain.name)) ) self.assertEqual( 2, Product.by_program_id(self.domain.name, self.default_program._id).count() ) self.assertEqual( 1, Product.by_program_id(self.domain.name, self.new_program._id).count() ) self.assertEqual( self.new_program._id, self.products[0].program_id ) self.assertEqual( self.new_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id ) # stash the id before we delete new_program_id = self.new_program._id self.new_program.delete() with self.assertRaises(ResourceNotFound): Program.get(new_program_id) self.assertEqual( 1, len(Program.by_domain(self.domain.name)) ) self.assertEqual( 3, Product.by_program_id(self.domain.name, self.default_program._id).count() ) self.assertEqual( self.default_program._id, Product.get(self.products[0]._id).program_id ) self.assertEqual( self.default_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id )
def product_data(self): data = [] if self.show_inactive: products = Product.archived_by_domain( domain=self.domain, limit=self.limit, skip=self.skip(), ) else: products = Product.by_domain( domain=self.domain, limit=self.limit, skip=self.skip(), ) for p in products: if p.program_id: program = Program.get(p.program_id) else: program = get_or_create_default_program(self.domain) p.program_id = program.get_id p.save() info = p._doc info['program'] = program.name info['edit_url'] = reverse('commtrack_product_edit', kwargs={'domain': self.domain, 'prod_id': p._id}) info['archive_action_desc'] = self.get_archive_text(self.show_inactive) info['archive_action_text'] = _("Un-Archive") if self.show_inactive else _("Archive") info['archive_url'] = reverse( 'unarchive_product' if self.show_inactive else 'archive_product', kwargs={'domain': self.domain, 'prod_id': p._id} ) data.append(info) return data
def stock_data_submission(sender, cases, endpoint=None, **kwargs): project = Domain.get_by_name(cases[0].domain) if project.commtrack_enabled and project.commtrack_settings.openlmis_enabled: if endpoint is None: endpoint = OpenLMISEndpoint.from_config(project.commtrack_settings.openlmis_config) # get agentCode and programCode - I assume all cases are part of the same program agentCode = (cases[0].get_supply_point_case()).location.site_code programCode = Program.get(cases[0].get_product().program_id).code products = [] for case in cases: product = case.get_product() product_json = {'productCode': product.code} product_json['stockInHand'] = int(case.get_default_value()) products.append(product_json) stock_data = { 'agentCode': agentCode, 'programCode': programCode, 'products': products } response = sync_stock_data_to_openlmis(submission=stock_data, openlmis_endpoint=endpoint) if response['requisitionId'] is not None: for case in cases: case.external_id = response['requisitionId'] case.save() cases, send_notification = sync_requisition_from_openlmis(project.name, response['requisitionId'], endpoint) if send_notification: send_notifications(xform=None, cases=cases)
def __init__(self, *args, **kwargs): from corehq.apps.locations.forms import LocationSelectWidget self.domain = kwargs.pop('domain', None) super(CommtrackUserForm, self).__init__(*args, **kwargs) self.fields['assigned_locations'].widget = LocationSelectWidget( self.domain, multiselect=True, id='id_assigned_locations' ) self.fields['assigned_locations'].help_text = ExpandedMobileWorkerFilter.location_search_help self.fields['primary_location'].widget = PrimaryLocationWidget( css_id='id_primary_location', source_css_id='id_assigned_locations', ) if self.commtrack_enabled: programs = Program.by_domain(self.domain) choices = list((prog.get_id, prog.name) for prog in programs) choices.insert(0, ('', '')) self.fields['program_id'].choices = choices else: self.fields['program_id'].widget = forms.HiddenInput() self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
def __init__(self, *args, **kwargs): self.domain = None if 'domain' in kwargs: self.domain = kwargs['domain'] del kwargs['domain'] super(CommtrackUserForm, self).__init__(*args, **kwargs) self.fields['assigned_locations'].widget = SupplyPointSelectWidget( self.domain, multiselect=True, id='id_assigned_locations') self.fields['primary_location'].widget = PrimaryLocationWidget( css_id='id_primary_location', source_css_id='id_assigned_locations') if self.commtrack_enabled: programs = Program.by_domain(self.domain, wrap=False) choices = list((prog['_id'], prog['name']) for prog in programs) choices.insert(0, ('', '')) self.fields['program_id'].choices = choices else: self.fields['program_id'].widget = forms.HiddenInput() self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
def get_url(cls, domain=None, render_as=None, **kwargs): def _is_admin(user, domain): return isinstance(user, WebUser) and user.get_domain_membership(domain).is_admin def _is_read_only(user, domain): user_role = user.get_role() return isinstance(user, WebUser) and user_role == UserRole.get_read_only_role_by_domain(domain) def _can_see_reports(user): user_role = user.get_role() return isinstance(user, CommCareUser) and user_role.permissions.view_reports url = super(MultiReport, cls).get_url(domain=domain, render_as=None, kwargs=kwargs) request = kwargs.get('request') user = getattr(request, 'couch_user', None) if user: if _is_admin(user, domain): loc = SQLLocation.objects.filter(domain=domain, location_type='country')[0] url = '%s?location_id=%s' % (url, loc.location_id) elif _is_read_only(user, domain) or _can_see_reports(user): dm = user.get_domain_membership(domain) if dm.program_id: program_id = dm.program_id else: program_id = Program.default_for_domain(domain) url = '%s?location_id=%s&program_id=%s' % ( url, dm.location_id if dm.location_id else '', program_id if program_id else '' ) return url
def __init__(self, data=None, excluded_emails=None, *args, **kwargs): domain = None location = None if 'domain' in kwargs: domain = Domain.get_by_name(kwargs['domain']) del kwargs['domain'] if 'location' in kwargs: location = kwargs['location'] del kwargs['location'] super(AdminInvitesUserForm, self).__init__(data=data, *args, **kwargs) if domain and domain.commtrack_enabled: self.fields['supply_point'] = forms.CharField( label='Supply Point:', required=False, widget=SupplyPointSelectWidget(domain=domain.name), initial=location.location_id if location else '') self.fields['program'] = forms.ChoiceField(label="Program", choices=(), required=False) programs = Program.by_domain(domain.name, wrap=False) choices = list((prog['_id'], prog['name']) for prog in programs) choices.insert(0, ('', '')) self.fields['program'].choices = choices self.excluded_emails = excluded_emails or [] self.helper = FormHelper() self.helper.form_tag = False self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
def __init__(self, *args, **kwargs): self.domain = None if 'domain' in kwargs: self.domain = kwargs['domain'] del kwargs['domain'] super(CommtrackUserForm, self).__init__(*args, **kwargs) self.fields['assigned_locations'].widget = SupplyPointSelectWidget( self.domain, multiselect=True, id='id_assigned_locations' ) self.fields['primary_location'].widget = PrimaryLocationWidget( css_id='id_primary_location', source_css_id='id_assigned_locations' ) if self.commtrack_enabled: programs = Program.by_domain(self.domain, wrap=False) choices = list((prog['_id'], prog['name']) for prog in programs) choices.insert(0, ('', '')) self.fields['program_id'].choices = choices else: self.fields['program_id'].widget = forms.HiddenInput() self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' self.helper.form_tag = False self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
def createProgram(self): self.program = Program() self.program.domain = TEST_DOMAIN self.program.code = "QYZ" self.program.name = "hiv_program" self.program.save()
def __init__(self, data=None, excluded_emails=None, *args, **kwargs): domain = None location = None if 'domain' in kwargs: domain = Domain.get_by_name(kwargs['domain']) del kwargs['domain'] if 'location' in kwargs: location = kwargs['location'] del kwargs['location'] super(AdminInvitesUserForm, self).__init__(data=data, *args, **kwargs) if domain and domain.commtrack_enabled: self.fields['supply_point'] = forms.CharField(label='Supply Point:', required=False, widget=SupplyPointSelectWidget(domain.name), initial=location.location_id if location else '') self.fields['program'] = forms.ChoiceField(label="Program", choices=(), required=False) programs = Program.by_domain(domain.name, wrap=False) choices = list((prog['_id'], prog['name']) for prog in programs) choices.insert(0, ('', '')) self.fields['program'].choices = choices self.excluded_emails = excluded_emails or [] self.helper = FormHelper() self.helper.form_tag = False self.helper.form_method = 'POST' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6'
def program_fixture_generator(user, version, last_sync=None): fields = [ 'name', 'code' ] data_fn = lambda: Program.by_domain(user.domain) return _simple_fixture_generator(user, "program", fields, data_fn, last_sync)
def test_program_fixture(self): user = self.user Program( domain=user.domain, name="test1", code="t1" ).save() program_list = Program.by_domain(user.domain) program_xml = self.generate_program_xml(program_list, user) fixture = call_fixture_generator(program_fixture_generator, user) self.assertXmlEqual( program_xml, ElementTree.tostring(fixture[0]) )
def drilldown_map(self): options = [] for program in Program.by_domain(self.domain): products = [] for product in Product.by_program_id(self.domain, program._id): products.append({"val": product.get_id, "text": product.name}) options.append({"val": program.get_id, "text": program.name, "next": products}) return options
def update_params(self): self.selected = self.request.GET.get("program") user = WebUser.get_by_username(str(self.request.user)) if not self.selected and self.selected != "" and user.get_domain_membership(self.domain): self.selected = user.get_domain_membership(self.domain).program_id self.programs = Program.by_domain(self.domain) opts = [dict(val=program.get_id, text=program.name) for program in self.programs] self.options = opts
def drilldown_map(self): options = [{"val": ALL_OPTION, "text": "All", "next": []}] for program in Program.by_domain(self.domain): products = [{"val": ALL_OPTION, "text": "All", "next": []}] for product in SQLProduct.objects.filter(domain=self.domain, program_id=program.get_id): products.append({"val": product.id, "text": product.name}) options.append({"val": program.get_id, "text": program.name, "next": products}) return options
def __init__(self, product, *args, **kwargs): self.product = product kwargs['initial'] = self.product._doc kwargs['initial']['code'] = self.product.code super(ProductForm, self).__init__(*args, **kwargs) programs = Program.by_domain(self.product.domain, wrap=False) self.fields['program_id'].choices = tuple((prog['_id'], prog['name']) for prog in programs) # make sure to select default program if # this is a new product if not product._id: self.initial['program_id'] = Program.default_for_domain( self.product.domain )._id
def __call__(self, restore_state): restore_user = restore_state.restore_user data_fn = lambda: Program.by_domain(restore_user.domain) return simple_fixture_generator( restore_user, self.id, "program", PROGRAM_FIELDS, data_fn, restore_state.last_sync_log )
def setUp(self): super(ProgramsTest, self).setUp() self.default_program = Program.by_domain(self.domain.name, wrap=True).one() self.new_program = make_program( self.domain.name, 'new program', 'newprogram' )
def test_programs(self): self.domain = bootstrap_domain(TEST_DOMAIN) self.addCleanup(self.domain.delete) bootstrap_products(self.domain.name) self.products = sorted(Product.by_domain(self.domain.name), key=lambda p: p._id) self.default_program = Program.by_domain(self.domain.name, wrap=True).one() self.new_program = make_program(self.domain.name, 'new program', 'newprogram') self.assertTrue(self.default_program.default) self.assertFalse(self.new_program.default) with self.assertRaises(Exception) as context: self.default_program.delete() self.assertEqual(context.exception.message, 'You cannot delete the default program') # assign some product to the new program self.products[0].program_id = self.new_program._id self.products[0].save() # make sure start state is okay self.assertEqual(2, len(Program.by_domain(self.domain.name))) self.assertEqual(2, self.default_program.get_products_count()) self.assertEqual(1, self.new_program.get_products_count()) self.assertEqual(self.new_program._id, self.products[0].program_id) self.assertEqual( self.new_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id) # stash the id before we delete new_program_id = self.new_program._id self.new_program.delete() with self.assertRaises(ResourceNotFound): Program.get(new_program_id) self.assertEqual(1, len(Program.by_domain(self.domain.name))) self.assertEqual(3, self.default_program.get_products_count()) self.assertEqual(self.default_program._id, Product.get(self.products[0]._id).program_id) self.assertEqual( self.default_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id)
def __init__(self, product, *args, **kwargs): self.product = product kwargs['initial'] = self.product._doc kwargs['initial']['code'] = self.product.code super(ProductForm, self).__init__(*args, **kwargs) programs = Program.by_domain(self.product.domain, wrap=False) self.fields['program_id'].choices = tuple( (prog['_id'], prog['name']) for prog in programs) # make sure to select default program if # this is a new product if not product._id: self.initial['program_id'] = Program.default_for_domain( self.product.domain)._id
def product_sync(self, ilsgateway_product): from custom.ilsgateway import PRODUCTS_CODES_PROGRAMS_MAPPING product = super(ILSGatewayAPI, self).product_sync(ilsgateway_product) programs = list(Program.by_domain(self.domain)) for program, products in PRODUCTS_CODES_PROGRAMS_MAPPING.iteritems(): if product.code in products: existing_program = filter(lambda p: p.name == program, programs) if not existing_program: new_program = Program(domain=self.domain) new_program.name = program new_program.save() product.program_id = new_program.get_id product.save() else: product.program_id = existing_program[0].get_id product.save() return product
def drilldown_map(self): options = [{"val": ALL_OPTION, "text": "All", "next": []}] for program in Program.by_domain(self.domain): products = [{"val": ALL_OPTION, "text": "All", "next": []}] for product in Product.by_program_id(self.domain, program._id): products.append({"val": product.get_id, "text": product.name + ' (%s)' % product.code}) options.append({"val": program.get_id, "text": program.name, "next": products}) return options
def test_selective_program_sync(self): user = self.user Program(domain=user.domain, name="test1", code="t1").save() program_list = Program.by_domain(user.domain) program_xml = self.generate_program_xml(program_list, user) fixture_original = call_fixture_generator(program_fixture_generator, user) deprecated_generate_restore_payload(self.domain_obj, user) self.assertXmlEqual(program_xml, ElementTree.tostring(fixture_original[0])) first_sync = self._get_latest_synclog() # make sure the time stamp on this first sync is # not on the same second that the programs were created first_sync.date += datetime.timedelta(seconds=1) # second sync is before any changes are made, so there should # be no programs synced fixture_pre_change = call_fixture_generator(program_fixture_generator, user, last_sync=first_sync) deprecated_generate_restore_payload(self.domain_obj, user) self.assertEqual([], fixture_pre_change, "Fixture was not empty on second sync") second_sync = self._get_latest_synclog() self.assertTrue(first_sync._id != second_sync._id) # save should make the program more recently updated than the # last sync for program in program_list: program.save() # now that we've updated a program, we should get # program data in sync again fixture_post_change = call_fixture_generator(program_fixture_generator, user, last_sync=second_sync) # regenerate the fixture xml to make sure it is still legit self.assertXmlEqual(program_xml, ElementTree.tostring(fixture_post_change[0]))
def delete_program(request, domain, prog_id): program = Program.get(prog_id) program.delete() return json_response({ 'success': True, 'message': _("Program '{program_name}' has successfully been deleted.").format( program_name=program.name, ) })
def test_program_fixture(self): user = self.user Program(domain=user.domain, name="test1", code="t1").save() program_list = Program.by_domain(user.domain) program_xml = self.generate_program_xml(program_list, user) fixture = call_fixture_generator(program_fixture_generator, user) self.assertXmlEqual(program_xml, fixture[0]) # test restore with different user user2 = create_restore_user(self.domain, username='******') self.addCleanup(user2._couch_user.delete) program_xml = self.generate_program_xml(program_list, user2) fixture = call_fixture_generator(program_fixture_generator, user2) self.assertXmlEqual(program_xml, fixture[0])
def delete_program(request, domain, prog_id): program = Program.get(prog_id) program.delete() return JsonResponse({ 'success': True, 'message': _("Program '{program_name}' has successfully been deleted.").format( program_name=program.name, ) })
def commtrack_programs(): if app.commtrack_enabled: programs = Program.by_domain(app.domain) return [{ 'value': program.get_id, 'label': program.name } for program in programs] else: return []
def make_program(domain, name, code, default=False): p = Program() p.domain = domain p.name = name p.code = code.lower() p.default = default p.save() return p
def program_data(self): data = [] programs = Program.by_domain(self.domain) for p in programs: info = p._doc info['is_default'] = info.pop('default') info['edit_url'] = reverse('commtrack_program_edit', kwargs={'domain': self.domain, 'prog_id': p._id}) info['delete_url'] = reverse('delete_program', kwargs={'domain': self.domain, 'prog_id': p._id}) data.append(info) return data
def get_or_create_default_program(domain): program = Program.default_for_domain(domain) if program: return program else: return make_program(domain, _('Uncategorized'), _('uncategorized'), default=True)
def test_program_fixture(self): user = create_restore_user(self.domain.name) Program(domain=user.domain, name="test1", code="t1").save() program_list = Program.by_domain(user.domain) program_xml = self.generate_program_xml(program_list, user) fixture = program_fixture_generator(user, V1) self.assertXmlEqual(program_xml, ElementTree.tostring(fixture[0]))
def rendered_content(self): location = SQLLocation.objects.get( location_id=self.config['location_id']) if location.location_type.administrative: locations = get_descendants(self.config['location_id']) products = self.unique_products(locations, all=True) else: products = location.products programs = { program.get_id: program.name for program in Program.by_domain(self.domain) } headers = [] if 'report_type' in self.config: from custom.ewsghana.reports.specific_reports.stock_status_report import MonthOfStockProduct headers = [ h.html for h in MonthOfStockProduct(self.config).headers ] result = {} for idx, product in enumerate(products, start=1): program = programs[product.program_id] product_dict = { 'name': product.name, 'code': product.code, 'idx': idx if not headers else headers.index(product.code) if product.code in headers else -1, 'checked': self.config['program'] is None or self.config['program'] == product.program_id } if program in result: result[program]['product_list'].append(product_dict) if result[program]['all'] and not product_dict['checked']: result[program]['all'] = False else: result[program] = { 'product_list': [product_dict], 'all': product_dict['checked'] } for _, product_dict in result.iteritems(): product_dict['product_list'].sort(key=lambda prd: prd['name']) return render_to_string( 'ewsghana/partials/product_selection_pane.html', { 'products_by_program': result, 'is_rendered_as_email': self.config.get('is_rendered_as_email', False), 'hide_columns': self.hide_columns })
def _report_info(self): program_id = self.request.GET.get('filter_by_program') return [['Title of report', 'Location', 'Date range', 'Program'], [ self.title, self.location.name if self.location else 'NATIONAL', '{} - {}'.format(ews_date_format(self.datespan.startdate), ews_date_format(self.datespan.enddate)), 'all' if not program_id or program_id == 'all' else Program.get(docid=program_id).name ], []]
def clean_name(self): name = self.cleaned_data['name'] other_program_names = [ p['name'] for p in Program.by_domain(self.program.domain, wrap=False) if p['_id'] != self.program._id ] if name in other_program_names: raise forms.ValidationError(_('Name already in use')) return name
def _report_info(self): program_id = self.request.GET.get('filter_by_program') return [ ['Title of report', 'Location', 'Date range', 'Program'], [ self.title, self.active_location.name, '{} - {}'.format(self.datespan.startdate_display, self.datespan.enddate_display), 'all' if not program_id or program_id == 'all' else Program.get(docid=program_id).name ], [] ]
def get_or_create_default_program(domain): program = Program.default_for_domain(domain) if program: return program else: return make_program( domain, _('Uncategorized'), _('uncategorized'), default=True )
def create_test_products(domain): program = Program(domain=domain, name='HIV/AIDS', code='hiv') program.save() abacavir = Product( domain=domain, name="Abacavir 300mg", code_="abc", program_id=program.get_id, ) abacavir.save() ali = Product( domain=domain, name="AL 20mg/120mg 1X6", code_="ali", program_id=program.get_id, ) ali.save() al = Product( domain=domain, name="AL 20mg/120mg 4x6", code_="alk" ) al.save() ad = Product( domain=domain, name="A-L Dispersible", code_="ad" ) ad.save() al = Product( domain=domain, name="A-L Suspension", code_="al" ) al.save()
def test_selective_program_sync(self): user = self.user Program( domain=user.domain, name="test1", code="t1" ).save() program_list = Program.by_domain(user.domain) program_xml = self.generate_program_xml(program_list, user) fixture_original = call_fixture_generator(program_fixture_generator, user) deprecated_generate_restore_payload(self.domain_obj, user) self.assertXmlEqual( program_xml, ElementTree.tostring(fixture_original[0]) ) first_sync = self._get_latest_synclog() # make sure the time stamp on this first sync is # not on the same second that the programs were created first_sync.date += datetime.timedelta(seconds=1) # second sync is before any changes are made, so there should # be no programs synced fixture_pre_change = call_fixture_generator(program_fixture_generator, user, last_sync=first_sync) deprecated_generate_restore_payload(self.domain_obj, user) self.assertEqual( [], fixture_pre_change, "Fixture was not empty on second sync" ) second_sync = self._get_latest_synclog() self.assertTrue(first_sync._id != second_sync._id) # save should make the program more recently updated than the # last sync for program in program_list: program.save() # now that we've updated a program, we should get # program data in sync again fixture_post_change = call_fixture_generator(program_fixture_generator, user, last_sync=second_sync) # regenerate the fixture xml to make sure it is still legit self.assertXmlEqual( program_xml, ElementTree.tostring(fixture_post_change[0]) )
def test_create_product(self): with open(os.path.join(self.datapath, 'sample_products.json')) as f: product = Product(json.loads(f.read())[0]) self.assertEqual(0, len(Prod.by_domain(TEST_DOMAIN))) ewsghana_product = self.api_object.product_sync(product) self.assertEqual(product.sms_code, ewsghana_product.code.lower()) self.assertEqual(product.name, ewsghana_product.name) self.assertEqual(product.description, ewsghana_product.description) self.assertEqual(product.units, str(ewsghana_product.unit)) self.assertIsNotNone(ewsghana_product.program_id) program = Program.get(ewsghana_product.program_id) self.assertEqual(product.program.name, program.name) self.assertEqual(product.program.code, program.code)
def test_set_program(self): program_id = uuid.uuid4().hex program = Program(_id=program_id, name="Program Name") self._test_change_messages(UserChangeMessage.program_change, [program], { "program": { "set_program": { "id": program_id, "name": "Program Name" } } }, f"Program: Program Name[{program_id}]")
def update_params(self): self.selected = self.request.GET.get('program') user = WebUser.get_by_username(str(self.request.user)) if not self.selected and \ self.selected != '' and \ user.get_domain_membership(self.domain): self.selected = user.get_domain_membership(self.domain).program_id self.programs = Program.by_domain(self.domain) opts = [ dict(val=program.get_id, text=program.name) for program in self.programs ] self.options = opts
def clean_name(self): name = self.cleaned_data['name'].strip() if not name: raise forms.ValidationError(_('This field is required.')) other_program_names = [ p['name'] for p in Program.by_domain(self.program.domain, wrap=False) if p['_id'] != self.program._id ] if name in other_program_names: raise forms.ValidationError(_('Name already in use')) return name
def ews_product_extension(couch_product, product): if not product.program.code: return couch_product program = Program.get_by_code(couch_product.domain, product.program.code) if not program: program = Program(domain=couch_product.domain) program.name = product.program.name program.code = product.program.code.lower() program._doc_type_attr = "Program" program.save() if couch_product.program_id != program._id: couch_product.program_id = program._id couch_product.save() return couch_product
def test_delete(self): # assign some product to the new program self.products[0].program_id = self.new_program._id self.products[0].save() # make sure start state is okay self.assertEqual( 2, len(Program.by_domain(self.domain.name)) ) self.assertEqual(2, self.default_program.get_products_count()) self.assertEqual(1, self.new_program.get_products_count()) self.assertEqual( self.new_program._id, self.products[0].program_id ) self.assertEqual( self.new_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id ) # stash the id before we delete new_program_id = self.new_program._id self.new_program.delete() with self.assertRaises(ResourceNotFound): Program.get(new_program_id) self.assertEqual(1, len(Program.by_domain(self.domain.name))) self.assertEqual(3, self.default_program.get_products_count()) self.assertEqual( self.default_program._id, Product.get(self.products[0]._id).program_id ) self.assertEqual( self.default_program._id, SQLProduct.objects.get(product_id=self.products[0]._id).program_id )
def __init__(self, *args, **kwargs): domain = None if 'domain' in kwargs: domain = kwargs['domain'] del kwargs['domain'] super(CommtrackUserForm, self).__init__(*args, **kwargs) self.fields['location'].widget = SupplyPointSelectWidget(domain=domain) if Domain.get_by_name(domain).commtrack_enabled: programs = Program.by_domain(domain, wrap=False) choices = list((prog['_id'], prog['name']) for prog in programs) choices.insert(0, ('', '')) self.fields['program_id'].choices = choices else: self.fields['program_id'].widget = forms.HiddenInput()
def _get_fixture_items(self, restore_state): restore_user = restore_state.restore_user project = restore_user.project if not project or not project.commtrack_enabled: return [] data = Program.by_domain(restore_user.domain) if not self._should_sync(data, restore_state.last_sync_log): return [] return simple_fixture_generator(restore_user, self.id, "program", PROGRAM_FIELDS, data)
def sync_openlmis_program(domain, lmis_program): program = get_program(domain, lmis_program) if program is None: program = Program(domain=domain) program.name = lmis_program.name program.code = lmis_program.code.lower() program._doc_type_attr = "Program" program.save() if lmis_program.products: for lmis_product in lmis_program.products: sync_openlmis_product(domain, program, lmis_product) return program
def __init__(self, product, *args, **kwargs): self.product = product kwargs['initial'] = self.product._doc kwargs['initial']['code'] = self.product.code super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = False self.helper.label_class = 'col-sm-3 col-md-4 col-lg-2' self.helper.field_class = 'col-sm-4 col-md-5 col-lg-3' programs = Program.by_domain(self.product.domain) self.fields['program_id'].choices = tuple( (prog.get_id, prog.name) for prog in programs) # make sure to select default program if # this is a new product if not product._id: self.initial['program_id'] = Program.default_for_domain( self.product.domain)._id self.helper.layout = Layout('name', 'code', 'description', 'unit', 'program_id', 'cost')
def program_fixture_generator_json(domain): if Program.by_domain(domain).count() == 0: return None fields = list(PROGRAM_FIELDS) fields.append('@id') uri = 'jr://fixture/{}'.format(ProgramFixturesProvider.id) return { 'id': 'programs', 'uri': uri, 'path': '/programs/program', 'name': 'Programs', 'structure': {f: {'name': f, 'no_option': True} for f in fields}, }
def report_subtitles(self): if self.is_rendered_as_email: program = self.request.GET.get('filter_by_program') products = self.request.GET.getlist('filter_by_product') return mark_safe(""" <br>For Filters:<br> Location: {0}<br> Program: {1}<br> Product: {2}<br> Date range: {3} - {4} """.format( self.location.name, Program.get(program).name if program and program != ALL_OPTION else ALL_OPTION.title(), ", ".join([ p.name for p in SQLProduct.objects.filter(product_id__in=products) ]) if products != ALL_OPTION and products else ALL_OPTION.title(), ews_date_format(self.datespan.startdate_utc), ews_date_format(self.datespan.enddate_utc))) return None