Ejemplo n.º 1
0
    def test_stock_on_hand_language_english(self):
        with localize("en"):
            response = unicode(LANGUAGE_CONFIRM)
            response2 = unicode(SOH_CONFIRM)

        language_message = """
            5551234 > language en
            5551234 < {0}
        """.format(
            unicode(response % dict(language="English"))
        )
        self.run_script(language_message)

        script = """
            5551234 > hmk fs100md100
            5551234 < %(soh_confirm)s
        """ % {
            "soh_confirm": response2
        }
        self.run_script(script)

        with localize("sw"):
            response = unicode(LANGUAGE_CONFIRM)

        language_message = """
            5551234 > language sw
            5551234 < {0}
        """.format(
            unicode(response % dict(language="Swahili"))
        )
        self.run_script(language_message)
Ejemplo n.º 2
0
    def test_stock_on_hand_language_english(self):
        with localize('en'):
            response = six.text_type(LANGUAGE_CONFIRM)
            response2 = six.text_type(SOH_CONFIRM)

        language_message = """
            5551234 > language en
            5551234 < {0}
        """.format(six.text_type(response % dict(language='English')))
        self.run_script(language_message)

        script = """
            5551234 > hmk fs100md100
            5551234 < %(soh_confirm)s
        """ % {"soh_confirm": response2}
        self.run_script(script)

        with localize('sw'):
            response = six.text_type(LANGUAGE_CONFIRM)

        language_message = """
            5551234 > language sw
            5551234 < {0}
        """.format(six.text_type(response % dict(language='Swahili')))
        self.run_script(language_message)
Ejemplo n.º 3
0
def upload(dropbox_helper_id, access_token, size, max_retries):
    from .models import DropboxUploadHelper
    helper = DropboxUploadHelper.objects.get(id=dropbox_helper_id)

    def progress_callback(bytes_uploaded, helper=helper, size=size):
        helper.progress = float(bytes_uploaded) / size
        helper.save()

    try:
        dropbox_path = '/{}'.format(os.path.basename(helper.src))
        path_display = upload_to_dropbox(access_token, dropbox_path, helper.src, progress_callback)
    except Exception as e:
        helper.failure_reason = str(e)
        helper.save()

    couch_user = CouchUser.get_by_username(helper.user.username)
    if helper.failure_reason is None:
        dbx = Dropbox(access_token)
        path_link_metadata = dbx.sharing_create_shared_link_with_settings(
            path_display,
            SharedLinkSettings(
                requested_visibility=RequestedVisibility.team_only,
            ),
        )
        context = {
            'share_url': path_link_metadata.url,
            'path': os.path.join(
                'Apps',
                settings.DROPBOX_APP_NAME,
                path_link_metadata.name,
            )
        }
        with localize(couch_user.get_language_code()):
            subject = _('{} has been uploaded to dropbox!'.format(helper.dest))
            html_content = render_to_string('dropbox/emails/upload_success.html', context)
            text_content = render_to_string('dropbox/emails/upload_success.txt', context)
    else:
        context = {
            'reason': helper.failure_reason,
            'path': helper.dest
        }
        with localize(couch_user.get_language_code()):
            subject = _('{} has failed to upload to dropbox'.format(helper.dest))
            html_content = render_to_string('dropbox/emails/upload_error.html', context)
            text_content = render_to_string('dropbox/emails/upload_error.txt', context)

    send_HTML_email(
        subject,
        helper.user.email,
        html_content,
        text_content=text_content,
    )
Ejemplo n.º 4
0
    def test_product_aliases(self):
        with localize("sw"):
            response = unicode(SOH_CONFIRM)

        script = """
            5551234 > Hmk iucd 400
            5551234 < {}
        """.format(
            response
        )
        self.run_script(script)

        script = """
            5551234 > Hmk Depo 569
            5551234 < {}
        """.format(
            response
        )
        self.run_script(script)

        script = """
            5551234 > Hmk IMPL 678
            5551234 < %(soh_confirm)s
        """ % {
            "soh_confirm": response
        }
        self.run_script(script)
Ejemplo n.º 5
0
    def test_reminder(self):
        now = datetime.utcnow()
        self.assertEqual(0, len(list(StockoutReminder(TEST_DOMAIN, now).get_people())))
        script = """
            5551234 > Hmk Id 400 Dp 620 Ip 678
        """
        self.run_script(script)
        self.assertEqual(1, len(list(StockoutReminder(TEST_DOMAIN, now).get_people())))

        script = """
            5551235 > Hmk Id 0 Dp 0 Ip 0
        """
        self.run_script(script)

        with localize('sw'):
            reminder_stockout = unicode(REMINDER_STOCKOUT)

        StockoutReminder(TEST_DOMAIN, now).send()
        script = """
            5551235 < %s
        """ % reminder_stockout % {
            'products_list': 'dp, id, ip',
            'overstocked_list': 'Test Facility 1 (dp, ip)'
        }
        self.run_script(script)
Ejemplo n.º 6
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (
                _(DEFAULT_REPORT_NOTIF_SUBJECT)
                if self.email_subject == DEFAULT_REPORT_NOTIF_SUBJECT
                else self.email_subject
            )

            attach_excel = getattr(self, 'attach_excel', False)
            content, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel,
                send_only_active=True
            )

            # Will be False if ALL the ReportConfigs in the ReportNotification
            # have a start_date in the future.
            if content is False:
                return

            for email in emails:
                body = render_full_report_notification(None, content, email, self).content
                send_html_email_async.delay(
                    title, email, body,
                    email_from=settings.DEFAULT_FROM_EMAIL,
                    file_attachments=excel_files)
Ejemplo n.º 7
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (
                _(DEFAULT_REPORT_NOTIF_SUBJECT)
                if self.email_subject == DEFAULT_REPORT_NOTIF_SUBJECT
                else self.email_subject
            )

            attach_excel = getattr(self, "attach_excel", False)
            content, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel
            )
            slugs = [r.report_slug for r in self.configs]

            for email in emails:
                body = render_full_report_notification(None, content, email, self).content
                send_html_email_async.delay(
                    title,
                    email,
                    body,
                    email_from=settings.DEFAULT_FROM_EMAIL,
                    file_attachments=excel_files,
                    ga_track=True,
                    ga_tracking_info={"cd4": self.domain, "cd10": ", ".join(slugs)},
                )
Ejemplo n.º 8
0
def get_month(form, prop):
    value = form.form.get(prop, "")
    if value:
        with localize("fr"):
            return format(force_to_datetime(value), "E")
    else:
        return value
Ejemplo n.º 9
0
    def get_fixture(self, restore_user_id, data_provider):
        """
        Generate a fixture representation of the indicator set. Something like the following:
           <fixture id="indicators:bihar-supervisor" user_id="3ce8b1611c38e956d3b3b84dd3a7ac18">
              <group id="1012aef098ab0c0" team="Samda Team 1">
                 <indicators>
                    <indicator id="bp">
                       <name>BP Visits last 30 days</name>
                       <done>25</done>
                       <due>22</due>
                       <clients>
                          <client id="a1029b09c090s9d173" status="done"></client>
                          <client id="bad7a1029b09c090s9" status="due"></client>
                       </clients>
                    </indicator>
                 </indicators>
              </group>
           </fixture>
        """

        def _el(tag, text, attrib=None):
            attrib = attrib or {}
            el = ElementTree.Element(tag, attrib=attrib)
            el.text = unicode(text)
            return el

        def _indicator_to_fixture(indicator):
            ind_el = ElementTree.Element("indicator", attrib={"id": indicator.slug})
            done, due = data_provider.get_indicator_data(indicator)
            ind_el.append(_el("name", indicator.name, attrib={"lang": "en"}))
            ind_el.append(_el("name", _(indicator.name), attrib={"lang": "hin"}))
            ind_el.append(_el("done", done))
            ind_el.append(_el("due", due))
            clients = ElementTree.Element("clients")
            for case_id, data in data_provider.get_case_data(indicator).items():
                client = ElementTree.Element(
                    "client", attrib={"id": case_id, "status": "done" if data["num"] else "due"}
                )
                clients.append(client)
            ind_el.append(clients)
            return ind_el

        # switch to hindi so we can use our builtin translations
        with localize("hin"):
            root = ElementTree.Element("fixture", attrib={"id": self.id, "user_id": restore_user_id})
            group = ElementTree.Element(
                "group", attrib={"id": data_provider.groups[0]._id, "team": data_provider.groups[0].name}
            )
            root.append(group)
            indicators = ElementTree.Element("indicators")

            # hack: we have to have something with 'clients' show up first in the list
            # context: http://manage.dimagi.com/default.asp?107569
            sorted_indicators = sorted(
                data_provider.summary_indicators, key=lambda indicator: -len(data_provider.get_case_data(indicator))
            )
            for indicator in sorted_indicators:
                indicators.append(_indicator_to_fixture(indicator))
            group.append(indicators)
            return root
Ejemplo n.º 10
0
 def _send_submission_alert_to_msd(self, params):
     users = filter(lambda u: u.user_data.get('role', None) == 'MSD', CommCareUser.by_domain(self.domain))
     for user in users:
         if not user.get_verified_number():
             continue
         with localize(user.get_language_code()):
             send_sms_to_verified_number(user.get_verified_number(), SUBMITTED_NOTIFICATION_MSD % params)
Ejemplo n.º 11
0
def get_month(form, prop):
    value = form.form.get(prop, '')
    if value:
        with localize('fr'):
            return format(force_to_datetime(value), 'E')
    else:
        return value
Ejemplo n.º 12
0
    def test_losses_adjustments_la_word(self):
        with localize('sw'):
            response1 = unicode(SOH_CONFIRM)
            response2 = unicode(LOSS_ADJUST_CONFIRM)

        sohs = {
            'id': 400,
            'dp': 569,
            'ip': 678
        }

        script = """
            5551234 > Hmk Id 400 Dp 569 Ip 678
            5551234 < {0}
        """.format(response1)
        self.run_script(script)

        self.assertEqual(StockState.objects.filter(case_id=self.facility_sp_id).count(), 3)
        for ps in StockState.objects.all():
            self.assertEqual(self.user_fac1.location.linked_supply_point().get_id, ps.case_id)
            self.assertEqual(ps.stock_on_hand, sohs[ps.sql_product.code])

        script = """
            5551234 > la id -3 dp -5 ip 13
            5551234 < {0}
        """.format(response2)
        self.run_script(script)

        self.assertEqual(StockState.objects.filter(case_id=self.facility_sp_id).count(), 3)

        self.assertEqual(StockState.objects.get(sql_product__code="id").stock_on_hand, 397)
        self.assertEqual(StockState.objects.get(sql_product__code="dp").stock_on_hand, 564)
        self.assertEqual(StockState.objects.get(sql_product__code="ip").stock_on_hand, 691)
Ejemplo n.º 13
0
def send_translated_message(user, message, **kwargs):
    verified_number = user.get_verified_number()
    if not verified_number:
        return False
    with localize(user.get_language_code()):
        send_sms_to_verified_number(verified_number, message % kwargs)
        return True
Ejemplo n.º 14
0
    def report_subtitles(self):
        with localize(self.lang):
            sf = self.report_config.get('sf')
            selected_af = self.request.GET.get('hierarchy_af')
            selected_block = self.request.GET.get('hierarchy_block')
            selected_district = self.request.GET.get('hierarchy_district')
            subtitles = [
                _("Report: {0}").format(self.report.name),
                _("District: {0}").format(selected_district),
            ]
            if not sf or sf in ['sf2', 'sf3', 'sf4']:
                subtitles.extend([
                    _("Block: {0}").format(selected_block),
                ])
                if sf != 'sf4' and selected_af:
                    user = CommCareUser.get(selected_af)
                    subtitles.append(_("AF: {0} {1}").format(user.first_name, user.last_name))

            if sf in ['sf5', 'sf4', 'sf3']:
                subtitles.append(
                    _("Last Reporting Month of the Quarter: {0} {1}").format(
                        calendar.month_name[int(self.request.GET.get('month'))],
                        self.request.GET.get('year')
                    )
                )
            else:
                subtitles.append(
                    _("For Date: {0} to {1}").format(self.datespan.startdate.strftime("%Y-%m-%d"),
                                                     self.datespan.enddate.strftime("%Y-%m-%d"))
                )
            return subtitles
Ejemplo n.º 15
0
def process_verification(phone_number, msg, backend_id=None):
    v = VerifiedNumber.by_phone(phone_number, True)
    if not v:
        return

    if not verification_response_ok(msg.text):
        return

    msg.domain = v.domain
    msg.couch_recipient_doc_type = v.owner_doc_type
    msg.couch_recipient = v.owner_id
    msg.save()

    if not domain_has_privilege(msg.domain, privileges.INBOUND_SMS):
        return

    if backend_id:
        backend = MobileBackend.load(backend_id)
    else:
        backend = MobileBackend.auto_load(phone_number, v.domain)

    # i don't know how to dynamically instantiate this object, which may be any number of doc types...
    #owner = CommCareMobileContactMixin.get(v.owner_id)
    assert v.owner_doc_type == 'CommCareUser'
    owner = CommCareUser.get(v.owner_id)

    v = owner.save_verified_number(v.domain, phone_number, True, backend.name)
    with localize(owner.language):
        send_sms_to_verified_number(v, _(CONFIRM))
Ejemplo n.º 16
0
def send_translated_message(user, message, **kwargs):
    verified_number = get_two_way_number_for_recipient(user)
    if not verified_number:
        return False
    with localize(user.get_language_code()):
        send_sms_to_verified_number(verified_number, message % kwargs)
        return True
Ejemplo n.º 17
0
 def get_message(self, data):
     with localize(self.user.get_language_code()):
         return STOCKOUT_CONFIRM % {
             'contact_name': self.verified_contact.owner.full_name,
             'product_names': self.msg.text.split(' ', 1)[1],
             'facility_name': self.sql_location.name
         }
Ejemplo n.º 18
0
 def test_message_initiator_soh(self):
     with localize('sw'):
         response1 = six.text_type(TEST_HANDLER_CONFIRM)
         response2 = six.text_type(SOH_HELP_MESSAGE)
     script = """
         5551234 > test soh d31049
         5551234 < %(test_handler_confirm)s
         32347 < %(response)s
         32348 < %(response)s
         32349 < %(response)s
         5551234 > test hmk d31049
         5551234 < %(test_handler_confirm)s
         32347 < %(response)s
         32348 < %(response)s
         32349 < %(response)s
         """ % {
         "test_handler_confirm": response1,
         "response": response2
     }
     self.run_script(script)
     supply_point_status = SupplyPointStatus.objects.filter(
         location_id=self.facility3.get_id,
         status_type=SupplyPointStatusTypes.SOH_FACILITY
     ).order_by("-status_date")[0]
     self.assertEqual(SupplyPointStatusValues.REMINDER_SENT, supply_point_status.status_value)
     self.assertEqual(SupplyPointStatusTypes.SOH_FACILITY, supply_point_status.status_type)
Ejemplo n.º 19
0
 def test_yes(self):
     with localize('sw'):
         response = YES_HELP
     script = """
       5551234 > ndio
       5551234 < {0}
     """.format(unicode(response))
     self.run_script(script)
Ejemplo n.º 20
0
 def test_message_initiator_bad_code(self):
     with localize('sw'):
         response = six.text_type(TEST_HANDLER_BAD_CODE)
     script = """
         5551234 > test la d5000000
         5551234 < %(test_bad_code)s
         """ % {"test_bad_code": response % {"code": "d5000000"}}
     self.run_script(script)
Ejemplo n.º 21
0
 def test_message_initiator_help(self):
     with localize('sw'):
         response = six.text_type(TEST_HANDLER_HELP)
     script = """
         5551234 > test
         5551234 < %s
     """ % response
     self.run_script(script)
Ejemplo n.º 22
0
 def test_language_unknown(self):
     with localize('sw'):
         response = six.text_type(LANGUAGE_UNKNOWN)
     script = """
         5551234 > language de
         5551234 < %(language_unknown)s
         """ % {'language_unknown': response % {"language": "de"}}
     self.run_script(script)
Ejemplo n.º 23
0
 def test_stock_on_hand_language_swahili(self):
     with localize('sw'):
         response = six.text_type(SOH_CONFIRM)
     script = """
         5551234 > hmk fs100md100
         5551234 < %(soh_confirm)s
     """ % {"soh_confirm": response}
     self.run_script(script)
Ejemplo n.º 24
0
 def test_losses_adjustments_without_soh(self):
     with localize('sw'):
         response = unicode(LOSS_ADJUST_NO_SOH)
     script = """
         5551234 > um ID -3 dp -5 IP 13
         5551234 < {0}
     """.format(response % {'products_list': 'dp, id, ip'})
     self.run_script(script)
Ejemplo n.º 25
0
 def test_invalid_randr_with_amounts(self):
     with localize('sw'):
         response1 = unicode(SUBMITTED_INVALID_QUANTITY)
     script = """
         555 > nimetuma a dd b 11 c 12
         555 < {0}
     """ .format(response1 % {'number': 'dd'})
     self.run_script(script)
Ejemplo n.º 26
0
 def test_delivery_facility_report_product_error(self):
     with localize('sw'):
         response = unicode(INVALID_PRODUCT_CODE)
     script = """
         5551234 > nimepokea Ig 400 Dp 569 Ip 678
         5551234 < %(error_message)s
         """ % {'error_message': response % {"product_code": "ig"}}
     self.run_script(script)
Ejemplo n.º 27
0
 def test_stock_on_hand_delimiters_all_spaced_out(self):
     with localize('sw'):
         response = six.text_type(SOH_CONFIRM)
     # all space delimited
     script = """
         5551234 > hmk fs 100 md 100 ff 100 dx 100 bp 100 pc 100 qi 100
         5551234 < %(soh_confirm)s
     """ % {"soh_confirm": response}
     self.run_script(script)
Ejemplo n.º 28
0
 def test_language_swahili(self):
     with localize('sw'):
         response = six.text_type(LANGUAGE_CONFIRM)
     script = """
         5551234 > lugha sw
         5551234 < %(language_confirm)s
         """ % {'language_confirm': response % {"language": "Swahili"}}
     self.run_script(script)
     self._verify_language('sw', '5551234')
Ejemplo n.º 29
0
 def test_language_english(self):
     with localize('en'):
         response = six.text_type(LANGUAGE_CONFIRM)
     script = """
         5551234 > language en
         5551234 < %(language_confirm)s
         """ % {'language_confirm': response % {"language": "English"}}
     self.run_script(script)
     self._verify_language('en', '5551234')
Ejemplo n.º 30
0
 def get_message(self, data):
     with localize(self.user.get_language_code()):
         products = sorted([
             (SQLProduct.objects.get(product_id=tx.product_id).code, tx.quantity)
             for tx in data['transactions']
         ], key=lambda x: x[0])
         return DELIVERED_CONFIRM % {'reply_list': ', '.join(
             ['{} {}'.format(product, quantity) for product, quantity in products]
         )}
Ejemplo n.º 31
0
    def test_randr_not_submitted(self):
        with localize('sw'):
            response = unicode(NOT_SUBMITTED_CONFIRM)

        script = """
          5551234 > sijatuma
          5551234 < {0}
        """.format(response)
        self.run_script(script)

        sps = SupplyPointStatus.objects.filter(
            location_id=self.loc1.get_id,
            status_type="rr_fac").order_by("-status_date")[0]

        self.assertEqual(SupplyPointStatusValues.NOT_SUBMITTED,
                         sps.status_value)
        self.assertEqual(SupplyPointStatusTypes.R_AND_R_FACILITY,
                         sps.status_type)
Ejemplo n.º 32
0
    def test_register_facility(self):
        with localize('sw'):
            response = unicode(REGISTRATION_CONFIRM)

        script = """
          5551234 > sajili Test Test d31049
          5551234 < %(registration_confirm)s
        """ % {
            "registration_confirm": response % {
                "sdp_name": self.facility3.name,
                "msd_code": "d31049",
                "contact_name": "Test Test"
            }
        }
        self.run_script(script)
        user = CommCareUser.get_by_username('stella')
        self.assertEqual(user.location.site_code, 'd31049')
        self.assertEqual(user.full_name, 'Test Test')
Ejemplo n.º 33
0
    def test_register_district_uppercase(self):
        with localize('sw'):
            response = six.text_type(REGISTRATION_CONFIRM_DISTRICT)

        script = """
          5551234 > sajili Test Test : TESTDISTRICT
          5551234 < %(registration_confirm)s
        """ % {
            "registration_confirm": response % {
                "sdp_name": self.district3.name,
                "contact_name": "Test Test"
            }
        }
        self.run_script(script)

        self.assertEqual(
            CommCareUser.get_by_username('stella').location.site_code,
            'd10102')
Ejemplo n.º 34
0
    def test_delivery_district_not_received(self):
        with localize('sw'):
            response = unicode(NOT_DELIVERED_CONFIRM)

        script = """
          555 > sijapokea
          555 < {0}
        """.format(response)
        self.run_script(script)

        sps = SupplyPointStatus.objects.filter(
            location_id=self.dis.get_id,
            status_type="del_dist").order_by("-status_date")[0]

        self.assertEqual(SupplyPointStatusValues.NOT_RECEIVED,
                         sps.status_value)
        self.assertEqual(SupplyPointStatusTypes.DELIVERY_DISTRICT,
                         sps.status_type)
Ejemplo n.º 35
0
    def test_delivery_facility_not_received(self):
        with localize('sw'):
            response = six.text_type(NOT_DELIVERED_CONFIRM)

        script = """
            5551234 > sijapokea
            5551234 < {0}
            """.format(response)
        self.run_script(script)

        sps = SupplyPointStatus.objects.filter(
            location_id=self.loc1.get_id,
            status_type="del_fac").order_by("-status_date")[0]

        self.assertEqual(SupplyPointStatusValues.NOT_RECEIVED,
                         sps.status_value)
        self.assertEqual(SupplyPointStatusTypes.DELIVERY_FACILITY,
                         sps.status_type)
Ejemplo n.º 36
0
    def test_help_registered(self):
        with localize('sw'):
            response = unicode(HELP_REGISTERED)

        script = """
          5551234 > msaada
          5551234 < %(help_registered)s
        """ % {
            'help_registered': response
        }
        self.run_script(script)

        script = """
          5555678 > help
          5555678 < %(help_registered)s
        """ % {
            'help_registered': response
        }
        self.run_script(script)
Ejemplo n.º 37
0
    def test_randr_submitted_facility(self):
        with localize('sw'):
            response = unicode(SUBMITTED_CONFIRM)

        script = """
          5551234 > nimetuma
          5551234 < {0}
        """.format(response % {
            "contact_name": self.user_fac1.name,
            "sp_name": self.loc1.name
        })
        self.run_script(script)

        sps = SupplyPointStatus.objects.filter(
            location_id=self.loc1.get_id,
            status_type="rr_fac").order_by("-status_date")[0]

        self.assertEqual(SupplyPointStatusValues.SUBMITTED, sps.status_value)
        self.assertEqual(SupplyPointStatusTypes.R_AND_R_FACILITY,
                         sps.status_type)
Ejemplo n.º 38
0
    def test_stock_on_hand_stockouts(self):
        with localize('sw'):
            response = unicode(SOH_CONFIRM)
        script = """
            5551234 > Hmk Id 0 Dp 0 Ip 0
            5551234 < %(soh_confirm)s
        """ % {
            "soh_confirm": response
        }
        self.run_script(script)

        self.assertEqual(
            StockTransaction.objects.filter(
                case_id=self.facility_sp_id).count(), 3)
        self.assertEqual(
            StockState.objects.filter(case_id=self.facility_sp_id).count(), 3)

        for stock_transaction in StockTransaction.objects.filter(
                case_id=self.facility_sp_id):
            self.assertTrue(stock_transaction.stock_on_hand == 0)
Ejemplo n.º 39
0
    def test_stop(self):
        user = bootstrap_user(self.loc1,
                              username='******',
                              domain=self.domain.name,
                              phone_number='643',
                              first_name='stop',
                              last_name='Person',
                              language='sw')
        self.addCleanup(user.delete)

        with localize('sw'):
            response = str(STOP_CONFIRM)

        script = """
          643 > stop
          643 < {0}
        """.format(response)
        self.run_script(script)
        contact = CommCareUser.get_by_username('stop_person')
        self.assertFalse(contact.is_active)
Ejemplo n.º 40
0
 def test_message_initiator_late_delivery_report_district(self):
     with localize('sw'):
         response1 = six.text_type(TEST_HANDLER_CONFIRM)
         response2 = six.text_type(DELIVERY_LATE_DISTRICT)
     script = """
         5551234 > test latedelivery d10101
         5551234 < %(test_handler_confirm)s
         32350 < %(response)s
         32351 < %(response)s
         32352 < %(response)s
         """ % {
         "test_handler_confirm": response1,
         "response": six.text_type(response2 % {
             'group_name': 'changeme',
             'group_total': 1,
             'not_responded_count': 2,
             'not_received_count': 3
         })
     }
     self.run_script(script)
Ejemplo n.º 41
0
def send_verification(domain, user, phone_number, logged_event):
    backend = MobileBackend.auto_load(phone_number, domain)
    reply_phone = backend.reply_to_phone_number

    subevent = logged_event.create_subevent_for_single_sms(
        user.doc_type, user.get_id)

    with localize(user.language):
        message = _(OUTGOING) % {
            'name':
            user.username.split('@')[0],
            'replyto':
            ' to %s' %
            util.clean_phone_number(reply_phone) if reply_phone else '',
        }
        send_sms(domain,
                 user,
                 phone_number,
                 message,
                 metadata=MessageMetadata(messaging_subevent_id=subevent.pk))
        subevent.completed()
Ejemplo n.º 42
0
 def test_message_initiator_supervision(self):
     with localize('sw'):
         response1 = six.text_type(TEST_HANDLER_CONFIRM)
         response2 = six.text_type(SUPERVISION_REMINDER)
     script = """
         5551234 > test supervision d31049
         5551234 < %(test_handler_confirm)s
         32347 < %(response)s
         32348 < %(response)s
         32349 < %(response)s
         """ % {
         "test_handler_confirm": response1,
         "response": response2
     }
     self.run_script(script)
     supply_point_status = SupplyPointStatus.objects.filter(
         location_id=self.facility3.get_id,
         status_type=SupplyPointStatusTypes.SUPERVISION_FACILITY
     ).order_by("-status_date")[0]
     self.assertEqual(SupplyPointStatusValues.REMINDER_SENT, supply_point_status.status_value)
     self.assertEqual(SupplyPointStatusTypes.SUPERVISION_FACILITY, supply_point_status.status_type)
Ejemplo n.º 43
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (_(DEFAULT_REPORT_NOTIF_SUBJECT) if self.email_subject
                     == DEFAULT_REPORT_NOTIF_SUBJECT else self.email_subject)

            attach_excel = getattr(self, 'attach_excel', False)
            content, excel_files = get_scheduled_report_response(
                self.owner, self.domain, self._id, attach_excel=attach_excel)
            slugs = [r.report_slug for r in self.configs]

            for email in emails:
                body = render_full_report_notification(None, content, email,
                                                       self).content
                send_html_email_async.delay(
                    title,
                    email,
                    body,
                    email_from=settings.DEFAULT_FROM_EMAIL,
                    file_attachments=excel_files)
Ejemplo n.º 44
0
    def test_product_aliases(self):
        with localize('sw'):
            response = six.text_type(SOH_CONFIRM)

        script = """
            5551234 > Hmk iucd 400
            5551234 < {}
        """.format(response)
        self.run_script(script)

        script = """
            5551234 > Hmk Depo 569
            5551234 < {}
        """.format(response)
        self.run_script(script)

        script = """
            5551234 > Hmk IMPL 678
            5551234 < %(soh_confirm)s
        """ % {"soh_confirm": response}
        self.run_script(script)
Ejemplo n.º 45
0
    def test_unicode_characters(self):
        with localize('sw'):
            response = _(SOH_CONFIRM)
        script = """
            5551235 > Hmk Id 400 \u0660Dp 569 Ip 678
            5551235 < %(soh_confirm)s
        """ % {"soh_confirm": response}

        now = datetime.datetime.utcnow()
        self.run_script(script)

        txs = list(StockTransaction.objects.filter(
            case_id=self.loc1.sql_location.supply_point_id,
            report__date__gte=now)
        )
        self.assertEqual(len(txs), 3)

        self.assertSetEqual(
            {(tx.sql_product.code, int(tx.stock_on_hand)) for tx in txs},
            {('id', 400), ('dp', 569), ('ip', 678)}
        )
Ejemplo n.º 46
0
 def test_message_initiator_delivery_facility(self):
     with localize('sw'):
         response1 = unicode(TEST_HANDLER_CONFIRM)
         response2 = unicode(DELIVERY_REMINDER_FACILITY)
     script = """
         5551234 > test delivery d31049
         5551234 < %(test_handler_confirm)s
         32347 < %(response)s
         32348 < %(response)s
         32349 < %(response)s
         """ % {
         "test_handler_confirm": response1,
         "response": response2
     }
     self.run_script(script)
     supply_point_status = SupplyPointStatus.objects.filter(
         location_id=self.facility3.get_id,
         status_type=SupplyPointStatusTypes.DELIVERY_FACILITY
     ).order_by("-status_date")[0]
     self.assertEqual(SupplyPointStatusValues.REMINDER_SENT, supply_point_status.status_value)
     self.assertEqual(SupplyPointStatusTypes.DELIVERY_FACILITY, supply_point_status.status_type)
Ejemplo n.º 47
0
 def test_message_initiator_delivery_district(self):
     with localize('sw'):
         response1 = six.text_type(TEST_HANDLER_CONFIRM)
         response2 = six.text_type(DELIVERY_REMINDER_DISTRICT)
     script = """
         5551234 > test delivery d10101
         5551234 < %(test_handler_confirm)s
         32350 < %(response)s
         32351 < %(response)s
         32352 < %(response)s
         """ % {
         "test_handler_confirm": response1,
         "response": response2
     }
     self.run_script(script)
     supply_point_status = SupplyPointStatus.objects.filter(
         location_id=self.district2.get_id,
         status_type=SupplyPointStatusTypes.DELIVERY_DISTRICT
     ).order_by("-status_date")[0]
     self.assertEqual(SupplyPointStatusValues.REMINDER_SENT, supply_point_status.status_value)
     self.assertEqual(SupplyPointStatusTypes.DELIVERY_DISTRICT, supply_point_status.status_type)
Ejemplo n.º 48
0
    def test_stockout(self):
        with localize('sw'):
            response1 = six.text_type(SOH_CONFIRM)
            response2 = six.text_type(STOCKOUT_CONFIRM)
            response3 = six.text_type(STOCKOUT_HELP)

        supply_point_id = self.loc1.sql_location.supply_point_id

        script = """
            5551234 > Hmk Id 400 Dp 569 Ip 678
            5551234 < %(soh_confirm)s
        """ % {"soh_confirm": response1}
        self.run_script(script)
        self.assertEqual(StockTransaction.objects.filter(case_id=self.facility_sp_id).count(), 3)
        self.assertEqual(StockState.objects.filter(case_id=self.facility_sp_id).count(), 3)

        script = """
            5551234 > hakuna
            5551234 < {}
        """.format(response3)
        self.run_script(script)

        quantities = [400, 569, 678]
        for (idx, stock_transaction) in enumerate(StockTransaction.objects.all().order_by('pk')):
            self.assertEqual(stock_transaction.case_id, supply_point_id)
            self.assertEqual(stock_transaction.stock_on_hand, quantities[idx])
        now = datetime.utcnow()
        script = """
            5551234 > stockout id dp ip
            5551234 < {}
        """.format(response2 % {
            "contact_name": self.user1.full_name,
            "product_names": "id dp ip",
            "facility_name": self.loc1.name
        })
        self.run_script(script)

        for stock_transaction in StockTransaction.objects.filter(report__date__gte=now):
            self.assertEqual(stock_transaction.case_id, supply_point_id)
            self.assertEqual(stock_transaction.stock_on_hand, 0)
Ejemplo n.º 49
0
def pricing_table_json(request, product, locale):
    if product not in [c[0] for c in SoftwareProductType.CHOICES]:
        return HttpResponseBadRequest("Not a valid product")
    if locale not in [l[0] for l in settings.LANGUAGES]:
        return HttpResponseBadRequest("Not a supported language.")
    with localize(locale):
        table = PricingTable.get_table_by_product(product)
        table_json = json.dumps(table, cls=LazyEncoder)

    # This is necessary for responding to requests from Internet Explorer.
    # IE you can FOAD.
    callback = request.GET.get('callback') or request.POST.get('callback')
    if callback is not None:
        table_json = "%s(%s)" % (callback, table_json)

    response = HttpResponse(table_json,
                            content_type='application/json; charset=UTF-8')
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response
Ejemplo n.º 50
0
 def test_stock_on_hand_update(self):
     with localize('sw'):
         response = unicode(SOH_CONFIRM)
     prod_amt_configs = [
         (('Id', 100), ('Dp', 200), ('Ip', 300)),
         (('Id', 0), ('Dp', 100), ('Ip', 200)),
         (('Id', 100), ('Dp', 0), ('Ip', 0)),
         (('Id', 50), ('Dp', 150), ('Ip', 250)),
         (('Id', 0), ('Dp', 0), ('Ip', 0)),
     ]
     pkmax = -1
     for prod_amt_config in prod_amt_configs:
         this_pkmax = pkmax
         product_string = ' '.join(
             ['{p} {v}'.format(p=p, v=v) for p, v in prod_amt_config])
         script = """
             5551234 > Hmk {products}
             5551234 < {soh_confirm}
         """.format(products=product_string, soh_confirm=response)
         self.run_script(script)
         self.assertEqual(
             StockTransaction.objects.filter(
                 case_id=self.facility_sp_id,
                 type__in=['stockonhand', 'stockout'],
                 pk__gt=pkmax).count(), 3)
         self.assertEqual(StockState.objects.count(), 3)
         for code, amt in prod_amt_config:
             ps = StockState.objects.get(sql_product__code__iexact=code,
                                         case_id=self.facility_sp_id)
             self.assertEqual(amt, ps.stock_on_hand)
             pr = StockTransaction.objects.get(
                 case_id=self.facility_sp_id,
                 pk__gt=pkmax,
                 sql_product__code__iexact=code,
                 type__in=['stockonhand', 'stockout'])
             self.assertEqual(amt, pr.stock_on_hand)
             this_pkmax = max(this_pkmax, pr.pk)
         pkmax = max(this_pkmax, pkmax)
Ejemplo n.º 51
0
 def test_message_initiator_losses_adjustments(self):
     with localize('sw'):
         response1 = str(TEST_HANDLER_CONFIRM)
         response2 = str(LOSS_ADJUST_HELP)
     script = """
         5551234 > test la d31049
         5551234 < %(test_handler_confirm)s
         32347 < %(response)s
         32348 < %(response)s
         32349 < %(response)s
         """ % {
         "test_handler_confirm": response1,
         "response": response2
     }
     self.run_script(script)
     supply_point_status = SupplyPointStatus.objects.filter(
         location_id=self.facility3.get_id,
         status_type=SupplyPointStatusTypes.LOSS_ADJUSTMENT_FACILITY
     ).order_by("-status_date")[0]
     self.assertEqual(SupplyPointStatusValues.REMINDER_SENT,
                      supply_point_status.status_value)
     self.assertEqual(SupplyPointStatusTypes.LOSS_ADJUSTMENT_FACILITY,
                      supply_point_status.status_type)
Ejemplo n.º 52
0
    def testTrans(self):
        with localize('sw'):
            response = six.text_type(SOH_CONFIRM)

        script = """
          5551234 > trans yes
          5551234 < %s
        """ % response
        self.run_script(script)

        script = """
          5551234 > trans no
          5551234 < %s
        """ % response
        self.run_script(script)

        self.assertEqual(SupplyPointStatus.objects.count(), 2)
        status1 = SupplyPointStatus.objects.get(status_type=SupplyPointStatusTypes.TRANS_FACILITY,
                                                status_value=SupplyPointStatusValues.NOT_SUBMITTED)
        status2 = SupplyPointStatus.objects.get(status_type=SupplyPointStatusTypes.TRANS_FACILITY,
                                                status_value=SupplyPointStatusValues.SUBMITTED)
        self.assertEqual(self.user1.location_id, status1.location_id)
        self.assertEqual(self.user1.location_id, status2.location_id)
Ejemplo n.º 53
0
    def test_losses_adjustments(self):
        with localize('sw'):
            response1 = str(SOH_CONFIRM)
            response2 = str(LOSS_ADJUST_CONFIRM)

        sohs = {'id': 400, 'dp': 569, 'ip': 678}
        script = """
            5551234 > Hmk Id 400 Dp 569 Ip 678
            5551234 < {0}
        """.format(response1)
        self.run_script(script)

        self.assertEqual(
            StockState.objects.filter(case_id=self.facility_sp_id).count(), 3)
        for ps in StockState.objects.all():
            self.assertEqual(
                self.user_fac1.location.linked_supply_point().get_id,
                ps.case_id)
            self.assertEqual(ps.stock_on_hand, sohs[ps.sql_product.code])

        script = """
            5551234 > um ID -3 dp -5 IP 13
            5551234 < {0}
        """.format(response2)
        self.run_script(script)

        self.assertEqual(
            StockState.objects.filter(case_id=self.facility_sp_id).count(), 3)

        self.assertEqual(
            StockState.objects.get(sql_product__code="id").stock_on_hand, 397)
        self.assertEqual(
            StockState.objects.get(sql_product__code="dp",
                                   case_id=self.facility_sp_id).stock_on_hand,
            564)
        self.assertEqual(
            StockState.objects.get(sql_product__code="ip").stock_on_hand, 691)
Ejemplo n.º 54
0
    def test_register_district_mixed_spacing_for_separator(self):
        with localize('sw'):
            response = unicode(REGISTRATION_CONFIRM_DISTRICT)

        script = """
          5551234 > sajili Test Test: testdistrict
          5551234 < %(registration_confirm)s
        """ % {
            "registration_confirm": response % {
                "sdp_name": self.district3.name,
                "contact_name": "Test Test"
            }
        }
        self.run_script(script)

        script = """
          5551234 > sajili Test Test :testdistrict
          5551234 < %(registration_confirm)s
        """ % {
            "registration_confirm": response % {
                "sdp_name": self.district3.name,
                "contact_name": "Test Test"
            }
        }
        self.run_script(script)

        script = """
          5551234 > sajili Test Test  :   testdistrict
          5551234 < %(registration_confirm)s
        """ % {
            "registration_confirm": response % {
                "sdp_name": self.district3.name,
                "contact_name": "Test Test"
            }
        }
        self.run_script(script)
Ejemplo n.º 55
0
    def test_delivery_district_received(self):
        with localize('sw'):
            response = unicode(DELIVERY_CONFIRM_DISTRICT)
            response2 = unicode(DELIVERY_CONFIRM_CHILDREN)
        script = """
          555 > nimepokea
          555 < {0}
          5551234 < {1}
          5555678 < {1}
        """.format(
            response % dict(contact_name="{0} {1}".format(
                self.user_dis.first_name, self.user_dis.last_name),
                            facility_name=self.dis.name),
            response2 % dict(district_name=self.dis.name))

        self.run_script(script)

        sps = SupplyPointStatus.objects.filter(
            location_id=self.dis.get_id,
            status_type="del_dist").order_by("-status_date")[0]

        self.assertEqual(SupplyPointStatusValues.RECEIVED, sps.status_value)
        self.assertEqual(SupplyPointStatusTypes.DELIVERY_DISTRICT,
                         sps.status_type)
Ejemplo n.º 56
0
    def test_randr_submitted_district(self):
        with localize('sw'):
            response1 = unicode(SUBMITTED_REMINDER_DISTRICT)
            response2 = unicode(SUBMITTED_NOTIFICATION_MSD)
        script = """
          555 > nimetuma
          555 < {0}
          111 < {1}
        """.format(
            response1, response2 % {
                "district_name": self.dis.name,
                "group_a": 0,
                "group_b": 0,
                "group_c": 0
            })
        self.run_script(script)

        sps = SupplyPointStatus.objects.filter(
            location_id=self.dis.get_id,
            status_type="rr_dist").order_by("-status_date")[0]

        self.assertEqual(SupplyPointStatusValues.SUBMITTED, sps.status_value)
        self.assertEqual(SupplyPointStatusTypes.R_AND_R_DISTRICT,
                         sps.status_type)
Ejemplo n.º 57
0
    def _get_and_send_report(self, language, emails):
        from corehq.apps.reports.views import get_scheduled_report_response, render_full_report_notification

        with localize(language):
            title = (_(DEFAULT_REPORT_NOTIF_SUBJECT) if self.email_subject
                     == DEFAULT_REPORT_NOTIF_SUBJECT else self.email_subject)

            attach_excel = getattr(self, 'attach_excel', False)
            try:
                content, excel_files = get_scheduled_report_response(
                    self.owner,
                    self.domain,
                    self._id,
                    attach_excel=attach_excel,
                    send_only_active=True)

                # Will be False if ALL the ReportConfigs in the ReportNotification
                # have a start_date in the future.
                if content is False:
                    return

                for email in emails:
                    body = render_full_report_notification(
                        None, content, email, self).content
                    send_html_email_async(
                        title,
                        email,
                        body,
                        email_from=settings.DEFAULT_FROM_EMAIL,
                        file_attachments=excel_files,
                        smtp_exception_skip_list=LARGE_FILE_SIZE_ERROR_CODES)
            except Exception as er:
                notify_exception(
                    None,
                    message=
                    "Encountered error while generating report or sending email",
                    details={
                        'subject': title,
                        'recipients': str(emails),
                        'error': er,
                    })
                if getattr(er, 'smtp_code',
                           None) in LARGE_FILE_SIZE_ERROR_CODES or type(
                               er) == ESError:
                    # If the email doesn't work because it is too large to fit in the HTML body,
                    # send it as an excel attachment, by creating a mock request with the right data.

                    for report_config in self.configs:
                        mock_request = HttpRequest()
                        mock_request.couch_user = self.owner
                        mock_request.user = self.owner.get_django_user()
                        mock_request.domain = self.domain
                        mock_request.couch_user.current_domain = self.domain
                        mock_request.couch_user.language = self.language
                        mock_request.method = 'GET'
                        mock_request.bypass_two_factor = True

                        mock_query_string_parts = [
                            report_config.query_string, 'filterSet=true'
                        ]
                        if report_config.is_configurable_report:
                            mock_query_string_parts.append(
                                urlencode(report_config.filters, True))
                            mock_query_string_parts.append(
                                urlencode(report_config.get_date_range(),
                                          True))
                        mock_request.GET = QueryDict(
                            '&'.join(mock_query_string_parts))
                        date_range = report_config.get_date_range()
                        start_date = datetime.strptime(date_range['startdate'],
                                                       '%Y-%m-%d')
                        end_date = datetime.strptime(date_range['enddate'],
                                                     '%Y-%m-%d')

                        datespan = DateSpan(start_date, end_date)
                        request_data = vars(mock_request)
                        request_data[
                            'couch_user'] = mock_request.couch_user.userID
                        request_data['datespan'] = datespan

                        full_request = {
                            'request': request_data,
                            'domain': request_data['domain'],
                            'context': {},
                            'request_params': json_request(request_data['GET'])
                        }

                        export_all_rows_task(report_config.report,
                                             full_request, emails, title)
Ejemplo n.º 58
0
def _create_custom_app_strings(app, lang, for_default=False):
    def trans(d):
        return clean_trans(d, langs)

    def maybe_add_index(text):
        if app.build_version and app.build_version >= LooseVersion('2.8'):
            numeric_nav_on = app.profile.get(
                'properties', {}).get('cc-entry-mode') == 'cc-entry-review'
            if app.profile.get('features',
                               {}).get('sense') == 'true' or numeric_nav_on:
                text = "${0} %s" % (text, ) if not (
                    text and text[0].isdigit()) else text
        return text

    langs = [lang] + app.langs
    yield id_strings.homescreen_title(), app.name
    yield id_strings.app_display_name(), app.name

    for id, value in id_strings.REGEX_DEFAULT_VALUES.items():
        yield id, value

    if for_default:
        # include language code names and current language
        for lc in app.langs:
            name = langcodes.get_name(lc) or lc
            if not name:
                continue
            with localize(convert_to_two_letter_code(lc)):
                name = ugettext(name)
            yield lc, name

    yield id_strings.current_language(), lang

    for module in app.get_modules():
        for detail_type, detail, _ in module.get_details():
            for column in detail.get_columns():
                yield id_strings.detail_column_header_locale(
                    module, detail_type, column), trans(column.header)

                if column.format in ('enum', 'enum-image', 'conditional-enum'):
                    for item in column.enum:
                        yield id_strings.detail_column_enum_variable(
                            module, detail_type, column,
                            item.key_as_variable), trans(item.value)
                elif column.format == "graph":
                    for index, item in enumerate(
                            column.graph_configuration.annotations):
                        yield id_strings.graph_annotation(
                            module, detail_type, column,
                            index), trans(item.values)
                    for property, values in six.iteritems(
                            column.graph_configuration.locale_specific_config):
                        yield id_strings.graph_configuration(
                            module, detail_type, column,
                            property), trans(values)
                    for index, item in enumerate(
                            column.graph_configuration.series):
                        for property, values in six.iteritems(
                                item.locale_specific_config):
                            yield id_strings.graph_series_configuration(
                                module, detail_type, column, index,
                                property), trans(values)

            # To list app strings for properties used as sorting properties only
            if detail.sort_elements:
                sort_only, sort_columns = get_sort_and_sort_only_columns(
                    detail, detail.sort_elements)
                for field, sort_element, order in sort_only:
                    if sort_element.has_display_values():
                        column = create_temp_sort_column(sort_element, order)
                        yield id_strings.detail_column_header_locale(module, detail_type, column), \
                            trans(column.header)

            for tab in detail.get_tabs():
                yield id_strings.detail_tab_title_locale(
                    module, detail_type, tab), trans(tab.header)

            if getattr(detail, 'lookup_display_results'):
                yield id_strings.callout_header_locale(module), trans(
                    detail.lookup_field_header)

        yield id_strings.module_locale(module), maybe_add_index(
            trans(module.name))

        icon = module.icon_app_string(lang, for_default=for_default)
        audio = module.audio_app_string(lang, for_default=for_default)
        custom_icon_form, custom_icon_text = module.custom_icon_form_and_text_by_language(
            lang)
        if icon:
            yield id_strings.module_icon_locale(module), icon
        if audio:
            yield id_strings.module_audio_locale(module), audio
        if custom_icon_form and custom_icon_text:
            yield _get_custom_icon_app_locale_and_value(custom_icon_form,
                                                        custom_icon_text,
                                                        module=module)

        if hasattr(module, 'report_configs'):
            for config in module.report_configs:
                yield id_strings.report_command(config.uuid), trans(
                    config.header)
                yield id_strings.report_name(config.uuid), trans(config.header)
                yield id_strings.report_description(config.uuid), trans(
                    config.localized_description)
                for column in config.report(app.domain).report_columns:
                    yield (id_strings.report_column_header(
                        config.uuid,
                        column.column_id), column.get_header(lang))
                for chart_id, graph_config in six.iteritems(
                        config.complete_graph_configs):
                    for index, item in enumerate(graph_config.annotations):
                        yield id_strings.mobile_ucr_annotation(
                            module, config.uuid, index), trans(item.values)
                    for property, values in six.iteritems(
                            graph_config.locale_specific_config):
                        yield id_strings.mobile_ucr_configuration(
                            module, config.uuid, property), trans(values)
                    for index, item in enumerate(graph_config.series):
                        for property, values in six.iteritems(
                                item.locale_specific_config):
                            yield id_strings.mobile_ucr_series_configuration(
                                module, config.uuid, index,
                                property), trans(values)

        if hasattr(module, 'case_list'):
            if module.case_list.show:
                yield id_strings.case_list_locale(module), trans(
                    module.case_list.label) or "Case List"
                icon = module.case_list.icon_app_string(
                    lang, for_default=for_default)
                audio = module.case_list.audio_app_string(
                    lang, for_default=for_default)
                if icon:
                    yield id_strings.case_list_icon_locale(module), icon
                if audio:
                    yield id_strings.case_list_audio_locale(module), audio

        if module_offers_search(module):
            yield id_strings.case_search_locale(module), trans(
                module.search_config.command_label)
            # icon and audio not yet available
            for prop in module.search_config.properties:
                yield id_strings.search_property_locale(
                    module, prop.name), trans(prop.label)

        if hasattr(module, 'referral_list'):
            if module.referral_list.show:
                yield id_strings.referral_list_locale(module), trans(
                    module.referral_list.label)
        for form in module.get_forms():
            form_name = trans(form.name) + ('${0}' if form.show_count else '')
            yield id_strings.form_locale(form), maybe_add_index(form_name)

            icon = form.icon_app_string(lang, for_default=for_default)
            audio = form.audio_app_string(lang, for_default=for_default)
            custom_icon_form, custom_icon_text = form.custom_icon_form_and_text_by_language(
                lang)
            if icon:
                yield id_strings.form_icon_locale(form), icon
            if audio:
                yield id_strings.form_audio_locale(form), audio
            if custom_icon_form and custom_icon_text:
                yield _get_custom_icon_app_locale_and_value(custom_icon_form,
                                                            custom_icon_text,
                                                            form=form)

        if hasattr(module, 'case_list_form') and module.case_list_form.form_id:
            yield (id_strings.case_list_form_locale(module),
                   trans(module.case_list_form.label) or "Create a new Case")
            icon = module.case_list_form.icon_app_string(
                lang, for_default=for_default)
            audio = module.case_list_form.audio_app_string(
                lang, for_default=for_default)
            if icon:
                yield id_strings.case_list_form_icon_locale(module), icon
            if audio:
                yield id_strings.case_list_form_audio_locale(module), audio
Ejemplo n.º 59
0
 def global_msg_domain_lang():
     result = None
     if tdoc and tdoc.default_lang:
         with localize(tdoc.default_lang):
             result = _(default_msg)
     return result if result != default_msg else None
Ejemplo n.º 60
0
 def global_msg_user_lang():
     result = None
     if user_lang:
         with localize(user_lang):
             result = _(default_msg)
     return result if result != default_msg else None