Ejemplo n.º 1
0
    def testReceiptsWithNoOpenRequisition(self):
        # make sure we don't have any open requisitions
        self.assertEqual(
            0,
            len(
                RequisitionCase.open_for_location(self.domain.name,
                                                  self.loc._id)))

        rec_amounts = {
            'pp': 30,
            'pq': 20,
            'pr': 10,
        }
        # rec loc1 pp 10 pq 20...
        handled = handle(
            self.verified_number, 'rec {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v)
                                for k, v in rec_amounts.items())))
        self.assertTrue(handled)

        # should still be no open requisitions
        self.assertEqual(
            0,
            len(
                RequisitionCase.open_for_location(self.domain.name,
                                                  self.loc._id)))
    def testReceipts(self):
        # this tests the requisition specific receipt keyword. not to be confused
        # with the standard stock receipt keyword
        self.testRequisition()

        reqs = RequisitionCase.open_for_location(self.domain.name, self.loc._id)
        self.assertEqual(3, len(reqs))
        req_ids_by_product_code = dict(((RequisitionCase.get(id).get_product().code, id) for id in reqs))

        rec_amounts = {
            'pp': 30,
            'pq': 20,
            'pr': 10,
        }
        # rec loc1 pp 10 pq 20...
        handled = handle(self.user.get_verified_number(), 'rec {loc} {report}'.format(
            loc='loc1',
            report=' '.join('%s %s' % (k, v) for k, v in rec_amounts.items())
        ))
        self.assertTrue(handled)

        # we should have closed the requisitions
        self.assertEqual(0, len(RequisitionCase.open_for_location(self.domain.name, self.loc._id)))

        forms = list(self.get_commtrack_forms())
        self.assertEqual(2, len(forms))

        self.assertEqual(self.sp.location_, forms[1].location_)
        # check updated status
        for code, amt in rec_amounts.items():
            req_case = RequisitionCase.get(req_ids_by_product_code[code])
            self.assertTrue(req_case.closed)
            self.assertEqual(str(amt), req_case.amount_received)
            self.assertEqual(self.user._id, req_case.received_by)
            self.assertTrue(req_case._id in reqs, 'requisition %s should be in %s' % (req_case._id, reqs))
    def testRequisition(self):
        self.assertEqual(0, len(RequisitionCase.open_for_location(self.domain.name, self.loc._id)))
        self.assertEqual(0, len(self.get_commtrack_forms()))

        amounts = {
            'pp': 10,
            'pq': 20,
            'pr': 30,
        }
        # req loc1 pp 10 pq 20...
        handled = handle(self.user.get_verified_number(), 'req {loc} {report}'.format(
            loc='loc1',
            report=' '.join('%s %s' % (k, v) for k, v in amounts.items())
        ))
        self.assertTrue(handled)

        # make sure we got the updated requisitions
        reqs = RequisitionCase.open_for_location(self.domain.name, self.loc._id)
        self.assertEqual(3, len(reqs))

        forms = list(self.get_commtrack_forms())
        self.assertEqual(1, len(forms))

        self.assertEqual(self.sp.location_, forms[0].location_)
        # check updated status
        for code, amt in amounts.items():
            spp = CommCareCase.get(self.spps[code]._id)
            # make sure the index was created
            [req_ref] = spp.reverse_indices
            req_case = RequisitionCase.get(req_ref.referenced_id)
            self.assertEqual(str(amt), req_case.amount_requested)
            self.assertEqual(self.user._id, req_case.requested_by)
            self.assertEqual(req_case.location_, self.sp.location_)
            self.assertTrue(req_case._id in reqs)
            self.assertEqual(spp._id, req_case.get_product_case()._id)
Ejemplo n.º 4
0
def create_requisition(user_id, product_stock_case, transaction):
    req = RequisitionState.from_transactions(user_id, product_stock_case,
                                             [transaction])
    submit_case_blocks(req.to_xml(), req.domain, req.username, req.user_id)
    case = RequisitionCase.get(req.id)
    case.location_ = product_stock_case.location_
    return case
Ejemplo n.º 5
0
    def testRequisition(self):
        # confirm we have a clean start
        self.assertEqual(0, len(RequisitionCase.open_for_location(self.domain.name, self.loc._id)))
        self.assertEqual(0, len(self.get_commtrack_forms(self.domain.name)))

        amounts = {
            'pp': 10,
            'pq': 20,
            'pr': 30,
        }
        # req loc1 pp 10 pq 20...
        handled = handle(self.users[0].get_verified_number(), 'req {loc} {report}'.format(
            loc='loc1',
            report=' '.join('%s %s' % (k, v) for k, v in amounts.items())
        ))

        self.assertTrue(handled)

        # make sure we got the updated requisitions
        reqs = RequisitionCase.open_for_location(self.domain.name, self.loc._id)
        self.assertEqual(1, len(reqs))

        req = RequisitionCase.get(reqs[0])
        [index] = req.indices

        self.assertEqual(req.requisition_status, 'requested')
        self.assertEqual(const.SUPPLY_POINT_CASE_TYPE, index.referenced_type)
        self.assertEqual(self.sp._id, index.referenced_id)
        self.assertEqual('parent_id', index.identifier)

        # check updated status
        for code, amt in amounts.items():
            self.check_stock(code, amt, req._id, 'ct-requested')
            self.check_stock(code, 0, req._id, 'stock')
Ejemplo n.º 6
0
 def get_case_ids(self):
     # todo: too many couch requests
     for c in filter(
         create_unique_filter(lambda id: RequisitionCase.get(id).get_product_case_id()),
         RequisitionCase.open_for_location(self.domain, self.location_id),
     ):
         yield c
Ejemplo n.º 7
0
 def get_case_ids(self):
     # todo: too many couch requests
     for c in filter(
             create_unique_filter(
                 lambda id: RequisitionCase.get(id).get_product_case_id()),
             RequisitionCase.open_for_location(self.domain,
                                               self.location_id)):
         yield c
Ejemplo n.º 8
0
    def testReceipt(self):
        amounts = {
            'pp': 10,
            'pq': 20,
            'pr': 30,
        }

        # start with an open request
        handle(
            self.users[0].get_verified_number(),
            'req {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v) for k, v in amounts.items())
            )
        )

        # fulfill it
        handle(
            self.users[0].get_verified_number(),
            'fulfill {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v) for k, v in amounts.items())
            )
        )

        # grab this first because we are about to close it
        req_id = RequisitionCase.open_for_location(self.domain.name, self.loc._id)[0]

        # mark it received
        handle(
            self.users[0].get_verified_number(),
            'rec {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v) for k, v in amounts.items())
            )
        )

        reqs = RequisitionCase.open_for_location(self.domain.name, self.loc._id)

        # receiving by sms closes the req
        self.assertEqual(0, len(reqs))

        req = RequisitionCase.get(req_id)
        [index] = req.indices

        self.assertEqual(req.requisition_status, 'received')

        # check updated status
        for code, amt in amounts.items():
            self.check_stock(code, 0, req._id, 'stock')
            self.check_stock(code, amt, self.sp._id, 'stock')
Ejemplo n.º 9
0
def raise_events(xform, cases):
    supply_points = [SupplyPointCase.wrap(c._doc) for c in cases if c.type == const.SUPPLY_POINT_CASE_TYPE]
    case_updates = get_case_updates(xform)
    for sp in supply_points:
        created = any(filter(lambda update: update.id == sp._id and update.creates_case(), case_updates))
        supply_point_modified.send(sender=None, supply_point=sp, created=created)
    requisition_cases = [RequisitionCase.wrap(c._doc) for c in cases if c.type == const.REQUISITION_CASE_TYPE]
    if requisition_cases and requisition_cases[0].requisition_status is RequisitionStatus.APPROVED:
        requisition_approved.send(sender=None, requisitions=requisition_cases)
    if requisition_cases and requisition_cases[0].requisition_status is RequisitionStatus.RECEIVED:
        requisition_receipt.send(sender=None, requisitions=requisition_cases)

    requisition_cases = [RequisitionCase.wrap(c._doc) for c in cases if c.type == const.REQUISITION_CASE_TYPE]
    if requisition_cases:
        requisition_modified.send(sender=None, cases=requisition_cases)
Ejemplo n.º 10
0
def create_requisition(user_id, product_stock_case, transaction):
    req = RequisitionState.from_transactions(user_id, product_stock_case, [transaction])
    submit_case_blocks(req.to_xml(), req.domain, req.username,
                       req.user_id)
    case = RequisitionCase.get(req.id)
    case.location_ = product_stock_case.location_
    return case
Ejemplo n.º 11
0
def sync_requisition_from_openlmis(domain, requisition_id, openlmis_endpoint):
    cases = []
    send_notification = False
    lmis_requisition_details = openlmis_endpoint.get_requisition_details(requisition_id)
    if lmis_requisition_details:
        rec_cases = [c for c in RequisitionCase.get_by_external_id(domain, str(lmis_requisition_details.id)) if c.type == const.REQUISITION_CASE_TYPE]

        if len(rec_cases) == 0:
            products = [product for product in lmis_requisition_details.products if product.skipped == False]
            for product in products:
                pdt = Product.get_by_code(domain, product.code.lower())
                if pdt:
                    case = lmis_requisition_details.to_requisition_case(pdt._id)
                    case.save()
                    if case.requisition_status == 'AUTHORIZED':
                        send_notification = True
                    cases.append(case)
        else:
            for case in rec_cases:
                before_status = case.requisition_status
                if apply_updates(case, lmis_requisition_details.to_dict(case.product_id)):
                    after_status = case.requisition_status
                    case.save()
                    if before_status in ['INITIATED', 'SUBMITTED'] and after_status == 'AUTHORIZED':
                        send_notification = True
                cases.append(case)
        return cases, send_notification
    else:
        return None, False
Ejemplo n.º 12
0
 def get_req_id(self):
     reqs = RequisitionCase.open_for_location(self.location["location"].domain, self.location["location"]._id)
     if reqs:
         # only support one open requisition per location
         assert len(reqs) == 1
         return reqs[0]
     else:
         return uuid.uuid4().hex
Ejemplo n.º 13
0
 def get_req_id(self):
     reqs = RequisitionCase.open_for_location(
         self.location['location'].domain, self.location['location']._id)
     if reqs:
         # only support one open requisition per location
         assert (len(reqs) == 1)
         return reqs[0]
     else:
         return uuid.uuid4().hex
Ejemplo n.º 14
0
    def testReceiptsWithNoOpenRequisition(self):
        # make sure we don't have any open requisitions
        self.assertEqual(0, len(RequisitionCase.open_for_location(self.domain.name, self.loc._id)))

        rec_amounts = {
            'pp': 30,
            'pq': 20,
            'pr': 10,
        }
        # rec loc1 pp 10 pq 20...
        handled = handle(self.user.get_verified_number(), 'rec {loc} {report}'.format(
            loc='loc1',
            report=' '.join('%s %s' % (k, v) for k, v in rec_amounts.items())
        ))
        self.assertTrue(handled)

        # should still be no open requisitions
        self.assertEqual(0, len(RequisitionCase.open_for_location(self.domain.name, self.loc._id)))
Ejemplo n.º 15
0
def raise_events(xform, cases):
    requisition_cases = [RequisitionCase.wrap(c._doc) for c in cases if c.type == const.REQUISITION_CASE_TYPE]
    if requisition_cases and requisition_cases[0].requisition_status == RequisitionStatus.APPROVED:
        requisition_approved.send(sender=None, requisitions=requisition_cases)
    if requisition_cases and requisition_cases[0].requisition_status == RequisitionStatus.RECEIVED:
        requisition_receipt.send(sender=None, requisitions=requisition_cases)

    if requisition_cases and requisition_cases[0].requisition_status == RequisitionStatus.REQUESTED:
        requisition_modified.send(sender=None, cases=requisition_cases)
Ejemplo n.º 16
0
    def inactive_testSimpleApproval(self):
        self.testRequisition()

        # approve loc1
        handled = handle(self.user.get_verified_number(), 'approve {loc}'.format(
            loc='loc1',
            ))
        self.assertTrue(handled)
        reqs = RequisitionCase.open_for_location(self.domain.name, self.loc._id)
        self.assertEqual(3, len(reqs))

        for req_id in reqs:
            req_case = RequisitionCase.get(req_id)
            self.assertEqual(RequisitionStatus.APPROVED, req_case.requisition_status)
            self.assertEqual(req_case.amount_requested, req_case.amount_approved)
            self.assertEqual(self.user._id, req_case.approved_by)
            self.assertIsNotNone(req_case.approved_on)
            self.assertTrue(isinstance(req_case.approved_on, datetime))
Ejemplo n.º 17
0
    def testReceipts(self):
        # this tests the requisition specific receipt keyword. not to be confused
        # with the standard stock receipt keyword
        self.testRequisition()

        reqs = RequisitionCase.open_for_location(self.domain.name,
                                                 self.loc._id)
        self.assertEqual(3, len(reqs))
        req_ids_by_product_code = dict(
            ((RequisitionCase.get(id).get_product().code, id) for id in reqs))

        rec_amounts = {
            'pp': 30,
            'pq': 20,
            'pr': 10,
        }
        # rec loc1 pp 10 pq 20...
        handled = handle(
            self.verified_number, 'rec {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v)
                                for k, v in rec_amounts.items())))
        self.assertTrue(handled)

        # we should have closed the requisitions
        self.assertEqual(
            0,
            len(
                RequisitionCase.open_for_location(self.domain.name,
                                                  self.loc._id)))

        forms = list(self.get_commtrack_forms())
        self.assertEqual(2, len(forms))

        self.assertEqual(self.sp.location_, forms[1].location_)
        # check updated status
        for code, amt in rec_amounts.items():
            req_case = RequisitionCase.get(req_ids_by_product_code[code])
            self.assertTrue(req_case.closed)
            self.assertEqual(str(amt), req_case.amount_received)
            self.assertEqual(self.user._id, req_case.received_by)
            self.assertTrue(
                req_case._id in reqs,
                'requisition %s should be in %s' % (req_case._id, reqs))
Ejemplo n.º 18
0
    def testSimplePack(self):
        self.testRequisition()

        # pack loc1
        handled = handle(self.user.get_verified_number(), 'pack {loc}'.format(
            loc='loc1',
        ))
        self.assertTrue(handled)
        reqs = RequisitionCase.open_for_location(self.domain.name, self.loc._id)
        self.assertEqual(3, len(reqs))

        for req_id in reqs:
            req_case = RequisitionCase.get(req_id)
            self.assertEqual(RequisitionStatus.PACKED, req_case.requisition_status)
            self.assertEqual(req_case.amount_requested, req_case.amount_packed)
            self.assertEqual(self.user._id, req_case.packed_by)
            self.assertIsNotNone(req_case.packed_on)
            self.assertTrue(isinstance(req_case.packed_on, datetime))
            self.assertEqual(req_case.product_id, req_case.get_product_case().product)
Ejemplo n.º 19
0
    def testSimplePack(self):
        self.testRequisition()

        # pack loc1
        handled = handle(self.verified_number,
                         'pack {loc}'.format(loc='loc1', ))
        self.assertTrue(handled)
        reqs = RequisitionCase.open_for_location(self.domain.name,
                                                 self.loc._id)
        self.assertEqual(3, len(reqs))

        for req_id in reqs:
            req_case = RequisitionCase.get(req_id)
            self.assertEqual(RequisitionStatus.PACKED,
                             req_case.requisition_status)
            self.assertEqual(req_case.amount_requested, req_case.amount_packed)
            self.assertEqual(self.user._id, req_case.packed_by)
            self.assertIsNotNone(req_case.packed_on)
            self.assertTrue(isinstance(req_case.packed_on, datetime))
            self.assertEqual(req_case.product_id,
                             req_case.get_product_case().product)
Ejemplo n.º 20
0
 def get_transactions(self):
     for case_id in self.get_case_ids():
         # this is going to hit the db a lot
         c = RequisitionCase.get(case_id)
         yield (RequisitionResponse(
             product_id=c.product_id,
             case_id=c._id,
             action_name=self.action_name,
             value=c.get_default_value(),
             inferred=True,
             config=self.config,
         ))
Ejemplo n.º 21
0
 def get_transactions(self):
     for case_id in self.get_case_ids():
         # this is going to hit the db a lot
         c = RequisitionCase.get(case_id)
         yield(RequisitionResponse(
             product_id = c.product_id,
             case_id=c._id,
             action_name=self.action_name,
             value=c.get_default_value(),
             inferred=True,
             config=self.config,
         ))
Ejemplo n.º 22
0
    def testRequisition(self):
        self.assertEqual(
            0,
            len(
                RequisitionCase.open_for_location(self.domain.name,
                                                  self.loc._id)))
        self.assertEqual(0, len(self.get_commtrack_forms()))

        amounts = {
            'pp': 10,
            'pq': 20,
            'pr': 30,
        }
        # req loc1 pp 10 pq 20...
        handled = handle(
            self.verified_number, 'req {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v) for k, v in amounts.items())))
        self.assertTrue(handled)

        # make sure we got the updated requisitions
        reqs = RequisitionCase.open_for_location(self.domain.name,
                                                 self.loc._id)
        self.assertEqual(3, len(reqs))

        forms = list(self.get_commtrack_forms())
        self.assertEqual(1, len(forms))

        self.assertEqual(self.sp.location_, forms[0].location_)
        # check updated status
        for code, amt in amounts.items():
            spp = CommCareCase.get(self.spps[code]._id)
            # make sure the index was created
            [req_ref] = spp.reverse_indices
            req_case = RequisitionCase.get(req_ref.referenced_id)
            self.assertEqual(str(amt), req_case.amount_requested)
            self.assertEqual(self.user._id, req_case.requested_by)
            self.assertEqual(req_case.location_, self.sp.location_)
            self.assertTrue(req_case._id in reqs)
            self.assertEqual(spp._id, req_case.get_product_case()._id)
Ejemplo n.º 23
0
    def testSimpleFulfill(self):
        amounts = {
            'pp': 10,
            'pq': 20,
            'pr': 30,
        }

        # start with an open request
        handle(
            self.users[0].get_verified_number(),
            'req {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v) for k, v in amounts.items())
            )
        )

        # fulfill loc1
        handled = handle(
            self.users[0].get_verified_number(),
            'fulfill {loc} {report}'.format(
                loc='loc1',
                report=' '.join('%s %s' % (k, v) for k, v in amounts.items())
            )
        )
        self.assertTrue(handled)

        reqs = RequisitionCase.open_for_location(self.domain.name, self.loc._id)

        # should not have created a new req
        self.assertEqual(1, len(reqs))

        req = RequisitionCase.get(reqs[0])
        [index] = req.indices

        self.assertEqual(req.requisition_status, 'fulfilled')

        for code, amt in amounts.items():
            self.check_stock(code, amt, req._id, 'stock')
            self.check_stock(code, amt, req._id, 'ct-fulfilled')
 def testSyncRequisition(self):
     with open(os.path.join(self.datapath, 'sample_program.json')) as f:
         lmis_program = Program.from_json(json.loads(f.read()))
     commtrack_program = sync_openlmis_program(TEST_DOMAIN, lmis_program)
     test_product = {
         'name': 'Test',
         'code': 'P151',
         'unit': 10,
         'description': 'decs',
         'category': 'category',
     }
     sync_openlmis_product(TEST_DOMAIN, commtrack_program, test_product)
     sync_requisition_from_openlmis(TEST_DOMAIN, 1, self.api)
     self.assertTrue(1, len(RequisitionCase.get_by_external(TEST_DOMAIN, 1)))
Ejemplo n.º 25
0
def sync_requisition_from_openlmis(domain, requisition_id, openlmis_endpoint):
    cases = []
    send_notification = False
    lmis_requisition_details = openlmis_endpoint.get_requisition_details(requisition_id)
    rec_cases = [RequisitionCase.wrap(c._doc) for c in RequisitionCase.get_by_external_id(domain, lmis_requisition_details.id) if c.type == const.REQUISITION_CASE_TYPE]
    if rec_cases is None:
        for product in lmis_requisition_details.products:
            pdt = Product.get_by_code(domain, product.code)
            case = lmis_requisition_details.to_requisition_case(pdt._id)
            case.save()
            if case.requisition_status is 'AUTHORIZED':
                send_notification = True
            cases.append(case)
    else:
        for case in rec_cases:
            before_status = case.requisition_status
            if _apply_updates(case, lmis_requisition_details.to_requisition_case(case.product_id)):
                after_status = case.requisition_status
                case.save()
                if before_status in ['INITIATED', 'SUBMITTED'] and after_status is 'AUTHORIZED':
                    send_notification = True
            cases.append(case)
    return cases, send_notification
Ejemplo n.º 26
0
def raise_events(xform, cases):
    requisition_cases = [
        RequisitionCase.wrap(c._doc) for c in cases
        if c.type == const.REQUISITION_CASE_TYPE
    ]
    if requisition_cases and requisition_cases[
            0].requisition_status == RequisitionStatus.APPROVED:
        requisition_approved.send(sender=None, requisitions=requisition_cases)
    if requisition_cases and requisition_cases[
            0].requisition_status == RequisitionStatus.RECEIVED:
        requisition_receipt.send(sender=None, requisitions=requisition_cases)

    if requisition_cases and requisition_cases[
            0].requisition_status == RequisitionStatus.REQUESTED:
        requisition_modified.send(sender=None, cases=requisition_cases)
 def fixmetestSyncRequisition(self):
     with open(os.path.join(self.datapath, 'sample_program.json')) as f:
         lmis_program = Program.from_json(json.loads(f.read()))
     commtrack_program = sync_openlmis_program(TEST_DOMAIN, lmis_program)
     test_product = LMISProduct.from_json({
         "programCode": "ESS_MEDS",
         "programName": "ESSENTIAL MEDICINES",
         "productCode": "P26",
         "productName": "Erythromycin ethyl succinate, pwd oral suspension, 125mg/5ml",
         "description": "TDF/FTC/EFV",
         "unit": 10,
         "category": "Analgesics"
     })
     sync_openlmis_product(TEST_DOMAIN, commtrack_program, test_product)
     sync_requisition_from_openlmis(TEST_DOMAIN, 1, self.api)
     self.assertTrue(1, len(RequisitionCase.get_by_external(TEST_DOMAIN, 1)))
Ejemplo n.º 28
0
def attach_locations(xform, cases):
    """
    Given a received form and cases, update the location of that form to the location
    of its cases (if they have one).
    """

    # todo: this won't change locations if you are trying to do that via XML.
    # this is mainly just a performance thing so you don't have to do extra lookups
    # every time you touch a case

    if cases:
        found_loc = None
        for case in cases:
            loc = None
            if not case.location_:
                if case.type == const.SUPPLY_POINT_CASE_TYPE:
                    loc_id = getattr(case, 'location_id', None)
                    if loc_id:
                        loc = Location.get(loc_id)
                        case.bind_to_location(loc)

                elif case.type == const.SUPPLY_POINT_PRODUCT_CASE_TYPE:
                    wrapped_case = SupplyPointProductCase.wrap(case._doc)
                    sp = wrapped_case.get_supply_point_case()
                    if sp and sp.location_:
                        loc = sp.location_
                        case.location_ = loc

                elif case.type == const.REQUISITION_CASE_TYPE:
                    req = RequisitionCase.wrap(case._doc)
                    prod = req.get_product_case()
                    if prod and prod.location_ and prod.location_ != case.location_:
                        case.location_ = prod.location_
                        case.save()

            if loc and found_loc and loc != found_loc:
                raise Exception(
                    'Submitted a commtrack case with multiple locations in a single form. '
                    'This is currently not allowed.'
                )
            found_loc = loc

        case = cases[0]
        if case.location_ is not None:
            # should probably store this in computed_
            xform.location_ = list(case.location_)
Ejemplo n.º 29
0
def sync_requisition_from_openlmis(domain, requisition_id, openlmis_endpoint):
    cases = []
    send_notification = False
    lmis_requisition_details = openlmis_endpoint.get_requisition_details(requisition_id)
    if lmis_requisition_details:
        rec_cases = [c for c in RequisitionCase.get_by_external_id(domain, str(lmis_requisition_details.id)) if c.type == const.REQUISITION_CASE_TYPE]

        if len(rec_cases) == 0:
            products = [product for product in lmis_requisition_details.products if product.skipped == False]
            for product in products:
                pdt = Product.get_by_code(domain, product.code.lower())
                if pdt:
                    case = lmis_requisition_details.to_requisition_case(pdt._id)
                    case.save()
                    if case.requisition_status == 'AUTHORIZED':
                        send_notification = True
                    cases.append(case)
 def fixmetestSyncRequisition(self):
     with open(os.path.join(self.datapath, 'sample_program.json')) as f:
         lmis_program = Program.from_json(json.loads(f.read()))
     commtrack_program = sync_openlmis_program(TEST_DOMAIN, lmis_program)
     test_product = LMISProduct.from_json({
         "programCode": "ESS_MEDS",
         "programName": "ESSENTIAL MEDICINES",
         "productCode": "P26",
         "productName":
         "Erythromycin ethyl succinate, pwd oral suspension, 125mg/5ml",
         "description": "TDF/FTC/EFV",
         "unit": 10,
         "category": "Analgesics"
     })
     sync_openlmis_product(TEST_DOMAIN, commtrack_program, test_product)
     sync_requisition_from_openlmis(TEST_DOMAIN, 1, self.api)
     self.assertTrue(1, len(RequisitionCase.get_by_external(TEST_DOMAIN,
                                                            1)))
Ejemplo n.º 31
0
    def requisition_case_id(self):
        # for somewhat obscure reasons, the case_id is the id of the
        # supply_point_product case, so we add a new field for this.
        # though for newly created requisitions it's just empty
        if self.base_action_type == RequisitionActions.REQUEST:
            return None
        if self.base_action_type == RequisitionActions.RECEIPTS:
            # for receipts the id should point to the most recent open requisition
            # (or none)
            try:
                product_stock_case = SupplyPointProductCase.get(self.case_id)
                return RequisitionCase.open_for_product_case(
                    self.domain, product_stock_case.location_[-1],
                    self.case_id)[0]
            except IndexError:
                # there was no open requisition. this is ok
                return None

        assert False, "%s is an unexpected action type!" % self.base_action_type
Ejemplo n.º 32
0
    def requisition_case_id(self):
        # for somewhat obscure reasons, the case_id is the id of the
        # supply_point_product case, so we add a new field for this.
        # though for newly created requisitions it's just empty
        if self.base_action_type == RequisitionActions.REQUEST:
            return None
        if self.base_action_type == RequisitionActions.RECEIPTS:
            # for receipts the id should point to the most recent open requisition
            # (or none)
            try:
                product_stock_case = SupplyPointProductCase.get(self.case_id)
                return RequisitionCase.open_for_product_case(
                    self.domain, product_stock_case.location_[-1], self.case_id
                )[0]
            except IndexError:
                # there was no open requisition. this is ok
                return None

        assert False, "%s is an unexpected action type!" % self.base_action_type
Ejemplo n.º 33
0
def send_notifications(xform, cases):
    # TODO: fix circular imports
    from corehq.apps.commtrack.requisitions import get_notification_recipients
    from corehq.apps.commtrack.requisitions import get_notification_message

    # for now the only notifications are for requisitions that were touched.
    # todo: if we wanted to include previously requested items we could do so
    # by either polling for other open requisitions here, or by ensuring that
    # they get touched by the commtrack case processing.
    requisitions = [RequisitionCase.wrap(case._doc) for case in cases if case.type == const.REQUISITION_CASE_TYPE]

    if requisitions:
        by_status = defaultdict(list)
        for r in requisitions:
            by_status[r.requisition_status].append(r)

        req_config = CommtrackConfig.for_domain(requisitions[0].domain).requisition_config
        # since each state transition might trigger a different person to be notified
        for s, reqs in by_status.items():
            next_action = req_config.get_next_action(RequisitionStatus.to_action_type(s))

            if next_action:
                # we could make this even more customizable by specifying it per requisition
                # but that would get even messier in terms of constructing the messages
                # so we'll just compose one message per status type now, and then send
                # it to everyone who should be notified.
                to_notify = filter(
                    create_unique_filter(lambda u: u._id),
                    itertools.chain(*(get_notification_recipients(next_action, r) for r in reqs)),
                )

                msg = get_notification_message(next_action, reqs)
                for u in to_notify:
                    phone = u.get_verified_number()
                    if phone:
                        send_sms_to_verified_number(phone, msg)
Ejemplo n.º 34
0
    def test_create_fulfill_and_receive_requisition(self):
        amounts = [(p._id, 50.0 + float(i*10)) for i, p in enumerate(self.products)]

        # ----------------
        # Create a request
        # ----------------

        self.submit_xml_form(create_requisition_xml(amounts))
        req_cases = list(get_cases_in_domain(self.domain.name, type=const.REQUISITION_CASE_TYPE))
        self.assertEqual(1, len(req_cases))
        req = RequisitionCase.get(req_cases[0]._id)
        [index] = req.indices

        self.assertEqual(req.requisition_status, 'requested')
        self.assertEqual(const.SUPPLY_POINT_CASE_TYPE, index.referenced_type)
        self.assertEqual(self.sp._id, index.referenced_id)
        self.assertEqual('parent_id', index.identifier)
        # TODO: these types of tests probably belong elsewhere
        self.assertEqual(req.get_next_action().keyword, 'fulfill')
        self.assertEqual(req.get_location()._id, self.sp.location._id)
        self.assertEqual(len(RequisitionCase.open_for_location(
            self.domain.name,
            self.sp.location._id
        )), 1)
        self.assertEqual(
            get_notification_message(
                req.get_next_action(),
                [req]
            ),
            self.expected_notification_message(req, amounts)
        )

        for product, amt in amounts:
            self.check_stock_models(req, product, amt, 0, 'ct-requested')

        # ----------------
        # Mark it fulfilled
        # -----------------

        self.submit_xml_form(create_fulfillment_xml(req, amounts))

        req = RequisitionCase.get(req._id)

        self.assertEqual(req.requisition_status, 'fulfilled')
        self.assertEqual(req.get_next_action().keyword, 'rec')
        self.assertEqual(
            get_notification_message(
                req.get_next_action(),
                [req]
            ),
            self.expected_notification_message(req, amounts)
        )

        for product, amt in amounts:
            # we are expecting two separate blocks to have come with the same
            # values
            self.check_stock_models(req, product, amt, amt, 'stock')
            self.check_stock_models(req, product, amt, 0, 'ct-fulfilled')

        # ----------------
        # Mark it received
        # ----------------

        self.submit_xml_form(create_received_xml(req, amounts))

        req = RequisitionCase.get(req._id)

        self.assertEqual(req.requisition_status, 'received')
        self.assertIsNone(req.get_next_action())
        self.assertEqual(len(RequisitionCase.open_for_location(
            self.domain.name,
            self.sp.location._id
        )), 0)

        for product, amt in amounts:
            self.check_stock_models(req, product, 0, -amt, 'stock')
            self.check_stock_models(self.sp, product, amt, amt, 'stock')
Ejemplo n.º 35
0
 def to_requisition_case(self, product_id):
     req_case = RequisitionCase()
     req_case.user_id = self.agent_code
     req_case.set_case_property("program_id", self.program_id)
     req_case.set_case_property("period_id", self.period_id)
     req_case.product_id = product_id
     req_case.external_id = self.id
     req_case.requisition_status = self.requisition_status
     req_case.set_case_property("order_id", self.order_id)
     req_case.set_case_property("order_status", self.order_status)
     req_case.set_case_property("emergency", self.emergency)
     req_case.set_case_property("start_date", self.period_start_date)
     req_case.set_case_peoperty("end_date", self.period_end_date)
     return req_case
Ejemplo n.º 36
0
    def to_requisition_case(self, product_id, case_id=None, case_rev=None):
        req_case = RequisitionCase()
        req_case.type = REQUISITION_CASE_TYPE
        req_case.user_id = self.agent_code
        req_case.set_case_property("program_id", self.program_id)
        req_case.set_case_property("period_id", self.period_id)
        req_case.product_id = product_id
        req_case.external_id = self.id
        req_case.requisition_status = self.requisition_status
        req_case.set_case_property("order_id", self.order_id)
        req_case.set_case_property("order_status", self.order_status)
        req_case.set_case_property("emergency", self.emergency)
        req_case.set_case_property("start_date", self.period_start_date)
        req_case.set_case_property("end_date", self.period_end_date)

        if case_id:
            req_case._id = case_id
        if case_rev:
            req_case._rev = case_rev

        return req_case
Ejemplo n.º 37
0
    def to_requisition_case(self, product_id, case_id=None, case_rev=None):
        req_case = RequisitionCase()
        req_case.type = REQUISITION_CASE_TYPE
        req_case.user_id = self.agent_code
        req_case.set_case_property("program_id", self.program_id)
        req_case.set_case_property("period_id", self.period_id)
        req_case.product_id = product_id
        req_case.external_id = self.id
        req_case.requisition_status = self.requisition_status
        req_case.set_case_property("order_id", self.order_id)
        req_case.set_case_property("order_status", self.order_status)
        req_case.set_case_property("emergency", self.emergency)
        req_case.set_case_property("start_date", self.period_start_date)
        req_case.set_case_property("end_date", self.period_end_date)

        if case_id:
            req_case._id = case_id
        if case_rev:
            req_case._rev = case_rev

        return req_case
Ejemplo n.º 38
0
    def test_create_fulfill_and_receive_requisition(self):
        amounts = [(p._id, 50.0 + float(i * 10))
                   for i, p in enumerate(self.products)]

        # ----------------
        # Create a request
        # ----------------

        self.submit_xml_form(create_requisition_xml(amounts))
        req_cases = list(
            get_cases_in_domain(self.domain.name,
                                type=const.REQUISITION_CASE_TYPE))
        self.assertEqual(1, len(req_cases))
        req = RequisitionCase.get(req_cases[0]._id)
        [index] = req.indices

        self.assertEqual(req.requisition_status, 'requested')
        self.assertEqual(const.SUPPLY_POINT_CASE_TYPE, index.referenced_type)
        self.assertEqual(self.sp._id, index.referenced_id)
        self.assertEqual('parent_id', index.identifier)
        # TODO: these types of tests probably belong elsewhere
        self.assertEqual(req.get_next_action().keyword, 'fulfill')
        self.assertEqual(req.get_location()._id, self.sp.location._id)
        self.assertEqual(
            len(
                RequisitionCase.open_for_location(self.domain.name,
                                                  self.sp.location._id)), 1)
        self.assertEqual(
            get_notification_message(req.get_next_action(), [req]),
            self.expected_notification_message(req, amounts))

        for product, amt in amounts:
            self.check_stock_models(req, product, amt, 0, 'ct-requested')

        # ----------------
        # Mark it fulfilled
        # -----------------

        self.submit_xml_form(create_fulfillment_xml(req, amounts))

        req = RequisitionCase.get(req._id)

        self.assertEqual(req.requisition_status, 'fulfilled')
        self.assertEqual(req.get_next_action().keyword, 'rec')
        self.assertEqual(
            get_notification_message(req.get_next_action(), [req]),
            self.expected_notification_message(req, amounts))

        for product, amt in amounts:
            # we are expecting two separate blocks to have come with the same
            # values
            self.check_stock_models(req, product, amt, amt, 'stock')
            self.check_stock_models(req, product, amt, 0, 'ct-fulfilled')

        # ----------------
        # Mark it received
        # ----------------

        self.submit_xml_form(create_received_xml(req, amounts))

        req = RequisitionCase.get(req._id)

        self.assertEqual(req.requisition_status, 'received')
        self.assertIsNone(req.get_next_action())
        self.assertEqual(
            len(
                RequisitionCase.open_for_location(self.domain.name,
                                                  self.sp.location._id)), 0)

        for product, amt in amounts:
            self.check_stock_models(req, product, 0, -amt, 'stock')
            self.check_stock_models(self.sp, product, amt, amt, 'stock')