Example #1
0
    def test_archive(self):
        bootstrap_products(self.domain)
        products = sorted(Product.by_domain(self.domain), key=lambda p: p._id)
        original_list = Product.by_domain(self.domain, wrap=False)

        products[0].archive()

        new_list = Product.by_domain(self.domain, wrap=False)

        self.assertTrue(
            products[0]._id not in [p['_id'] for p in new_list],
            "Archived product still returned by Product.by_domain()")

        self.assertEqual(len(new_list), len(original_list) - 1)

        self.assertEqual(
            len(
                Product.by_domain(self.domain,
                                  wrap=False,
                                  include_archived=True)), len(original_list))

        self.assertEqual(
            SQLProduct.objects.filter(domain=self.domain,
                                      is_archived=True).count(), 1)

        products[0].unarchive()

        self.assertEqual(len(original_list),
                         len(Product.by_domain(self.domain, wrap=False)))
Example #2
0
    def test_archive(self):
        original_list = Product.by_domain(self.domain.name, wrap=False)

        self.products[0].archive()

        new_list = Product.by_domain(self.domain.name, wrap=False)

        self.assertTrue(
            self.products[0]._id not in [p['_id'] for p in new_list],
            "Archived product still returned by Product.by_domain()")

        self.assertEqual(len(new_list), len(original_list) - 1)

        self.assertEqual(
            len(
                Product.by_domain(self.domain.name,
                                  wrap=False,
                                  include_archived=True)), len(original_list))

        self.assertEqual(
            SQLProduct.objects.filter(domain=self.domain.name,
                                      is_archived=True).count(), 1)

        self.products[0].unarchive()

        self.assertEqual(len(original_list),
                         len(Product.by_domain(self.domain.name, wrap=False)))
Example #3
0
    def test_archive(self):
        bootstrap_products(self.domain)
        products = sorted(Product.by_domain(self.domain), key=lambda p: p._id)
        original_list = Product.by_domain(self.domain, wrap=False)

        products[0].archive()

        new_list = Product.by_domain(self.domain, wrap=False)

        self.assertTrue(
            products[0]._id not in [p['_id'] for p in new_list],
            "Archived product still returned by Product.by_domain()"
        )

        self.assertEqual(
            len(new_list),
            len(original_list) - 1
        )

        self.assertEqual(
            len(Product.by_domain(self.domain, wrap=False, include_archived=True)),
            len(original_list)
        )

        self.assertEqual(
            SQLProduct.objects.filter(domain=self.domain, is_archived=True).count(),
            1
        )

        products[0].unarchive()

        self.assertEqual(
            len(original_list),
            len(Product.by_domain(self.domain, wrap=False))
        )
Example #4
0
    def test_archive(self):
        original_list = Product.by_domain(self.domain.name, wrap=False)

        self.products[0].archive()

        new_list = Product.by_domain(self.domain.name, wrap=False)

        self.assertTrue(
            self.products[0]._id not in [p['_id'] for p in new_list],
            "Archived product still returned by Product.by_domain()"
        )

        self.assertEqual(
            len(new_list),
            len(original_list) - 1
        )

        self.assertEqual(
            len(Product.by_domain(self.domain.name, wrap=False, include_archived=True)),
            len(original_list)
        )

        self.assertEqual(
            SQLProduct.objects.filter(domain=self.domain.name, is_archived=True).count(),
            1
        )

        self.products[0].unarchive()

        self.assertEqual(
            len(original_list),
            len(Product.by_domain(self.domain.name, wrap=False))
        )
Example #5
0
 def _column_tuples(self):
     product_ids = [p._id for p in Product.by_domain(self.domain)]
     return sorted(
         list(
             StockState.objects.filter(product_id__in=product_ids).values_list("product_id", "section_id").distinct()
         )
     )
Example #6
0
    def setUp(self):
        super(XMLTest, self).setUp()
        self.domain = util.bootstrap_domain(util.TEST_DOMAIN)
        util.bootstrap_location_types(self.domain.name)
        util.bootstrap_products(self.domain.name)
        self.products = sorted(Product.by_domain(self.domain.name),
                               key=lambda p: p._id)
        self.ct_settings = SQLCommtrackConfig.for_domain(self.domain.name)
        self.ct_settings.sqlconsumptionconfig = SQLConsumptionConfig(
            min_transactions=0,
            min_window=0,
            optimal_window=60,
        )
        self.ct_settings.save()
        self.ct_settings.sqlconsumptionconfig.commtrack_settings = self.ct_settings
        self.ct_settings.sqlconsumptionconfig.save()
        self.domain = Domain.get(self.domain._id)

        self.loc = make_loc('loc1')
        self.sp = self.loc.linked_supply_point()
        self.users = [
            util.bootstrap_user(self, **user_def)
            for user_def in self.user_definitions
        ]
        self.user = self.users[0]
Example #7
0
    def rows(self):

        def row_in_names(row, names):
            if row in names:
                return True, names.index(row)+1
            else:
                for idx, val in enumerate(names):
                    if unicode(row).lower() in PRODUCT_NAMES.get(val, []):
                        return True, idx+1
            return False, 0

        commandes = ['Comanndes']
        raux = ['Recu']
        taux = ['Taux']
        products = Product.by_domain(self.config['domain'])
        for product in products:
            commandes.append(0)
            raux.append(0)
            taux.append(0)
        names = []

        for product in products:
            names.append(unicode(product.name).lower())
        rows = super(DispDesProducts, self).rows
        for row in rows:
            exits, index = row_in_names(row[0], names)
            if exits:
                commandes[index] = row[1]
                raux[index] = row[2]
                taux[index] = "%d%%" % (100*row[2]['html']/(row[1]['html'] or 1))
        return [commandes, raux, taux]
Example #8
0
    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
Example #9
0
    def __init__(self, domain, *args, **kwargs):
        self.domain = domain
        super(ConsumptionForm, 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'

        layout = []
        products = Product.by_domain(domain)
        for p in products:
            field_name = 'default_%s' % p._id
            display = _('Default %(product_name)s') % {'product_name': p.name}
            layout.append(field_name)
            self.fields[field_name] = forms.DecimalField(
                label=display,
                required=False,
                initial=get_default_monthly_consumption(
                    self.domain,
                    p._id,
                    None,
                    None
                )
            )

        layout.append(hqcrispy.FormActions(
            ButtonHolder(
                Submit('submit', ugettext_lazy('Update Default Consumption Info'))
            )
        ))
        self.helper.layout = Layout(*layout)
Example #10
0
    def __init__(self, domain, *args, **kwargs):
        self.domain = domain
        super(ConsumptionForm, 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'

        layout = []
        products = Product.by_domain(domain)
        for p in products:
            field_name = 'default_%s' % p._id
            display = _('Default %(product_name)s') % {'product_name': p.name}
            layout.append(field_name)
            self.fields[field_name] = forms.DecimalField(
                label=display,
                required=False,
                initial=get_default_monthly_consumption(
                    self.domain,
                    p._id,
                    None,
                    None
                )
            )

        layout.append(hqcrispy.FormActions(
            ButtonHolder(
                Submit('submit', ugettext_lazy('Update Default Consumption Info'))
            )
        ))
        self.helper.layout = Layout(*layout)
Example #11
0
 def _column_tuples(self):
     product_ids = [p._id for p in Product.by_domain(self.domain)]
     return sorted(
         list(
             StockState.objects.filter(
                 product_id__in=product_ids).values_list(
                     'product_id', 'section_id').distinct()))
Example #12
0
    def clean_name(self):
        name = self.cleaned_data['name']

        other_products = [p for p in Product.by_domain(self.product.domain) if p._id != self.product._id]
        if name in [p.name for p in other_products]:
            raise forms.ValidationError('name already in use')

        return name
Example #13
0
def all_sms_codes(domain):
    config = CommtrackConfig.for_domain(domain)

    actions = dict((action.keyword, action) for action in config.actions)
    products = dict((p.code, p) for p in Product.by_domain(domain))

    sms_codes = zip(('action', 'product'), (actions, products))
    return dict(itertools.chain(*([(k.lower(), (type, v)) for k, v in six.iteritems(codes)] for type, codes in sms_codes)))
 def setUp(self):
     self.datapath = os.path.join(os.path.dirname(__file__), 'data')
     self.api = MockOpenLMISEndpoint("uri://mock/lmis/endpoint", username='******', password='******')
     initial_bootstrap(TEST_DOMAIN)
     bootstrap_domain(TEST_DOMAIN)
     delete_all_cases()
     for product in Product.by_domain(TEST_DOMAIN):
         product.delete()
Example #15
0
    def test_selective_product_sync(self):
        user = self.user

        expected_xml = self.generate_product_fixture_xml(user)

        product_list = Product.by_domain(user.domain)
        self._initialize_product_names(len(product_list))

        fixture_original = call_fixture_generator(product_fixture_generator, user)[1]
        deprecated_generate_restore_payload(self.domain_obj, user)
        self.assertXmlEqual(
            expected_xml,
            ElementTree.tostring(fixture_original)
        )

        first_sync = sorted(SyncLog.view(
            "phone/sync_logs_by_user",
            include_docs=True,
            reduce=False
        ).all(), key=lambda x: x.date)[-1]

        # make sure the time stamp on this first sync is
        # not on the same second that the products were created
        first_sync.date += datetime.timedelta(seconds=1)

        # second sync is before any changes are made, so there should
        # be no products synced
        fixture_pre_change = call_fixture_generator(product_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 = sorted(SyncLog.view(
            "phone/sync_logs_by_user",
            include_docs=True,
            reduce=False
        ).all(), key=lambda x: x.date)[-1]

        self.assertTrue(first_sync._id != second_sync._id)

        # save should make the product more recently updated than the
        # last sync
        for product in product_list:
            product.save()

        # now that we've updated a product, we should get
        # product data in sync again
        fixture_post_change = call_fixture_generator(product_fixture_generator, user, last_sync=second_sync)[1]

        # regenerate the fixture xml to make sure it is still legit
        self.assertXmlEqual(
            expected_xml,
            ElementTree.tostring(fixture_post_change)
        )
Example #16
0
    def test_selective_product_sync(self):
        user = bootstrap_user(self, phone_number="1234567890")

        expected_xml = self.generate_product_fixture_xml(user)

        product_list = Product.by_domain(user.domain)
        self._initialize_product_names(len(product_list))

        fixture_original = product_fixture_generator(user, V1)
        generate_restore_payload(user.to_casexml_user())
        self.assertXmlEqual(
            expected_xml,
            ElementTree.tostring(fixture_original[0])
        )

        first_sync = sorted(SyncLog.view(
            "phone/sync_logs_by_user",
            include_docs=True,
            reduce=False
        ).all(), key=lambda x: x.date)[-1]

        # make sure the time stamp on this first sync is
        # not on the same second that the products were created
        first_sync.date += datetime.timedelta(seconds=1)

        # second sync is before any changes are made, so there should
        # be no products synced
        fixture_pre_change = product_fixture_generator(user, V1, last_sync=first_sync)
        generate_restore_payload(user.to_casexml_user())
        self.assertEqual(
            [],
            fixture_pre_change,
            "Fixture was not empty on second sync"
        )

        second_sync = sorted(SyncLog.view(
            "phone/sync_logs_by_user",
            include_docs=True,
            reduce=False
        ).all(), key=lambda x: x.date)[-1]

        self.assertTrue(first_sync._id != second_sync._id)

        # save should make the product more recently updated than the
        # last sync
        for product in product_list:
            product.save()

        # now that we've updated a product, we should get
        # product data in sync again
        fixture_post_change = product_fixture_generator(user, V1, last_sync=second_sync)

        # regenerate the fixture xml to make sure it is still legit
        self.assertXmlEqual(
            expected_xml,
            ElementTree.tostring(fixture_post_change[0])
        )
Example #17
0
    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 setUpClass(cls):
     super(SMSTests, cls).setUpClass()
     cls.backend, cls.backend_mapping = setup_default_sms_test_backend()
     cls.domain = util.bootstrap_domain(util.TEST_DOMAIN)
     util.bootstrap_location_types(cls.domain.name)
     util.bootstrap_products(cls.domain.name)
     cls.products = sorted(Product.by_domain(cls.domain.name), key=lambda p: p._id)
     cls.loc = util.make_loc('loc1')
     cls.sp = cls.loc.linked_supply_point()
     cls.users = [util.bootstrap_user(cls, **user_def) for user_def in cls.user_definitions]
    def testCreateProgram(self):
        with open(os.path.join(self.datapath, 'sample_program.json')) as f:
            lmis_program = Program.from_json(json.loads(f.read()))

        # program sync
        self.assertEqual(0, len(Product.by_domain(TEST_DOMAIN)))
        commtrack_program = sync_openlmis_program(TEST_DOMAIN, lmis_program)
        self.assertEqual(lmis_program.name, commtrack_program.name)
        self.assertEqual(lmis_program.code.lower(), commtrack_program.code)

        # product sync
        self.assertEqual(len(lmis_program.products), len(Product.by_domain(TEST_DOMAIN)))
        lmis_product = lmis_program.products[0]
        product = Product.get_by_code(TEST_DOMAIN, lmis_product.code)
        self.assertEqual(product.code, lmis_product.code.lower())
        self.assertEqual(product.name, lmis_product.name)
        self.assertEqual(product.description, lmis_product.description)
        self.assertEqual(product.unit, str(lmis_product.unit))
        self.assertEqual(product.category, str(lmis_product.category))
Example #20
0
    def tearDown(self):
        delete_all_locations()
        delete_all_users()

        delete_domain_phone_numbers(self.TEST_DOMAIN)

        for product in Product.by_domain(self.TEST_DOMAIN):
            product.delete()

        super(MissingReportNotificationTestCase, self).tearDown()
Example #21
0
 def setUpClass(cls):
     super(SMSTests, cls).setUpClass()
     cls.backend, cls.backend_mapping = setup_default_sms_test_backend()
     cls.domain = util.bootstrap_domain(util.TEST_DOMAIN)
     util.bootstrap_location_types(cls.domain.name)
     util.bootstrap_products(cls.domain.name)
     cls.products = sorted(Product.by_domain(cls.domain.name), key=lambda p: p._id)
     cls.loc = util.make_loc('loc1')
     cls.sp = cls.loc.linked_supply_point()
     cls.users = [util.bootstrap_user(cls, **user_def) for user_def in cls.user_definitions]
Example #22
0
    def tearDown(self):
        delete_all_locations()
        delete_all_users()

        delete_domain_phone_numbers(self.TEST_DOMAIN)

        for product in Product.by_domain(self.TEST_DOMAIN):
            product.delete()

        super(MissingReportNotificationTestCase, self).tearDown()
Example #23
0
    def testCreateProgram(self):
        with open(os.path.join(self.datapath, 'sample_program.json')) as f:
            lmis_program = Program.from_json(json.loads(f.read()))

        # program sync
        self.assertEqual(0, len(Product.by_domain(TEST_DOMAIN)))
        commtrack_program = sync_openlmis_program(TEST_DOMAIN, lmis_program)
        self.assertEqual(lmis_program.name, commtrack_program.name)
        self.assertEqual(lmis_program.code.lower(), commtrack_program.code)

        # product sync
        self.assertEqual(len(lmis_program.products),
                         len(Product.by_domain(TEST_DOMAIN)))
        lmis_product = lmis_program.products[0]
        product = Product.get_by_code(TEST_DOMAIN, lmis_product.code)
        self.assertEqual(product.code, lmis_product.code.lower())
        self.assertEqual(product.name, lmis_product.name)
        self.assertEqual(product.description, lmis_product.description)
        self.assertEqual(product.unit, str(lmis_product.unit))
        self.assertEqual(product.category, str(lmis_product.category))
Example #24
0
def all_sms_codes(domain):
    config = CommtrackConfig.for_domain(domain)

    actions = dict((action.keyword, action) for action in config.actions)
    products = dict((p.code, p) for p in Product.by_domain(domain))
    commands = {
        config.multiaction_keyword: {'type': 'stock_report_generic', 'caption': 'Stock Report'},
    }

    sms_codes = zip(('action', 'product', 'command'), (actions, products, commands))
    return dict(itertools.chain(*([(k.lower(), (type, v)) for k, v in codes.iteritems()] for type, codes in sms_codes)))
Example #25
0
def all_sms_codes(domain):
    config = CommtrackConfig.for_domain(domain)

    actions = dict((action.keyword, action) for action in config.actions)
    products = dict((p.code, p) for p in Product.by_domain(domain))
    commands = {
        config.multiaction_keyword: {'type': 'stock_report_generic', 'caption': 'Stock Report'},
    }

    sms_codes = zip(('action', 'product', 'command'), (actions, products, commands))
    return dict(itertools.chain(*([(k.lower(), (type, v)) for k, v in codes.iteritems()] for type, codes in sms_codes)))
Example #26
0
 def consumption(self):
     consumptions = []
     for product in Product.by_domain(self.domain):
         consumption = get_default_monthly_consumption(
             self.domain,
             product._id,
             self.location.location_type_name,
             self.location.supply_point_id or None,
         )
         if consumption:
             consumptions.append((product.name, consumption))
     return consumptions
Example #27
0
    def tearDown(self):
        delete_all_locations()

        for user in WebUser.by_domain(self.TEST_DOMAIN):
            user.delete()

        delete_domain_phone_numbers(self.TEST_DOMAIN)

        for product in Product.by_domain(self.TEST_DOMAIN):
            product.delete()

        super(UrgentNonReportingNotificationTestCase, self).tearDown()
Example #28
0
    def tearDown(self):
        for location in Location.by_domain(self.TEST_DOMAIN):
            location.delete()

        for user in WebUser.by_domain(self.TEST_DOMAIN):
            user.delete()

        for vn in VerifiedNumber.by_domain(self.TEST_DOMAIN):
            vn.delete()

        for product in Product.by_domain(self.TEST_DOMAIN):
            product.delete()
Example #29
0
 def consumption(self):
     consumptions = []
     for product in Product.by_domain(self.domain):
         consumption = get_default_monthly_consumption(
             self.domain,
             product._id,
             self.location.location_type_name,
             self.location.supply_point_id or None,
         )
         if consumption:
             consumptions.append((product.name, consumption))
     return consumptions
Example #30
0
    def tearDown(self):
        for location in Location.by_domain(self.TEST_DOMAIN):
            location.delete()

        for user in WebUser.by_domain(self.TEST_DOMAIN):
            user.delete()

        delete_domain_phone_numbers(self.TEST_DOMAIN)

        for product in Product.by_domain(self.TEST_DOMAIN):
            product.delete()

        super(MissingReportNotificationTestCase, self).tearDown()
Example #31
0
 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()
Example #32
0
 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()
Example #33
0
    def tearDown(self):
        for location in Location.by_domain(self.TEST_DOMAIN):
            location.delete()

        for user in WebUser.by_domain(self.TEST_DOMAIN):
            user.delete()

        delete_domain_phone_numbers(self.TEST_DOMAIN)

        for product in Product.by_domain(self.TEST_DOMAIN):
            product.delete()

        super(MissingReportNotificationTestCase, self).tearDown()
Example #34
0
 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()
Example #35
0
 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()
Example #36
0
def product_fixture_generator(user, version, case_sync_op=None, last_sync=None):
    fields = [
        'name',
        'unit',
        'code',
        'description',
        'category',
        'program_id',
        'cost',
        'product_data'
    ]
    data_fn = lambda: Product.by_domain(user.domain, include_archived=True)
    return _simple_fixture_generator(user, "product", fields, data_fn, last_sync)
Example #37
0
 def consumption(self):
     consumptions = []
     for product in Product.by_domain(self.domain):
         consumption = get_default_monthly_consumption(
             self.domain,
             product._id,
             self.location.location_type,
             # FIXME accessing this value from the sql location
             # would be faster
             self.supply_point._id if self.supply_point else None,
         )
         if consumption:
             consumptions.append((product.name, consumption))
     return consumptions
Example #38
0
 def consumption(self):
     consumptions = []
     for product in Product.by_domain(self.domain):
         consumption = get_default_monthly_consumption(
             self.domain,
             product._id,
             self.location.location_type_name,
             # FIXME accessing this value from the sql location
             # would be faster
             self.supply_point.case_id if self.supply_point else None,
         )
         if consumption:
             consumptions.append((product.name, consumption))
     return consumptions
Example #39
0
    def test_archive(self):
        original_list = Product.by_domain(self.domain.name, wrap=False)

        self.products[0].archive()

        new_list = Product.by_domain(self.domain.name, wrap=False)

        self.assertTrue(
            self.products[0]._id not in [p["_id"] for p in new_list],
            "Archived product still returned by Product.by_domain()",
        )

        self.assertEqual(len(new_list), len(original_list) - 1)

        self.assertEqual(
            len(Product.by_domain(self.domain.name, wrap=False, include_archived=True)), len(original_list)
        )

        self.assertEqual(len(Product.archived_by_domain(self.domain.name, wrap=False, include_archived=True)), 1)

        self.products[0].unarchive()

        self.assertEqual(len(original_list), len(Product.by_domain(self.domain.name, wrap=False)))
Example #40
0
 def include_consumption(self):
     if bool(self.include_consumption_flag and self.domain_obj.
             commtrack_settings.individual_consumption_defaults):
         # we'll be needing these, so init 'em:
         self.products = Product.by_domain(self.domain)
         self.product_codes = [p.code for p in self.products]
         self.supply_point_map = SupplyInterface(
             self.domain).get_supply_point_ids_by_location()
         self.administrative_types = {
             lt.name
             for lt in self.location_types if lt.administrative
         }
         return True
     return False
Example #41
0
    def test_selective_product_sync(self):
        user = self.user

        expected_xml = self.generate_product_fixture_xml(user)

        product_list = Product.by_domain(user.domain)
        self._initialize_product_names(len(product_list))

        fixture_original = call_fixture_generator(product_fixture_generator, user)[1]
        deprecated_generate_restore_payload(self.domain_obj, user)
        self.assertXmlEqual(
            expected_xml,
            ElementTree.tostring(fixture_original)
        )

        first_sync = self._get_latest_synclog()

        # make sure the time stamp on this first sync is
        # not on the same second that the products were created
        first_sync.date += datetime.timedelta(seconds=1)

        # second sync is before any changes are made, so there should
        # be no products synced
        fixture_pre_change = call_fixture_generator(product_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 product more recently updated than the
        # last sync
        for product in product_list:
            product.save()

        # now that we've updated a product, we should get
        # product data in sync again
        fixture_post_change = call_fixture_generator(product_fixture_generator, user, last_sync=second_sync)[1]

        # regenerate the fixture xml to make sure it is still legit
        self.assertXmlEqual(
            expected_xml,
            ElementTree.tostring(fixture_post_change)
        )
Example #42
0
 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()
Example #43
0
    def setUp(self):
        super(CommTrackTest, self).setUp()
        # might as well clean house before doing anything
        delete_all_xforms()
        delete_all_cases()
        delete_all_sync_logs()

        StockReport.objects.all().delete()
        StockTransaction.objects.all().delete()

        self.backend, self.backend_mapping = setup_default_sms_test_backend()

        self.domain = bootstrap_domain(TEST_DOMAIN)
        bootstrap_location_types(self.domain.name)
        bootstrap_products(self.domain.name)
        self.ct_settings = CommtrackConfig.for_domain(self.domain.name)
        self.ct_settings.consumption_config = ConsumptionConfig(
            min_transactions=0,
            min_window=0,
            optimal_window=60,
            min_periods=0,
        )
        # todo: remove?
        if self.requisitions_enabled:
            self.ct_settings.requisition_config = get_default_requisition_config(
            )

        self.ct_settings.save()

        self.domain = Domain.get(self.domain._id)

        self.loc = make_loc('loc1')
        self.sp = self.loc.linked_supply_point()
        self.users = [
            bootstrap_user(self, **user_def)
            for user_def in self.user_definitions
        ]

        # everyone should be in a group.
        self.group = Group(domain=TEST_DOMAIN,
                           name='commtrack-folks',
                           users=[u._id for u in self.users],
                           case_sharing=True)
        self.group._id = self.sp.owner_id
        self.group.save()
        self.products = sorted(Product.by_domain(self.domain.name),
                               key=lambda p: p._id)
        self.assertEqual(3, len(self.products))
Example #44
0
    def include_consumption(self):
        if bool(
            self.include_consumption_flag and
            self.domain_obj.commtrack_settings.individual_consumption_defaults
        ):
            # we'll be needing these, so init 'em:
            self.products = Product.by_domain(self.domain)
            self.product_codes = [p.code for p in self.products]
            self.supply_point_map = SupplyPointCase.get_location_map_by_domain(self.domain)
            self.administrative_types = {
                lt.name for lt in self.domain_obj.location_types
                if lt.administrative

            }
            return True
        return False
Example #45
0
def recalculate_domain_consumption(domain):
    """
    Given a domain, recalculate all saved consumption settings in that domain.
    """
    # note: might get slow as this gets huge
    found_doc_ids = DocDomainMapping.objects.filter(domain_name=domain, doc_type="CommCareCase").values_list(
        "doc_id", flat=True
    )
    products = Product.by_domain(domain)
    for supply_point_id in found_doc_ids:
        for product in products:
            filtered_transactions = StockTransaction.objects.filter(
                case_id=supply_point_id, product_id=product._id, section_id=const.SECTION_TYPE_STOCK
            ).order_by("-report__date", "-pk")
            if filtered_transactions:
                update_stock_state_for_transaction(filtered_transactions[0])
Example #46
0
    def setUp(self):
        # might as well clean house before doing anything
        delete_all_xforms()
        delete_all_cases()
        delete_all_sync_logs()

        StockReport.objects.all().delete()
        StockTransaction.objects.all().delete()

        self.backend = test.bootstrap(TEST_BACKEND, to_console=True)
        self.domain = bootstrap_domain()
        bootstrap_location_types(self.domain.name)
        bootstrap_products(self.domain.name)
        self.ct_settings = CommtrackConfig.for_domain(self.domain.name)
        self.ct_settings.consumption_config = ConsumptionConfig(
            min_transactions=0,
            min_window=0,
            optimal_window=60,
            min_periods=0,
        )
        if self.requisitions_enabled:
            self.ct_settings.requisition_config = get_default_requisition_config()

        self.ct_settings.save()

        self.domain = Domain.get(self.domain._id)

        self.loc = make_loc('loc1')
        self.sp = make_supply_point(self.domain.name, self.loc)
        self.users = [bootstrap_user(self, **user_def) for user_def in self.user_definitions]

        if False:
            # bootstrap additional users for requisitions
            # needs to get reinserted for requisition stuff later
            self.approver = bootstrap_user(self, **APPROVER_USER)
            self.packer = bootstrap_user(self, **PACKER_USER)
            self.users += [self.approver, self.packer]

        # everyone should be in a group.
        self.group = Group(domain=TEST_DOMAIN, name='commtrack-folks',
                           users=[u._id for u in self.users],
                           case_sharing=True)
        self.group.save()
        self.sp.owner_id = self.group._id
        self.sp.save()
        self.products = sorted(Product.by_domain(self.domain.name), key=lambda p: p._id)
        self.assertEqual(3, len(self.products))
Example #47
0
 def __init__(self, domain, *args, **kwargs):
     self.domain = domain
     super(ConsumptionForm, self).__init__(*args, **kwargs)
     products = Product.by_domain(domain)
     for p in products:
         field_name = 'default_%s' % p._id
         display = _('Default %(product_name)s') % {'product_name': p.name}
         self.fields[field_name] = forms.DecimalField(
             label=display,
             required=False,
             initial=get_default_monthly_consumption(
                 self.domain,
                 p._id,
                 None,
                 None
             )
         )
Example #48
0
def recalculate_domain_consumption(domain):
    """
    Given a domain, recalculate all saved consumption settings in that domain.
    """
    # note: might get slow as this gets huge
    found_doc_ids = DocDomainMapping.objects.filter(
        domain_name=domain,
        doc_type='CommCareCase',
    ).values_list('doc_id', flat=True)
    products = Product.by_domain(domain)
    for supply_point_id in found_doc_ids:
        for product in products:
            filtered_transactions = StockTransaction.get_ordered_transactions_for_stock(
                supply_point_id, const.SECTION_TYPE_STOCK, product._id
            )
            if filtered_transactions:
                update_stock_state_for_transaction(filtered_transactions[0])
Example #49
0
 def __init__(self, domain, *args, **kwargs):
     self.domain = domain
     super(ConsumptionForm, self).__init__(*args, **kwargs)
     products = Product.by_domain(domain)
     for p in products:
         field_name = 'default_%s' % p._id
         display = _('Default %(product_name)s') % {'product_name': p.name}
         self.fields[field_name] = forms.DecimalField(
             label=display,
             required=False,
             initial=get_default_monthly_consumption(
                 self.domain,
                 p._id,
                 None,
                 None
             )
         )
Example #50
0
    def setUpClass(cls):
        super(StockStateTest, cls).setUpClass()
        cls.domain_obj = util.bootstrap_domain(cls.domain)
        util.bootstrap_location_types(cls.domain)
        util.bootstrap_products(cls.domain)
        cls.ct_settings = CommtrackConfig.for_domain(cls.domain)
        cls.ct_settings.use_auto_consumption = True
        cls.ct_settings.consumption_config = ConsumptionConfig(
            min_transactions=0,
            min_window=0,
            optimal_window=60,
            min_periods=0,
        )
        cls.ct_settings.save()

        cls.loc = util.make_loc('loc1', domain=cls.domain)
        cls.sp = cls.loc.linked_supply_point()
        cls.products = sorted(Product.by_domain(cls.domain), key=lambda p: p._id)
Example #51
0
def recalculate_domain_consumption(domain):
    """
    Given a domain, recalculate all saved consumption settings in that domain.
    """
    # note: might get slow as this gets huge
    found_doc_ids = DocDomainMapping.objects.filter(
        domain_name=domain,
        doc_type='CommCareCase',
    ).values_list('doc_id', flat=True)
    products = Product.by_domain(domain)
    for supply_point_id in found_doc_ids:
        for product in products:
            filtered_transactions = StockTransaction.objects.filter(
                case_id=supply_point_id,
                product_id=product._id,
                section_id=const.SECTION_TYPE_STOCK,
            ).order_by('-report__date', '-pk')
            if filtered_transactions:
                update_stock_state_for_transaction(filtered_transactions[0])
Example #52
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()
Example #53
0
    def copy_products(self):
        from corehq.apps.products.models import Product
        from corehq.apps.programs.models import Program
        from corehq.apps.products.views import ProductFieldsView

        self._copy_custom_data(ProductFieldsView.field_type)

        program_map = {}
        programs = Program.by_domain(self.existing_domain)
        for program in programs:
            old_id, new_id = self.save_couch_copy(program, self.new_domain)
            program_map[old_id] = new_id

        products = Product.by_domain(self.existing_domain)
        for product in products:
            if product.program_id:
                try:
                    product.program_id = program_map[product.program_id]
                except:
                    self.stderr('Missing program {} for product {}'.format(product.program_id, product._id))
            self.save_couch_copy(product, self.new_domain)
Example #54
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()
Example #55
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()
Example #56
0
    def setUpClass(cls):
        super(StockStateTest, cls).setUpClass()
        cls.domain_obj = util.bootstrap_domain(cls.domain)
        util.bootstrap_location_types(cls.domain)
        util.bootstrap_products(cls.domain)
        cls.ct_settings = SQLCommtrackConfig.for_domain(cls.domain)
        cls.ct_settings.use_auto_consumption = True
        cls.ct_settings.sqlconsumptionconfig = SQLConsumptionConfig(
            min_transactions=0,
            min_window=0,
            optimal_window=60,
        )
        cls.ct_settings.save()
        cls.ct_settings.sqlconsumptionconfig.commtrack_settings = cls.ct_settings
        cls.ct_settings.sqlconsumptionconfig.save()

        cls.loc = util.make_loc('loc1', domain=cls.domain)
        cls.sp = cls.loc.linked_supply_point()
        cls.products = sorted(Product.by_domain(cls.domain),
                              key=lambda p: p._id)

        cls.process_ledger_changes = process_pillow_changes(
            'LedgerToElasticsearchPillow')
Example #57
0
def recalculate_domain_consumption(domain):
    """
    Given a domain, recalculate all saved consumption settings in that domain.
    """
    # note: might get slow as this gets huge
    found_doc_ids = DocDomainMapping.objects.filter(
        domain_name=domain,
        doc_type='CommCareCase',
    ).values_list('doc_id', flat=True)
    products = Product.by_domain(domain)
    for supply_point_id in found_doc_ids:
        for product in products:
            try:
                latest_transaction = StockTransaction.get_ordered_transactions_for_stock(
                    supply_point_id, const.SECTION_TYPE_STOCK, product._id)[0]
            except IndexError:
                pass
            else:
                state = get_stock_state_for_transaction(latest_transaction)
                daily_consumption = get_consumption_for_ledger(state)
                state.daily_consumption = daily_consumption
                with drop_connected_signals(post_save):
                    state.save()