repo_name
stringlengths
7
65
path
stringlengths
5
185
copies
stringlengths
1
4
size
stringlengths
4
6
content
stringlengths
977
990k
license
stringclasses
14 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.4
line_max
int64
31
999
alpha_frac
float64
0.25
0.95
ratio
float64
1.5
7.84
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dimagi/commcare-hq
corehq/apps/smsbillables/management/commands/bootstrap_mach_gateway.py
1
2737
from itertools import islice from django.core.management.base import BaseCommand import openpyxl from corehq.apps.accounting.models import Currency from corehq.apps.sms.models import OUTGOING from corehq.apps.smsbillables.models import ( SmsGatewayFee, SmsGatewayFeeCriteria, ) from corehq.apps.smsbillables.utils import log_smsbillables_info from corehq.messaging.smsbackends.mach.models import SQLMachBackend def bootstrap_mach_gateway(apps): currency_class = apps.get_model('accounting', 'Currency') if apps else Currency sms_gateway_fee_class = apps.get_model('smsbillables', 'SmsGatewayFee') if apps else SmsGatewayFee sms_gateway_fee_criteria_class = apps.get_model('smsbillables', 'SmsGatewayFeeCriteria') \ if apps else SmsGatewayFeeCriteria filename = 'corehq/apps/smsbillables/management/pricing_data/Syniverse_coverage_list_PREMIUM_Sept2019.xlsx' workbook = openpyxl.load_workbook(filename, read_only=True, data_only=True) table = workbook.worksheets[0] data = {} for row in islice(table.rows, 7, None): if row[6].value == 'yes': country_code = int(row[0].value) if not(country_code in data): data[country_code] = [] subscribers = row[10].value.replace('.', '') try: data[country_code].append((row[9].value, int(subscribers))) except ValueError: log_smsbillables_info('Incomplete data for country code %d' % country_code) for country_code in data: total_subscribers = 0 weighted_price = 0 for price, subscribers in data[country_code]: total_subscribers += subscribers weighted_price += price * subscribers if total_subscribers == 0: continue weighted_price = weighted_price / total_subscribers SmsGatewayFee.create_new( SQLMachBackend.get_api_id(), OUTGOING, weighted_price, country_code=country_code, currency=currency_class.objects.get(code="EUR"), fee_class=sms_gateway_fee_class, criteria_class=sms_gateway_fee_criteria_class, ) # Fee for invalid phonenumber SmsGatewayFee.create_new( SQLMachBackend.get_api_id(), OUTGOING, 0.0225, country_code=None, currency=currency_class.objects.get(code="EUR"), fee_class=sms_gateway_fee_class, criteria_class=sms_gateway_fee_criteria_class, ) log_smsbillables_info("Updated MACH/Syniverse gateway fees.") class Command(BaseCommand): help = "bootstrap MACH/Syniverse gateway fees" def handle(self, **options): bootstrap_mach_gateway(None)
bsd-3-clause
3ce0facd0746aafe4fc37b7cacaf09fb
35.013158
111
0.660212
3.688679
false
false
false
false
onepercentclub/bluebottle
bluebottle/organizations/migrations/0003_auto_20170303_1057.py
1
1846
# -*- coding: utf-8 -*- # Generated by Django 1.10.2 on 2017-03-03 09:57 from __future__ import unicode_literals from django.db import migrations def remove_duplicates(apps, schema_editor): Organization = apps.get_model('organizations', 'Organization') OrganizationMember = apps.get_model('organizations', 'OrganizationMember') Project = apps.get_model('projects', 'Project') def merge(master, organizations): """ Merge `organizations` into `organization`. Makes sure that all foreign keys point to `organization`. Deletes all organization models in `organization` after merging. This duplicate `Organization.merge` since django migration do not give access to model methods. """ for organization in organizations: for member in OrganizationMember.objects.filter(organization=organization): member.organization = master member.save() for project in Project.objects.filter(organization=organization): project.organization = master project.save() organization.delete() for organization in Organization.objects.all(): try: Organization.objects.get(pk=organization.pk) except Organization.DoesNotExist: continue matches = Organization.objects.filter( name=organization.name, email=organization.email, website=organization.website, phone_number=organization.phone_number ).exclude(pk=organization.pk) if matches: merge(organization, matches) class Migration(migrations.Migration): dependencies = [ ('organizations', '0002_auto_20160610_1554'), ] operations = [ migrations.RunPython(remove_duplicates) ]
bsd-3-clause
c2d3241b452279a01663780d891856a8
30.827586
88
0.646804
4.896552
false
false
false
false
dimagi/commcare-hq
corehq/apps/smsforms/tasks.py
1
7147
from datetime import timedelta from dimagi.utils.logging import notify_error, notify_exception from corehq import toggles from corehq.apps.celery import task from corehq.apps.formplayer_api.smsforms.api import ( FormplayerInterface, TouchformsError, ) from corehq.apps.sms.api import ( MessageMetadata, send_sms, send_sms_to_verified_number, ) from corehq.apps.sms.models import PhoneNumber from corehq.apps.sms.util import format_message_list from corehq.apps.smsforms.app import ( _responses_to_text, get_events_from_responses, ) from corehq.apps.smsforms.models import ( SQLXFormsSession, XFormsSessionSynchronization, ) from corehq.apps.smsforms.util import critical_section_for_smsforms_sessions from corehq.messaging.scheduling.util import utcnow from corehq.util.celery_utils import no_result_task from corehq.util.metrics import metrics_counter @no_result_task(serializer='pickle', queue='background_queue') def send_first_message(domain, recipient, phone_entry_or_number, session, responses, logged_subevent, workflow): # This try/except section is just here (temporarily) to support future refactors # If any of these notify, they should be replaced with a comment as to why the two are different # so that someone refactoring in the future will know that this or that param is necessary. try: if session.workflow != workflow: # see if we can eliminate the workflow arg notify_error('Exploratory: session.workflow != workflow', details={ 'session.workflow': session.workflow, 'workflow': workflow}) if session.connection_id != recipient.get_id: # see if we can eliminate the recipient arg notify_error('Exploratory: session.connection_id != recipient.get_id', details={ 'session.connection_id': session.connection_id, 'recipient.get_id': recipient.get_id, 'recipient': recipient }) if session.related_subevent != logged_subevent: # see if we can eliminate the logged_subevent arg notify_error('Exploratory: session.related_subevent != logged_subevent', details={ 'session.connection_id': session.connection_id, 'logged_subevent': logged_subevent}) except Exception: # The above running is not mission critical, so if it errors just leave a message in the log # for us to follow up on. # Absence of the message below and messages above ever notifying # will indicate that we can remove these args. notify_exception(None, "Error in section of code that's just supposed help inform future refactors") if toggles.ONE_PHONE_NUMBER_MULTIPLE_CONTACTS.enabled(domain): if not XFormsSessionSynchronization.claim_channel_for_session(session): send_first_message.apply_async( args=(domain, recipient, phone_entry_or_number, session, responses, logged_subevent, workflow), countdown=60 ) return metrics_counter('commcare.smsforms.session_started', 1, tags={'domain': domain, 'workflow': workflow}) if len(responses) > 0: text_responses = _responses_to_text(responses) message = format_message_list(text_responses) events = get_events_from_responses(responses) metadata = MessageMetadata( workflow=workflow, xforms_session_couch_id=session.couch_id, messaging_subevent_id=logged_subevent.pk ) if isinstance(phone_entry_or_number, PhoneNumber): send_sms_to_verified_number( phone_entry_or_number, message, metadata, logged_subevent=logged_subevent, events=events ) else: send_sms( domain, recipient, phone_entry_or_number, message, metadata ) logged_subevent.completed() @no_result_task(serializer='pickle', queue='reminder_queue') def handle_due_survey_action(domain, contact_id, session_id): with critical_section_for_smsforms_sessions(contact_id): session = SQLXFormsSession.by_session_id(session_id) if ( not session or not session.session_is_open or session.current_action_due > utcnow() ): return if toggles.ONE_PHONE_NUMBER_MULTIPLE_CONTACTS.enabled(domain): if not XFormsSessionSynchronization.claim_channel_for_session(session): from .management.commands import handle_survey_actions # Unless we release this lock, handle_survey_actions will be unable to requeue this task # for the default duration of 1h, which we don't want handle_survey_actions.Command.get_enqueue_lock(session_id, session.current_action_due).release() return if session_is_stale(session): # If a session is having some unrecoverable errors that aren't benefitting from # being retried, those errors should show up in sentry log and the fix should # be dealt with. In terms of the current session itself, we just close it out # to allow new sessions to start. session.mark_completed(False) return if session.current_action_is_a_reminder: # Resend the current question in the open survey to the contact p = PhoneNumber.get_phone_number_for_owner(session.connection_id, session.phone_number) if p: subevent = session.related_subevent metadata = MessageMetadata( workflow=session.workflow, xforms_session_couch_id=session._id, messaging_subevent_id=subevent.pk if subevent else None ) resp = FormplayerInterface(session.session_id, domain).current_question() send_sms_to_verified_number( p, resp.event.text_prompt, metadata, logged_subevent=subevent ) session.move_to_next_action() session.save() else: close_session.delay(contact_id, session_id) @task(serializer='pickle', queue='reminder_queue', bind=True, max_retries=3, default_retry_delay=15 * 60) def close_session(self, contact_id, session_id): with critical_section_for_smsforms_sessions(contact_id): session = SQLXFormsSession.by_session_id(session_id) try: session.close(force=False) except TouchformsError as e: try: self.retry(exc=e) except TouchformsError as e: raise e finally: # Eventually the session needs to get closed session.mark_completed(False) return def session_is_stale(session): return utcnow() > (session.start_time + timedelta(minutes=SQLXFormsSession.MAX_SESSION_LENGTH * 2))
bsd-3-clause
d6a9e6ca47fda66b5eb7d9d8a797e9ff
41.541667
112
0.636211
4.206592
false
false
false
false
dimagi/commcare-hq
corehq/apps/dump_reload/tests/test_dump_models.py
1
6855
import itertools from django.apps import apps from corehq.apps.dump_reload.sql.dump import _get_app_list from corehq.apps.dump_reload.util import get_model_label IGNORE_MODELS = { "accounting.BillingAccount", "accounting.BillingContactInfo", "accounting.BillingRecord", "accounting.CreditAdjustment", "accounting.CreditLine", "accounting.Currency", "accounting.CustomerBillingRecord", "accounting.CustomerInvoice", "accounting.CustomerInvoiceCommunicationHistory", "accounting.DefaultProductPlan", "accounting.DomainUserHistory", "accounting.Feature", "accounting.FeatureRate", "accounting.Invoice", "accounting.InvoiceCommunicationHistory", "accounting.LineItem", "accounting.PaymentMethod", "accounting.PaymentRecord", "accounting.SoftwarePlan", "accounting.SoftwarePlanVersion", "accounting.SoftwareProductRate", "accounting.StripePaymentMethod", "accounting.Subscriber", "accounting.Subscription", "accounting.SubscriptionAdjustment", "accounting.WireBillingRecord", "accounting.WireInvoice", # this has a domain, but nothing else in accounting does "accounting.WirePrepaymentBillingRecord", "accounting.WirePrepaymentInvoice", "admin.LogEntry", "analytics.PartnerAnalyticsContact", "analytics.PartnerAnalyticsDataPoint", "analytics.PartnerAnalyticsReport", "api.ApiUser", "app_manager.ExchangeApplication", "auth.Group", "auth.Permission", "blobs.BlobMigrationState", "contenttypes.ContentType", "data_analytics.GIRRow", "data_analytics.MALTRow", "django_celery_results.ChordCounter", "django_celery_results.GroupResult", "django_celery_results.TaskResult", "django_digest.PartialDigest", "django_digest.UserNonce", "django_prbac.Grant", "django_prbac.Role", "django_prbac.UserRole", "dropbox.DropboxUploadHelper", "enterprise.EnterpriseMobileWorkerSettings", # tied to an account, not a domain "enterprise.EnterprisePermissions", "export.DefaultExportSettings", # tied to an account, not a domain "export.EmailExportWhenDoneRequest", # transient model tied to an export task "form_processor.DeprecatedXFormAttachmentSQL", "hqadmin.HistoricalPillowCheckpoint", "hqadmin.HqDeploy", "hqwebapp.HQOauthApplication", "hqwebapp.MaintenanceAlert", "hqwebapp.UserAccessLog", "hqwebapp.UserAgent", "notifications.DismissedUINotify", "notifications.LastSeenNotification", "notifications.Notification", "otp_static.StaticDevice", "otp_static.StaticToken", "otp_totp.TOTPDevice", "phone.SyncLogSQL", # not required and can be a lot of data "pillow_retry.PillowError", "pillowtop.DjangoPillowCheckpoint", "pillowtop.KafkaCheckpoint", "project_limits.DynamicRateDefinition", "project_limits.RateLimitedTwoFactorLog", # 'registry' models only make sense across multiple domains "registry.DataRegistry", "registry.RegistryAuditLog", "registry.RegistryGrant", "registry.RegistryInvitation", "sessions.Session", "sites.Site", "tastypie.ApiAccess", # not tagged by domain "tastypie.ApiKey", # not domain-specific "toggle_ui.ToggleAudit", "two_factor.PhoneDevice", "userreports.ReportComparisonDiff", "userreports.ReportComparisonException", "userreports.ReportComparisonTiming", "users.Permission", "util.BouncedEmail", "util.ComplaintBounceMeta", "util.PermanentBounceMeta", "util.TransientBounceEmail", } # TODO: determine which of these should not be ignored UNKNOWN_MODELS = { "aggregate_ucrs.AggregateTableDefinition", "aggregate_ucrs.PrimaryColumn", "aggregate_ucrs.SecondaryColumn", "aggregate_ucrs.SecondaryTableDefinition", "aggregate_ucrs.TimeAggregationDefinition", "auditcare.AccessAudit", "auditcare.AuditcareMigrationMeta", "auditcare.HttpAccept", "auditcare.NavigationEventAudit", "auditcare.UserAgent", "auditcare.ViewName", "blobs.DeletedBlobMeta", "couchforms.UnfinishedArchiveStub", "couchforms.UnfinishedSubmissionStub", "data_interfaces.CaseDeduplicationActionDefinition", "data_interfaces.CaseDuplicate", "dhis2.SQLDataSetMap", "dhis2.SQLDataValueMap", "export.IncrementalExport", "export.IncrementalExportCheckpoint", "fhir.FHIRImportConfig", "fhir.FHIRImportResourceProperty", "fhir.FHIRImportResourceType", "fhir.ResourceTypeRelationship", "field_audit.AuditEvent", "fixtures.UserLookupTableStatus", "ivr.Call", "oauth2_provider.AccessToken", "oauth2_provider.Application", "oauth2_provider.Grant", "oauth2_provider.IDToken", "oauth2_provider.RefreshToken", "oauth_integrations.GoogleApiToken", "oauth_integrations.LiveGoogleSheetRefreshStatus", "oauth_integrations.LiveGoogleSheetSchedule", "registration.AsyncSignupRequest", "registration.RegistrationRequest", "reminders.EmailUsage", "scheduling.MigratedReminder", "scheduling.SMSCallbackContent", "sms.DailyOutboundSMSLimitReached", "sms.Email", "sms.ExpectedCallback", "sms.MigrationStatus", "sms.MobileBackendInvitation", "sms.PhoneBlacklist", "sms.SQLLastReadMessage", "smsbillables.SmsBillable", "smsbillables.SmsGatewayFee", "smsbillables.SmsGatewayFeeCriteria", "smsbillables.SmsUsageFee", "smsbillables.SmsUsageFeeCriteria", "sso.AuthenticatedEmailDomain", "sso.IdentityProvider", "sso.SsoTestUser", "sso.TrustedIdentityProvider", "sso.UserExemptFromSingleSignOn", "start_enterprise.StartEnterpriseDeliveryReceipt", "telerivet.IncomingRequest", "userreports.AsyncIndicator", "userreports.DataSourceActionLog", "userreports.InvalidUCRData", "userreports.UCRExpression", "users.HQApiKey", "users.UserHistory", "users.UserReportingMetadataStaging", } def test_domain_dump_sql_models(): dump_apps = _get_app_list(set(), set()) covered_models = set(itertools.chain.from_iterable(dump_apps.values())) def _ignore_model(model): if not model._meta.managed: return True if get_model_label(model) in IGNORE_MODELS | UNKNOWN_MODELS: return True if model._meta.proxy: return model._meta.concrete_model in covered_models # Used in Couch to SQL migration tests return model.__name__ == 'DummySQLModel' installed_models = { model for model in apps.get_models() if not _ignore_model(model) } uncovered_models = [ get_model_label(model) for model in installed_models - covered_models ] assert not uncovered_models, ("Not all Django models are covered by domain dump.\n" + '\n'.join(sorted(uncovered_models)))
bsd-3-clause
10cb4871b8de5a8bafc8d4c6ab46cf17
33.104478
88
0.717433
3.737732
false
false
false
false
onepercentclub/bluebottle
bluebottle/members/migrations/0022_auto_20171207_0856.py
1
2480
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2017-12-07 07:56 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('members', '0021_auto_20171114_1035'), ] operations = [ migrations.CreateModel( name='CustomMemberField', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('value', models.CharField(blank=True, max_length=5000, null=True)), ], ), migrations.CreateModel( name='CustomMemberFieldSettings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('description', models.CharField(blank=True, max_length=200, null=True)), ('sequence', models.PositiveIntegerField(db_index=True, default=0, editable=False)), ], options={ 'ordering': ['sequence'], }, ), migrations.CreateModel( name='MemberPlatformSettings', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('update', models.DateTimeField(auto_now=True)), ], options={ 'verbose_name': 'member platform settings', 'verbose_name_plural': 'member platform settings', }, ), migrations.AddField( model_name='custommemberfieldsettings', name='member_settings', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='extra_fields', to='members.MemberPlatformSettings'), ), migrations.AddField( model_name='custommemberfield', name='field', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='members.CustomMemberFieldSettings'), ), migrations.AddField( model_name='custommemberfield', name='member', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='extra', to=settings.AUTH_USER_MODEL), ), ]
bsd-3-clause
0b3ff9fa183c14a31eba548e398264c8
39
158
0.584274
4.444444
false
false
false
false
dimagi/commcare-hq
corehq/form_processor/migrations/0011_add_fields_for_deprecation.py
1
1471
from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('form_processor', '0010_add_auth_and_openrosa_fields'), ] operations = [ migrations.AddField( model_name='xforminstancesql', name='deprecated_form_id', field=models.CharField(max_length=255, null=True), preserve_default=True, ), migrations.AddField( model_name='xforminstancesql', name='edited_on', field=models.DateTimeField(null=True), preserve_default=True, ), migrations.AddField( model_name='xforminstancesql', name='orig_id', field=models.CharField(max_length=255, null=True), preserve_default=True, ), migrations.AlterField( model_name='commcarecaseindexsql', name='case', field=models.ForeignKey(related_query_name='index', related_name='index_set', db_column='case_uuid', to_field='case_uuid', to='form_processor.CommCareCaseSQL', on_delete=models.CASCADE), preserve_default=True, ), migrations.AlterField( model_name='xformattachmentsql', name='xform', field=models.ForeignKey(to='form_processor.XFormInstanceSQL', db_column='form_uuid', to_field='form_uuid', on_delete=models.CASCADE), preserve_default=True, ), ]
bsd-3-clause
d7afcc11d0a220d787396ba3d3807764
34.878049
198
0.590075
4.143662
false
false
false
false
dimagi/commcare-hq
corehq/apps/accounting/forms.py
1
108963
import datetime import json from decimal import Decimal from django import forms from django.conf import settings from django.contrib import messages from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.validators import MinLengthValidator, validate_slug from django.db import transaction from django.forms.utils import ErrorList from django.template.loader import render_to_string from django.urls import reverse from django.utils.dates import MONTHS from django.utils.safestring import mark_safe from django.utils.html import format_html, format_html_join from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy, gettext_noop from crispy_forms import layout as crispy from crispy_forms.bootstrap import InlineField, StrictButton from crispy_forms.helper import FormHelper from dateutil.relativedelta import relativedelta from django_countries.data import COUNTRIES from django_prbac.models import Grant, Role, UserRole from memoized import memoized from corehq import privileges from corehq.apps.accounting.async_handlers import ( FeatureRateAsyncHandler, SoftwareProductRateAsyncHandler, ) from corehq.apps.accounting.exceptions import ( CreateAccountingAdminError, InvoiceError, ) from corehq.apps.accounting.invoicing import ( CustomerAccountInvoiceFactory, DomainInvoiceFactory, ) from corehq.apps.accounting.models import ( BillingAccount, BillingContactInfo, BillingRecord, CreditAdjustment, CreditAdjustmentReason, CreditLine, Currency, CustomerBillingRecord, CustomerInvoice, DefaultProductPlan, EntryPoint, Feature, FeatureRate, FeatureType, FundingSource, Invoice, InvoicingPlan, LastPayment, PreOrPostPay, ProBonoStatus, SoftwarePlan, SoftwarePlanEdition, SoftwarePlanVersion, SoftwarePlanVisibility, SoftwareProductRate, Subscription, SubscriptionType, WireBillingRecord, DomainUserHistory, ) from corehq.apps.accounting.tasks import send_subscription_reminder_emails from corehq.apps.accounting.utils import ( get_account_name_from_default_name, get_money_str, has_subscription_already_ended, make_anchor_tag, ) from corehq.apps.accounting.utils.software_plans import ( upgrade_subscriptions_to_latest_plan_version, ) from corehq.apps.domain.models import Domain from corehq.apps.hqwebapp import crispy as hqcrispy from corehq.apps.hqwebapp.tasks import send_html_email_async from corehq.apps.users.models import WebUser from corehq.util.dates import get_first_last_days class BillingAccountBasicForm(forms.Form): name = forms.CharField(label="Name") salesforce_account_id = forms.CharField(label=gettext_lazy("Salesforce Account ID"), max_length=80, required=False) currency = forms.ChoiceField(label="Currency") email_list = forms.CharField( label=gettext_lazy('Client Contact Emails'), widget=forms.SelectMultiple(choices=[]), ) is_active = forms.BooleanField( label=gettext_lazy("Account is Active"), required=False, initial=True, ) is_customer_billing_account = forms.BooleanField( label=gettext_lazy("Is Customer Billing Account"), required=False, initial=False ) is_sms_billable_report_visible = forms.BooleanField( label="", required=False, initial=False ) enterprise_admin_emails = forms.CharField( label="Enterprise Admin Emails", required=False, widget=forms.SelectMultiple(choices=[]), ) enterprise_restricted_signup_domains = forms.CharField( label="Enterprise Domains for Restricting Signups", required=False, help_text='ex: dimagi.com, commcarehq.org', ) invoicing_plan = forms.ChoiceField( label="Invoicing Plan", required=False ) active_accounts = forms.IntegerField( label=gettext_lazy("Transfer Subscriptions To"), help_text=gettext_lazy( "Transfer any existing subscriptions to the " "Billing Account specified here." ), required=False, ) dimagi_contact = forms.EmailField( label=gettext_lazy("Dimagi Contact Email"), max_length=BillingAccount._meta.get_field('dimagi_contact').max_length, required=False, ) entry_point = forms.ChoiceField( label=gettext_lazy("Entry Point"), choices=EntryPoint.CHOICES, ) last_payment_method = forms.ChoiceField( label=gettext_lazy("Last Payment Method"), choices=LastPayment.CHOICES ) pre_or_post_pay = forms.ChoiceField( label=gettext_lazy("Prepay or Postpay"), choices=PreOrPostPay.CHOICES ) account_basic = forms.CharField(widget=forms.HiddenInput, required=False) block_hubspot_data_for_all_users = forms.BooleanField( label="Enable Block Hubspot Data", required=False, initial=False, help_text="Users in any projects connected to this account will not " "have data sent to Hubspot", ) def __init__(self, account, *args, **kwargs): self.account = account if account is not None: contact_info, _ = BillingContactInfo.objects.get_or_create(account=account) kwargs['initial'] = { 'name': account.name, 'salesforce_account_id': account.salesforce_account_id, 'currency': account.currency.code, 'email_list': contact_info.email_list, 'is_active': account.is_active, 'is_customer_billing_account': account.is_customer_billing_account, 'is_sms_billable_report_visible': account.is_sms_billable_report_visible, 'enterprise_admin_emails': account.enterprise_admin_emails, 'enterprise_restricted_signup_domains': ','.join(account.enterprise_restricted_signup_domains), 'invoicing_plan': account.invoicing_plan, 'dimagi_contact': account.dimagi_contact, 'entry_point': account.entry_point, 'last_payment_method': account.last_payment_method, 'pre_or_post_pay': account.pre_or_post_pay, 'block_hubspot_data_for_all_users': account.block_hubspot_data_for_all_users, } else: kwargs['initial'] = { 'currency': Currency.get_default().code, 'entry_point': EntryPoint.CONTRACTED, 'last_payment_method': LastPayment.NONE, 'pre_or_post_pay': PreOrPostPay.POSTPAY, 'invoicing_plan': InvoicingPlan.MONTHLY } super(BillingAccountBasicForm, self).__init__(*args, **kwargs) self.fields['currency'].choices =\ [(cur.code, cur.code) for cur in Currency.objects.order_by('code')] self.fields['invoicing_plan'].choices = InvoicingPlan.CHOICES self.helper = FormHelper() self.helper.form_id = "account-form" self.helper.form_class = "form-horizontal" self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' additional_fields = [] if account is not None: additional_fields.append(hqcrispy.B3MultiField( "Active Status", hqcrispy.MultiInlineField( 'is_active', data_bind="checked: is_active", ), )) additional_fields.append(hqcrispy.B3MultiField( "Customer Billing Account", hqcrispy.MultiInlineField( 'is_customer_billing_account', data_bind="checked: is_customer_billing_account", ), )) additional_fields.append( crispy.Div( 'invoicing_plan', crispy.Field( 'enterprise_admin_emails', css_class='input-xxlarge accounting-email-select2', data_initial=json.dumps(self.initial.get('enterprise_admin_emails')), ), data_bind='visible: is_customer_billing_account', data_initial=json.dumps(self.initial.get('enterprise_admin_emails')), ) ) additional_fields.append( hqcrispy.B3MultiField( "SMS Billable Report Visible", hqcrispy.MultiInlineField( 'is_sms_billable_report_visible', data_bind="checked: is_sms_billable_report_visible", ), data_bind='visible: is_customer_billing_account', ), ) additional_fields.append( crispy.Div( crispy.Field( 'enterprise_restricted_signup_domains', css_class='input-xxlarge', ), data_bind='visible: is_customer_billing_account' ), ) if account.subscription_set.count() > 0: additional_fields.append(crispy.Div( crispy.Field( 'active_accounts', css_class="input-xxlarge accounting-async-select2", placeholder="Select Active Account", ), data_bind="visible: showActiveAccounts" )) additional_fields.extend([ hqcrispy.B3MultiField( "Block Hubspot Data for All Users", hqcrispy.MultiInlineField( 'block_hubspot_data_for_all_users', ), ), ]) self.helper.layout = crispy.Layout( crispy.Fieldset( 'Basic Information', 'name', crispy.Field('email_list', css_class='input-xxlarge accounting-email-select2', data_initial=json.dumps(self.initial.get('email_list'))), crispy.Div( crispy.Div( css_class='col-sm-3 col-md-2' ), crispy.Div( crispy.HTML(", ".join(self.initial.get('email_list'))), css_class='col-sm-9 col-md-8 col-lg-6' ), css_id='emails-text', css_class='collapse form-group' ) if self.initial.get('email_list') else crispy.Div(), crispy.Div( crispy.Div( css_class='col-sm-3 col-md-2' ), crispy.Div( StrictButton( "Show contact emails as text", type="button", css_class='btn btn-default', css_id='show_emails' ), crispy.HTML('<p class="help-block">Useful when you want to copy contact emails</p>'), css_class='col-sm-9 col-md-8 col-lg-6' ), css_class='form-group' ) if self.initial.get('email_list') else crispy.Div(), 'dimagi_contact', 'salesforce_account_id', 'currency', 'entry_point', 'last_payment_method', 'pre_or_post_pay', 'account_basic', crispy.Div(*additional_fields), ), hqcrispy.FormActions( crispy.Submit( 'account_basic', 'Update Basic Information' if account is not None else 'Add New Account', css_class='disable-on-submit', ) ) ) def clean_name(self): name = self.cleaned_data['name'] conflicting_named_accounts = BillingAccount.objects.filter(name=name) if self.account: conflicting_named_accounts = conflicting_named_accounts.exclude(name=self.account.name) if conflicting_named_accounts.exists(): raise ValidationError(_("Name '%s' is already taken.") % name) return name def clean_email_list(self): return self.data.getlist('email_list') def clean_enterprise_admin_emails(self): return self.data.getlist('enterprise_admin_emails') def clean_enterprise_restricted_signup_domains(self): if self.cleaned_data['enterprise_restricted_signup_domains']: # Check that no other account has claimed these domains, or we won't know which message to display errors = [] accounts = BillingAccount.get_enterprise_restricted_signup_accounts() domains = [e.strip() for e in self.cleaned_data['enterprise_restricted_signup_domains'].split(r',')] for domain in domains: for account in accounts: if domain in account.enterprise_restricted_signup_domains and account.id != self.account.id: errors.append("{} is restricted by {}".format(domain, account.name)) if errors: raise ValidationError("The following domains are already restricted by another account: " + ", ".join(errors)) return domains else: # Do not return a list with an empty string return [] def clean_active_accounts(self): transfer_subs = self.cleaned_data['active_accounts'] if ( not self.cleaned_data['is_active'] and self.account is not None and self.account.subscription_set.count() > 0 and not transfer_subs ): raise ValidationError( _("This account has subscriptions associated with it. " "Please specify a transfer account before deactivating.") ) if self.account is not None and transfer_subs == self.account.id: raise ValidationError( _("The transfer account can't be the same one you're trying " "to deactivate.") ) return transfer_subs @transaction.atomic def create_account(self): name = self.cleaned_data['name'] salesforce_account_id = self.cleaned_data['salesforce_account_id'] currency, _ = Currency.objects.get_or_create( code=self.cleaned_data['currency'] ) account = BillingAccount( name=get_account_name_from_default_name(name), salesforce_account_id=salesforce_account_id, currency=currency, entry_point=self.cleaned_data['entry_point'], last_payment_method=self.cleaned_data['last_payment_method'], pre_or_post_pay=self.cleaned_data['pre_or_post_pay'] ) account.save() contact_info, _ = BillingContactInfo.objects.get_or_create( account=account, ) contact_info.email_list = self.cleaned_data['email_list'] contact_info.save() return account @transaction.atomic def update_basic_info(self, account): account.name = self.cleaned_data['name'] account.is_active = self.cleaned_data['is_active'] account.is_customer_billing_account = self.cleaned_data['is_customer_billing_account'] account.is_sms_billable_report_visible = self.cleaned_data['is_sms_billable_report_visible'] account.enterprise_admin_emails = self.cleaned_data['enterprise_admin_emails'] account.enterprise_restricted_signup_domains = self.cleaned_data['enterprise_restricted_signup_domains'] account.invoicing_plan = self.cleaned_data['invoicing_plan'] account.block_hubspot_data_for_all_users = self.cleaned_data['block_hubspot_data_for_all_users'] transfer_id = self.cleaned_data['active_accounts'] if transfer_id: transfer_account = BillingAccount.objects.get(id=transfer_id) for sub in account.subscription_set.all(): sub.account = transfer_account sub.save() account.salesforce_account_id = \ self.cleaned_data['salesforce_account_id'] account.currency, _ = Currency.objects.get_or_create( code=self.cleaned_data['currency'], ) account.dimagi_contact = self.cleaned_data['dimagi_contact'] account.entry_point = self.cleaned_data['entry_point'] account.last_payment_method = self.cleaned_data['last_payment_method'] account.pre_or_post_pay = self.cleaned_data['pre_or_post_pay'] account.save() contact_info, _ = BillingContactInfo.objects.get_or_create( account=account, ) contact_info.email_list = self.cleaned_data['email_list'] contact_info.save() class BillingAccountContactForm(forms.ModelForm): account_contact = forms.CharField(widget=forms.HiddenInput, required=False) class Meta(object): model = BillingContactInfo fields = [ 'first_name', 'last_name', 'company_name', 'phone_number', 'first_line', 'second_line', 'city', 'state_province_region', 'postal_code', 'country', ] widgets = {'country': forms.Select(choices=[])} def __init__(self, account, *args, **kwargs): contact_info, _ = BillingContactInfo.objects.get_or_create( account=account, ) super(BillingAccountContactForm, self).__init__(instance=contact_info, *args, **kwargs) self.helper = FormHelper() self.helper.form_class = "form-horizontal" self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' country_code = args[0].get('country') if len(args) > 0 else account.billingcontactinfo.country self.helper.layout = crispy.Layout( crispy.Fieldset( 'Contact Information', 'first_name', 'last_name', 'company_name', 'phone_number', 'first_line', 'second_line', 'city', 'state_province_region', 'postal_code', crispy.Field( 'country', css_class="input-xlarge accounting-country-select2", data_country_code=country_code or '', data_country_name=COUNTRIES.get(country_code, ''), ), ), hqcrispy.FormActions( crispy.ButtonHolder( crispy.Submit( 'account_contact', 'Update Contact Information' ) ) ), ) class SubscriptionForm(forms.Form): account = forms.IntegerField( label=gettext_lazy("Billing Account"), widget=forms.Select(choices=[]), ) start_date = forms.DateField( label=gettext_lazy("Start Date"), widget=forms.DateInput() ) end_date = forms.DateField( label=gettext_lazy("End Date"), widget=forms.DateInput(), required=False ) plan_edition = forms.ChoiceField( label=gettext_lazy("Edition"), initial=SoftwarePlanEdition.ENTERPRISE, choices=SoftwarePlanEdition.CHOICES, ) plan_version = forms.IntegerField( label=gettext_lazy("Software Plan"), widget=forms.Select(choices=[]), ) domain = forms.CharField( label=gettext_lazy("Project Space"), widget=forms.Select(choices=[]), ) salesforce_contract_id = forms.CharField( label=gettext_lazy("Salesforce Deployment ID"), max_length=80, required=False ) do_not_invoice = forms.BooleanField( label=gettext_lazy("Do Not Invoice"), required=False ) no_invoice_reason = forms.CharField( label=gettext_lazy("Justify why \"Do Not Invoice\""), max_length=256, required=False ) do_not_email_invoice = forms.BooleanField(label="Do Not Email Invoices", required=False) do_not_email_reminder = forms.BooleanField(label="Do Not Email Subscription Reminders", required=False) auto_generate_credits = forms.BooleanField( label=gettext_lazy("Auto-generate Plan Credits"), required=False ) skip_invoicing_if_no_feature_charges = forms.BooleanField( label=gettext_lazy("Skip invoicing if no feature charges"), required=False ) active_accounts = forms.IntegerField( label=gettext_lazy("Transfer Subscription To"), required=False, widget=forms.Select(choices=[]), ) service_type = forms.ChoiceField( label=gettext_lazy("Type"), choices=SubscriptionType.CHOICES, initial=SubscriptionType.IMPLEMENTATION, ) pro_bono_status = forms.ChoiceField( label=gettext_lazy("Discounted"), choices=ProBonoStatus.CHOICES, initial=ProBonoStatus.NO, ) funding_source = forms.ChoiceField( label=gettext_lazy("Funding Source"), choices=FundingSource.CHOICES, initial=FundingSource.CLIENT, ) skip_auto_downgrade = forms.BooleanField( label=gettext_lazy("Exclude from automated downgrade process"), required=False ) skip_auto_downgrade_reason = forms.CharField( label=gettext_lazy("Justify why \"Skip Auto Downgrade\""), max_length=256, required=False, ) set_subscription = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, subscription, account_id, web_user, *args, **kwargs): # account_id is not referenced if subscription is not None super(SubscriptionForm, self).__init__(*args, **kwargs) self.subscription = subscription is_existing = subscription is not None self.web_user = web_user today = datetime.date.today() start_date_field = crispy.Field('start_date', css_class="date-picker") end_date_field = crispy.Field('end_date', css_class="date-picker") if is_existing: # circular import from corehq.apps.accounting.views import ( SoftwarePlanVersionView, ManageBillingAccountView ) from corehq.apps.domain.views.settings import DefaultProjectSettingsView self.fields['account'].initial = subscription.account.id account_field = hqcrispy.B3TextField( 'account', format_html('<a href="{}">{}</a>', reverse(ManageBillingAccountView.urlname, args=[subscription.account.id]), subscription.account.name) ) self.fields['plan_version'].initial = subscription.plan_version.id plan_version_field = hqcrispy.B3TextField( 'plan_version', format_html('<a href="{}">{}</a>', reverse(SoftwarePlanVersionView.urlname, args=[subscription.plan_version.plan.id, subscription.plan_version_id]), subscription.plan_version) ) self.fields['plan_edition'].initial = subscription.plan_version.plan.edition plan_edition_field = hqcrispy.B3TextField( 'plan_edition', self.fields['plan_edition'].initial ) self.fields['domain'].choices = [ (subscription.subscriber.domain, subscription.subscriber.domain) ] self.fields['domain'].initial = subscription.subscriber.domain domain_field = hqcrispy.B3TextField( 'domain', format_html('<a href="{}">{}</a>', reverse(DefaultProjectSettingsView.urlname, args=[subscription.subscriber.domain]), subscription.subscriber.domain) ) self.fields['start_date'].initial = subscription.date_start.isoformat() self.fields['end_date'].initial = ( subscription.date_end.isoformat() if subscription.date_end is not None else subscription.date_end ) self.fields['domain'].initial = subscription.subscriber.domain self.fields['salesforce_contract_id'].initial = subscription.salesforce_contract_id self.fields['do_not_invoice'].initial = subscription.do_not_invoice self.fields['no_invoice_reason'].initial = subscription.no_invoice_reason self.fields['do_not_email_invoice'].initial = subscription.do_not_email_invoice self.fields['do_not_email_reminder'].initial = subscription.do_not_email_reminder self.fields['auto_generate_credits'].initial = subscription.auto_generate_credits self.fields['skip_invoicing_if_no_feature_charges'].initial = \ subscription.skip_invoicing_if_no_feature_charges self.fields['service_type'].initial = subscription.service_type self.fields['pro_bono_status'].initial = subscription.pro_bono_status self.fields['funding_source'].initial = subscription.funding_source self.fields['skip_auto_downgrade'].initial = subscription.skip_auto_downgrade self.fields['skip_auto_downgrade_reason'].initial = subscription.skip_auto_downgrade_reason if ( subscription.date_start is not None and subscription.date_start <= today ): self.fields['start_date'].help_text = '(already started)' if has_subscription_already_ended(subscription): self.fields['end_date'].help_text = '(already ended)' self.fields['plan_version'].required = False self.fields['domain'].required = False else: account_field = crispy.Field( 'account', css_class="input-xxlarge", placeholder="Search for Billing Account" ) if account_id is not None: self.fields['account'].initial = account_id domain_field = crispy.Field( 'domain', css_class="input-xxlarge", placeholder="Search for Project Space" ) plan_edition_field = crispy.Field('plan_edition') plan_version_field = crispy.Field( 'plan_version', css_class="input-xxlarge", placeholder="Search for Software Plan" ) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_text_inline = True transfer_fields = [] if is_existing: transfer_fields.extend([ crispy.Field( 'active_accounts', css_class='input-xxlarge accounting-async-select2', placeholder="Select Active Account", style="width: 100%;", ), ]) self.helper.layout = crispy.Layout( crispy.Fieldset( '%s Subscription' % ('Edit' if is_existing else 'New'), account_field, crispy.Div(*transfer_fields), start_date_field, end_date_field, plan_edition_field, plan_version_field, domain_field, 'salesforce_contract_id', hqcrispy.B3MultiField( "Invoice Options", crispy.Field('do_not_invoice', data_bind="checked: noInvoice"), 'skip_invoicing_if_no_feature_charges', ), crispy.Div( crispy.Field( 'no_invoice_reason', data_bind="attr: {required: noInvoice}"), data_bind="visible: noInvoice"), hqcrispy.B3MultiField("Email Options", 'do_not_email_invoice', 'do_not_email_reminder'), hqcrispy.B3MultiField("Credit Options", 'auto_generate_credits'), 'service_type', 'pro_bono_status', 'funding_source', hqcrispy.B3MultiField( "Skip Auto Downgrade", crispy.Field('skip_auto_downgrade', data_bind="checked: skipAutoDowngrade") ), crispy.Div( crispy.Field( 'skip_auto_downgrade_reason', data_bind="attr: {required: skipAutoDowngrade}" ), data_bind="visible: skipAutoDowngrade", ), 'set_subscription' ), hqcrispy.FormActions( crispy.ButtonHolder( crispy.Submit( 'set_subscription', '%s Subscription' % ('Update' if is_existing else 'Create'), css_class='disable-on-submit', ) ) ) ) @transaction.atomic def create_subscription(self): account = BillingAccount.objects.get(id=self.cleaned_data['account']) domain = self.cleaned_data['domain'] plan_version = SoftwarePlanVersion.objects.get(id=self.cleaned_data['plan_version']) sub = Subscription.new_domain_subscription( account, domain, plan_version, web_user=self.web_user, internal_change=True, **self.shared_keywords ) return sub @transaction.atomic def update_subscription(self): self.subscription.update_subscription( web_user=self.web_user, **self.shared_keywords ) transfer_account = self.cleaned_data.get('active_accounts') if transfer_account: acct = BillingAccount.objects.get(id=transfer_account) CreditLine.objects.filter( account=self.subscription.account, # TODO - add this constraint to postgres subscription=self.subscription, ).update(account=acct) self.subscription.account = acct self.subscription.save() @property def shared_keywords(self): return dict( date_start=self.cleaned_data['start_date'], date_end=self.cleaned_data['end_date'], do_not_invoice=self.cleaned_data['do_not_invoice'], no_invoice_reason=self.cleaned_data['no_invoice_reason'], do_not_email_invoice=self.cleaned_data['do_not_email_invoice'], do_not_email_reminder=self.cleaned_data['do_not_email_reminder'], auto_generate_credits=self.cleaned_data['auto_generate_credits'], skip_invoicing_if_no_feature_charges=self.cleaned_data['skip_invoicing_if_no_feature_charges'], salesforce_contract_id=self.cleaned_data['salesforce_contract_id'], service_type=self.cleaned_data['service_type'], pro_bono_status=self.cleaned_data['pro_bono_status'], funding_source=self.cleaned_data['funding_source'], skip_auto_downgrade=self.cleaned_data['skip_auto_downgrade'], skip_auto_downgrade_reason=self.cleaned_data['skip_auto_downgrade_reason'], ) def clean_active_accounts(self): transfer_account = self.cleaned_data.get('active_accounts') if transfer_account and transfer_account == self.subscription.account.id: raise ValidationError(_("Please select an account other than the " "current account to transfer to.")) if transfer_account: acct = BillingAccount.objects.get(id=transfer_account) if acct.is_customer_billing_account != self.subscription.plan_version.plan.is_customer_software_plan: if acct.is_customer_billing_account: raise ValidationError("Please select a regular Billing Account to transfer to.") else: raise ValidationError("Please select a Customer Billing Account to transfer to.") return transfer_account def clean_domain(self): domain = self.cleaned_data['domain'] if self.fields['domain'].required: domain_obj = Domain.get_by_name(domain) if domain_obj is None: raise forms.ValidationError(_("A valid project space is required.")) return domain def clean(self): if not self.cleaned_data.get('active_accounts') and not self.cleaned_data.get('account'): raise ValidationError(_("Account must be specified")) account_id = self.cleaned_data.get('active_accounts') or self.cleaned_data.get('account') if account_id: account = BillingAccount.objects.get(id=account_id) if ( not self.cleaned_data['do_not_invoice'] and ( not BillingContactInfo.objects.filter(account=account).exists() or not account.billingcontactinfo.email_list ) ): from corehq.apps.accounting.views import ManageBillingAccountView raise forms.ValidationError(format_html(_( "Please update 'Client Contact Emails' " '<strong><a href={link} target="_blank">here</a></strong> ' "before using Billing Account <strong>{account}</strong>." ), link=reverse(ManageBillingAccountView.urlname, args=[account.id]), account=account.name, )) start_date = self.cleaned_data.get('start_date') if not start_date: if self.subscription: start_date = self.subscription.date_start else: raise ValidationError(_("You must specify a start date")) end_date = self.cleaned_data.get('end_date') if end_date: if start_date > end_date: raise ValidationError(_("End date must be after start date.")) return self.cleaned_data class ChangeSubscriptionForm(forms.Form): subscription_change_note = forms.CharField( label=gettext_lazy("Note"), required=True, widget=forms.Textarea(attrs={"class": "vertical-resize"}), ) new_plan_edition = forms.ChoiceField( label=gettext_lazy("Edition"), initial=SoftwarePlanEdition.ENTERPRISE, choices=SoftwarePlanEdition.CHOICES, ) new_plan_version = forms.CharField( label=gettext_lazy("New Software Plan"), widget=forms.Select(choices=[]), ) new_date_end = forms.DateField( label=gettext_lazy("End Date"), widget=forms.DateInput(), required=False ) service_type = forms.ChoiceField( label=gettext_lazy("Type"), choices=SubscriptionType.CHOICES, initial=SubscriptionType.IMPLEMENTATION, ) pro_bono_status = forms.ChoiceField( label=gettext_lazy("Discounted"), choices=ProBonoStatus.CHOICES, initial=ProBonoStatus.NO, ) funding_source = forms.ChoiceField( label=gettext_lazy("Funding Source"), choices=FundingSource.CHOICES, initial=FundingSource.CLIENT, ) def __init__(self, subscription, web_user, *args, **kwargs): self.subscription = subscription self.web_user = web_user super(ChangeSubscriptionForm, self).__init__(*args, **kwargs) if self.subscription.date_end is not None: self.fields['new_date_end'].initial = subscription.date_end self.helper = FormHelper() self.helper.form_class = "form-horizontal" self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( "Change Subscription", crispy.Field('new_date_end', css_class="date-picker"), 'new_plan_edition', crispy.Field( 'new_plan_version', css_class="input-xxlarge", placeholder="Search for Software Plan", style="width: 100%;" ), 'service_type', 'pro_bono_status', 'funding_source', 'subscription_change_note', ), hqcrispy.FormActions( StrictButton( "Change Subscription", type="submit", css_class="btn-primary disable-on-submit", ), ), ) @transaction.atomic def change_subscription(self): new_plan_version = SoftwarePlanVersion.objects.get(id=self.cleaned_data['new_plan_version']) return self.subscription.change_plan( new_plan_version, date_end=self.cleaned_data['new_date_end'], web_user=self.web_user, service_type=self.cleaned_data['service_type'], pro_bono_status=self.cleaned_data['pro_bono_status'], funding_source=self.cleaned_data['funding_source'], note=self.cleaned_data['subscription_change_note'], internal_change=True, ) class BulkUpgradeToLatestVersionForm(forms.Form): upgrade_note = forms.CharField( label="Note", required=True, widget=forms.Textarea(attrs={"class": "vertical-resize"}), ) def __init__(self, old_plan_version, web_user, *args, **kwargs): self.old_plan_version = old_plan_version self.web_user = web_user super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = "form-horizontal" self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( "Upgrade All Subscriptions To Latest Version", 'upgrade_note', ), hqcrispy.FormActions( StrictButton( "Upgrade All", type="submit", css_class="btn-primary disable-on-submit", ), ), ) @transaction.atomic def upgrade_subscriptions(self): upgrade_subscriptions_to_latest_plan_version( self.old_plan_version, self.web_user, self.cleaned_data['upgrade_note'], ) class CreditForm(forms.Form): amount = forms.DecimalField(label="Amount (USD)") note = forms.CharField(required=True) rate_type = forms.ChoiceField( label=gettext_lazy("Rate Type"), choices=( ('', 'Any'), ('Product', 'Product'), ('Feature', 'Feature'), ), required=False, ) feature_type = forms.ChoiceField(required=False, label=gettext_lazy("Feature Type")) adjust = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, account, subscription, *args, **kwargs): self.account = account self.subscription = subscription super(CreditForm, self).__init__(*args, **kwargs) self.fields['feature_type'].choices = FeatureType.CHOICES self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Add Credit', 'amount', 'note', crispy.Field('rate_type', data_bind="value: rateType"), crispy.Div('feature_type', data_bind="visible: showFeature"), 'adjust' ), hqcrispy.FormActions( crispy.ButtonHolder( crispy.Submit( 'adjust_credit', 'Update Credit', css_class='disable-on-submit', ), ) ) ) def clean_amount(self): amount = self.cleaned_data['amount'] field_metadata = CreditAdjustment._meta.get_field('amount') if amount >= 10 ** (field_metadata.max_digits - field_metadata.decimal_places): raise ValidationError(mark_safe(_( # nosec: no user input 'Amount over maximum size. If you need support for ' 'quantities this large, please <a data-toggle="modal" ' 'data-target="#modalReportIssue" href="#modalReportIssue">' 'Report an Issue</a>.' ))) return amount @transaction.atomic def adjust_credit(self, web_user=None): amount = self.cleaned_data['amount'] note = self.cleaned_data['note'] is_product = self.cleaned_data['rate_type'] == 'Product' feature_type = (self.cleaned_data['feature_type'] if self.cleaned_data['rate_type'] == 'Feature' else None) CreditLine.add_credit( amount, account=self.account, subscription=self.subscription, feature_type=feature_type, is_product=is_product, note=note, web_user=web_user, permit_inactive=True, ) return True class RemoveAutopayForm(forms.Form): remove_autopay = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, account, *args, **kwargs): super(RemoveAutopayForm, self).__init__(*args, **kwargs) self.account = account self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Remove Autopay User', 'remove_autopay' ), hqcrispy.FormActions( StrictButton( 'Remove Autopay User', css_class='btn-danger disable-on-submit', name='cancel_subscription', type='submit', ) ), ) def remove_autopay_user_from_account(self): self.account.auto_pay_user = None self.account.save() class CancelForm(forms.Form): note = forms.CharField( widget=forms.TextInput, ) cancel_subscription = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, subscription, *args, **kwargs): super(CancelForm, self).__init__(*args, **kwargs) can_cancel = has_subscription_already_ended(subscription) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Cancel Subscription', crispy.Field('note', **({'readonly': True} if can_cancel else {})), 'cancel_subscription' ), hqcrispy.FormActions( StrictButton( 'Cancel Subscription', css_class='btn-danger disable-on-submit', name='cancel_subscription', type='submit', **({'disabled': True} if can_cancel else {}) ) ), ) class SuppressSubscriptionForm(forms.Form): submit_kwarg = 'suppress_subscription' suppress_subscription = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, subscription, *args, **kwargs): self.subscription = subscription super(SuppressSubscriptionForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form-horizontal' fields = [ crispy.Div( crispy.HTML('Warning: this can only be undone by a developer.'), css_class='alert alert-danger', ), 'suppress_subscription' ] if self.subscription.is_active: fields.append(crispy.Div( crispy.HTML('An active subscription cannot be suppressed.'), css_class='alert alert-warning', )) self.helper.layout = crispy.Layout( crispy.Fieldset( 'Suppress subscription from subscription report, invoice generation, and from being activated', *fields ), hqcrispy.FormActions( StrictButton( 'Suppress Subscription', css_class='btn-danger disable-on-submit', name=self.submit_kwarg, type='submit', **({'disabled': True} if self.subscription.is_active else {}) ), ), ) def clean(self): from corehq.apps.accounting.views import InvoiceSummaryView invoices = self.subscription.invoice_set.all() if invoices: raise ValidationError(format_html( "Cannot suppress subscription. Suppress these invoices first: {}", format_html_join( ', ', '<a href="{}">{}</a>', [( reverse(InvoiceSummaryView.urlname, args=[invoice.id]), invoice.invoice_number, ) for invoice in invoices]) )) class PlanInformationForm(forms.Form): name = forms.CharField(max_length=80) description = forms.CharField(required=False) edition = forms.ChoiceField(choices=SoftwarePlanEdition.CHOICES) visibility = forms.ChoiceField(choices=SoftwarePlanVisibility.CHOICES) max_domains = forms.IntegerField(required=False) is_customer_software_plan = forms.BooleanField(required=False) is_annual_plan = forms.BooleanField(required=False) def __init__(self, plan, *args, **kwargs): self.plan = plan if plan is not None: kwargs['initial'] = { 'name': plan.name, 'description': plan.description, 'edition': plan.edition, 'visibility': plan.visibility, 'max_domains': plan.max_domains, 'is_customer_software_plan': plan.is_customer_software_plan, 'is_annual_plan': plan.is_annual_plan } else: kwargs['initial'] = { 'edition': SoftwarePlanEdition.ENTERPRISE, 'visibility': SoftwarePlanVisibility.INTERNAL, } super(PlanInformationForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Plan Information', 'name', 'description', 'edition', 'visibility', 'max_domains', 'is_customer_software_plan', 'is_annual_plan' ), hqcrispy.FormActions( crispy.ButtonHolder( crispy.Submit( 'plan_information', '%s Software Plan' % ('Update' if plan is not None else 'Create'), css_class='disable-on-submit', ) ) ) ) def clean_name(self): name = self.cleaned_data['name'] if ( len(SoftwarePlan.objects.filter(name=name)) != 0 and (self.plan is None or self.plan.name != name) ): raise ValidationError(_('Name already taken. Please enter a new name.')) return name def create_plan(self): name = self.cleaned_data['name'] description = self.cleaned_data['description'] edition = self.cleaned_data['edition'] visibility = self.cleaned_data['visibility'] max_domains = self.cleaned_data['max_domains'] is_customer_software_plan = self.cleaned_data['is_customer_software_plan'] is_annual_plan = self.cleaned_data['is_annual_plan'] plan = SoftwarePlan(name=name, description=description, edition=edition, visibility=visibility, max_domains=max_domains, is_customer_software_plan=is_customer_software_plan, is_annual_plan=is_annual_plan ) plan.save() return plan def update_plan(self, request, plan): if DefaultProductPlan.objects.filter(plan=self.plan).exists(): messages.warning(request, "You cannot modify a non-custom software plan.") else: plan.name = self.cleaned_data['name'] plan.description = self.cleaned_data['description'] plan.edition = self.cleaned_data['edition'] plan.visibility = self.cleaned_data['visibility'] plan.max_domains = self.cleaned_data['max_domains'] plan.is_customer_software_plan = self.cleaned_data['is_customer_software_plan'] plan.is_annual_plan = self.cleaned_data['is_annual_plan'] plan.save() messages.success(request, "The %s Software Plan was successfully updated." % self.plan.name) class SoftwarePlanVersionForm(forms.Form): """ A form for updating the software plan """ update_version = forms.CharField( required=False, widget=forms.HiddenInput, ) select2_feature_id = forms.CharField( required=False, label="Search for or Create Feature", widget=forms.Select(choices=[]), ) new_feature_type = forms.ChoiceField( required=False, choices=FeatureType.CHOICES, ) feature_rates = forms.CharField( required=False, widget=forms.HiddenInput, ) product_rate_id = forms.CharField( required=False, label="Search for or Create Product", widget=forms.Select(choices=[]), ) product_rates = forms.CharField( required=False, widget=forms.HiddenInput, ) privileges = forms.MultipleChoiceField( required=False, label="Privileges", validators=[MinLengthValidator(1)] ) role_slug = forms.ChoiceField( required=False, label="Role", widget=forms.Select(choices=[]), ) role_type = forms.ChoiceField( required=True, choices=( ('existing', "Use Existing Role"), ('new', "Create New Role"), ) ) create_new_role = forms.BooleanField( required=False, widget=forms.HiddenInput, ) new_role_slug = forms.CharField( required=False, max_length=256, label="New Role Slug", help_text="A slug is a short label containing only letters, numbers, underscores or hyphens.", ) new_role_name = forms.CharField( required=False, max_length=256, label="New Role Name", ) new_role_description = forms.CharField( required=False, label="New Role Description", widget=forms.Textarea(attrs={"class": "vertical-resize"}), ) upgrade_subscriptions = forms.BooleanField( label="Automatically upgrade all subscriptions on the " "previous version of this plan to this version immediately.", required=False, ) new_product_rate = None def __init__(self, plan, plan_version, admin_web_user, *args, **kwargs): self.plan = plan self.plan_version = plan_version self.admin_web_user = admin_web_user self.is_update = False super(SoftwarePlanVersionForm, self).__init__(*args, **kwargs) if not self.plan.is_customer_software_plan: del self.fields['upgrade_subscriptions'] self.fields['privileges'].choices = list(self.available_privileges) self.fields['role_slug'].choices = [ (r['slug'], "%s (%s)" % (r['name'], r['slug'])) for r in self.existing_roles ] self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form form-horizontal' self.helper.form_method = 'POST' permissions_fieldset = crispy.Fieldset( "Permissions", hqcrispy.B3MultiField( "Role Type", crispy.Div( data_bind="template: {" " name: 'select-role-type-template', " " data: role" "}, " ), ), crispy.Div( hqcrispy.B3MultiField( 'Role', InlineField( 'role_slug', data_bind="value: role.existing.roleSlug", css_class="input-xxlarge", style="width: 100%;", ), crispy.Div( data_bind="template: {" " name: 'selected-role-privileges-template', " " data: {" " privileges: role.existing.selectedPrivileges," " hasNoPrivileges: role.existing.hasNoPrivileges" " }" "}, " ), data_bind="visible: role.isRoleTypeExisting", ), ), crispy.Div( hqcrispy.B3MultiField( "Privileges", InlineField('privileges', data_bind="selectedOptions: role.new.privileges"), crispy.Div( data_bind="template: {" " name: 'privileges-match-role-template', " " data: {" " role: role.new.matchingRole" " }," " if: role.new.hasMatchingRole" "}, " ), ), crispy.Field('create_new_role', data_bind="value: role.new.allowCreate"), crispy.Div( 'new_role_slug', 'new_role_name', 'new_role_description', data_bind="visible: role.new.allowCreate", css_class="well", ), data_bind="visible: role.isRoleTypeNew", ), ) features_fieldset = crispy.Fieldset( "Features", InlineField('feature_rates', data_bind="value: featureRates.ratesString"), hqcrispy.B3MultiField( "Add Feature", InlineField('select2_feature_id', css_class="input-xxlarge", data_bind="value: featureRates.select2.value"), StrictButton( "Select Feature", css_class="btn-primary", data_bind="event: {click: featureRates.apply}, " "visible: featureRates.select2.isExisting", style="margin-left: 5px;" ), ), crispy.Div( css_class="alert alert-danger", data_bind="text: featureRates.error, visible: featureRates.showError" ), hqcrispy.B3MultiField( "Feature Type", InlineField( 'new_feature_type', data_bind="value: featureRates.rateType", ), crispy.Div( StrictButton( "Create Feature", css_class="btn-primary", data_bind="event: {click: featureRates.createNew}", ), style="margin: 10px 0;" ), data_bind="visible: featureRates.select2.isNew", ), crispy.Div( data_bind="template: {" "name: 'feature-rate-form-template', foreach: featureRates.rates" "}", ), ) products_fieldset = crispy.Fieldset( "Products", InlineField('product_rates', data_bind="value: productRates.ratesString"), hqcrispy.B3MultiField( "Add Product", InlineField('product_rate_id', css_class="input-xxlarge", data_bind="value: productRates.select2.value"), StrictButton( "Select Product", css_class="btn-primary", data_bind="event: {click: productRates.apply}, " "visible: productRates.select2.isExisting", style="margin-left: 5px;" ), ), crispy.Div( css_class="alert alert-danger", data_bind="text: productRates.error, visible: productRates.showError", ), hqcrispy.B3MultiField( "Product Type", crispy.Div( StrictButton( "Create Product", css_class="btn-primary", data_bind="event: {click: productRates.createNew}", ), style="margin: 10px 0;" ), data_bind="visible: productRates.select2.isNew", ), crispy.Div( data_bind="template: {" "name: 'product-rate-form-template', foreach: productRates.rates" "}", ), ) layout_fields = [ 'update_version', permissions_fieldset, features_fieldset, products_fieldset ] if self.plan.is_customer_software_plan: layout_fields.append(crispy.Fieldset( "Manage Existing Subscriptions", 'upgrade_subscriptions' )) layout_fields.append( hqcrispy.FormActions( StrictButton( 'Update Plan Version', css_class='btn-primary disable-on-submit', type="submit", ), ) ) self.helper.layout = crispy.Layout(*layout_fields) @property def available_privileges(self): for priv in privileges.MAX_PRIVILEGES: role = Role.objects.get(slug=priv) yield (role.slug, role.name) @property def existing_roles(self): roles = set([r['role'] for r in SoftwarePlanVersion.objects.values('role').distinct()]) grant_roles = set([r['from_role'] for r in Grant.objects.filter( to_role__slug__in=privileges.MAX_PRIVILEGES).values('from_role').distinct()]) roles = roles.union(grant_roles) roles = [Role.objects.get(pk=r) for r in roles] for role in roles: yield { 'slug': role.slug, 'name': role.name, 'description': role.description, 'privileges': [ (grant.to_role.slug, grant.to_role.name) for grant in role.memberships_granted.all() ], } @property def feature_rates_dict(self): return { 'currentValue': self['feature_rates'].value(), 'handlerSlug': FeatureRateAsyncHandler.slug, 'select2Options': { 'fieldName': 'select2_feature_id', } } @property def product_rates_dict(self): return { 'currentValue': self['product_rates'].value(), 'handlerSlug': SoftwareProductRateAsyncHandler.slug, 'select2Options': { 'fieldName': 'product_rate_id', } } @property def role_dict(self): return { 'currentValue': self['privileges'].value(), 'multiSelectField': { 'slug': 'privileges', 'titleSelect': _("Privileges Available"), 'titleSelected': _("Privileges Selected"), 'titleSearch': _("Search Privileges..."), }, 'existingRoles': list(self.existing_roles), 'roleType': self['role_type'].value() or 'existing', 'newPrivileges': self['privileges'].value(), 'currentRoleSlug': self.plan_version.role.slug if self.plan_version is not None else None, } @property @memoized def current_features_to_rates(self): if self.plan_version is not None: return dict([(r.feature.id, r) for r in self.plan_version.feature_rates.all()]) else: return {} @staticmethod def _get_errors_from_subform(form_name, subform): for field, field_errors in subform._errors.items(): for field_error in field_errors: error_message = "%(form_name)s > %(field_name)s: %(error)s" % { 'form_name': form_name, 'error': field_error, 'field_name': subform[field].label, } yield error_message def _retrieve_feature_rate(self, rate_form): feature = Feature.objects.get(id=rate_form['feature_id'].value()) new_rate = rate_form.get_instance(feature) if rate_form.is_new(): # a brand new rate self.is_update = True return new_rate if feature.id not in self.current_features_to_rates: # the plan does not have this rate yet, compare any changes to the feature's current latest rate # also mark the form as updated current_rate = feature.get_rate(default_instance=False) if current_rate is None: return new_rate self.is_update = True else: current_rate = self.current_features_to_rates[feature.id] # note: custom implementation of FeatureRate.__eq__ here... if not (current_rate == new_rate): self.is_update = True return new_rate return current_rate def _retrieve_product_rate(self, rate_form): new_rate = rate_form.get_instance() if rate_form.is_new(): # a brand new rate self.is_update = True return new_rate try: current_rate = SoftwareProductRate.objects.get(id=rate_form['rate_id'].value()) # note: custom implementation of SoftwareProductRate.__eq__ here... if not (current_rate == new_rate): self.is_update = True return new_rate else: return current_rate except SoftwareProductRate.DoesNotExist: self.is_update = True return new_rate def clean_feature_rates(self): original_data = self.cleaned_data['feature_rates'] rates = json.loads(original_data) rate_instances = [] errors = ErrorList() for rate_data in rates: rate_form = FeatureRateForm(rate_data) if not rate_form.is_valid(): errors.extend(list(self._get_errors_from_subform(rate_data['name'], rate_form))) else: rate_instances.append(self._retrieve_feature_rate(rate_form)) if errors: self._errors.setdefault('feature_rates', errors) required_types = list(dict(FeatureType.CHOICES)) feature_types = [r.feature.feature_type for r in rate_instances] if any([feature_types.count(t) != 1 for t in required_types]): raise ValidationError(_( "You must specify exactly one rate per feature type " "(SMS, USER, etc.)" )) self.new_feature_rates = rate_instances def rate_ids(rate_list): return set([rate.id for rate in rate_list]) if ( not self.is_update and ( self.plan_version is None or rate_ids(rate_instances).symmetric_difference( rate_ids(self.plan_version.feature_rates.all()) ) ) ): self.is_update = True return original_data def clean_product_rates(self): original_data = self.cleaned_data['product_rates'] rates = json.loads(original_data) errors = ErrorList() if len(rates) != 1: raise ValidationError(_("You must specify exactly one product rate.")) rate_data = rates[0] rate_form = ProductRateForm(rate_data) if not rate_form.is_valid(): errors.extend(list(self._get_errors_from_subform(rate_data['name'], rate_form))) self._errors.setdefault('product_rates', errors) self.is_update = True else: self.new_product_rate = self._retrieve_product_rate(rate_form) self.is_update = ( self.is_update or self.plan_version is None or self.new_product_rate.id != self.plan_version.product_rate.id ) return original_data def clean_create_new_role(self): val = self.cleaned_data['create_new_role'] if val: self.is_update = True return val def clean_role_slug(self): role_slug = self.cleaned_data['role_slug'] if self.plan_version is None or role_slug != self.plan_version.role.slug: self.is_update = True return role_slug def clean_new_role_slug(self): val = self.cleaned_data['new_role_slug'] if self.cleaned_data['create_new_role'] and not val: raise ValidationError(_("A slug is required for this new role.")) if val: validate_slug(val) if Role.objects.filter(slug=val).count() != 0: raise ValidationError(_("Enter a unique role slug.")) return val def clean_new_role_name(self): val = self.cleaned_data['new_role_name'] if self.cleaned_data['create_new_role'] and not val: raise ValidationError(_("A name is required for this new role.")) return val @transaction.atomic def save(self, request): if DefaultProductPlan.objects.filter(plan=self.plan).exists(): messages.warning(request, "You cannot modify a non-custom software plan.") return if not self.is_update: messages.info(request, "No changes to rates and roles were present, so the current version was kept.") return if self.cleaned_data['create_new_role']: role = Role.objects.create( slug=self.cleaned_data['new_role_slug'], name=self.cleaned_data['new_role_name'], description=self.cleaned_data['new_role_description'], ) for privilege in self.cleaned_data['privileges']: privilege = Role.objects.get(slug=privilege) Grant.objects.create( from_role=role, to_role=privilege, ) else: role = Role.objects.get(slug=self.cleaned_data['role_slug']) new_version = SoftwarePlanVersion( plan=self.plan, role=role ) self.new_product_rate.save() new_version.product_rate = self.new_product_rate new_version.save() for feature_rate in self.new_feature_rates: feature_rate.save() new_version.feature_rates.add(feature_rate) new_version.save() messages.success( request, 'The version for %s Software Plan was successfully updated.' % new_version.plan.name ) if self.plan.is_customer_software_plan and self.cleaned_data['upgrade_subscriptions']: upgrade_subscriptions_to_latest_plan_version( self.plan_version, self.admin_web_user, upgrade_note="Immediately upgraded when creating a new version." ) messages.success( request, "All subscriptions on the previous version of this plan were " "also upgraded to this new version." ) class FeatureRateForm(forms.ModelForm): """ A form for creating a new FeatureRate. """ # feature id will point to a select2 field, hence the CharField here. feature_id = forms.CharField( required=False, widget=forms.HiddenInput, ) rate_id = forms.CharField( required=False, widget=forms.HiddenInput, ) class Meta(object): model = FeatureRate fields = ['monthly_fee', 'monthly_limit', 'per_excess_fee'] def __init__(self, data=None, *args, **kwargs): super(FeatureRateForm, self).__init__(data, *args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_tag = False self.helper.layout = crispy.Layout( crispy.HTML(""" <h4><span data-bind="text: name"></span> <span class="label label-default" style="display: inline-block; margin: 0 10px;" data-bind="text: feature_type"></span></h4> <hr /> """), crispy.Field('feature_id', data_bind="value: feature_id"), crispy.Field('rate_id', data_bind="value: rate_id"), crispy.Field('monthly_fee', data_bind="value: monthly_fee"), crispy.Field('monthly_limit', data_bind="value: monthly_limit"), crispy.Div( crispy.Field('per_excess_fee', data_bind="value: per_excess_fee"), data_bind="visible: isPerExcessVisible", ), ) def is_new(self): return not self['rate_id'].value() def get_instance(self, feature): instance = self.save(commit=False) instance.feature = feature return instance class ProductRateForm(forms.ModelForm): """ A form for creating a new ProductRate. """ name = forms.CharField( required=True, widget=forms.HiddenInput, ) rate_id = forms.CharField( required=False, widget=forms.HiddenInput, ) class Meta(object): model = SoftwareProductRate fields = ['monthly_fee', 'name'] def __init__(self, data=None, *args, **kwargs): super(ProductRateForm, self).__init__(data, *args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_tag = False self.helper.layout = crispy.Layout( crispy.HTML(""" <h4><span data-bind="text: name"></span></h4> <hr /> """), crispy.Field('monthly_fee', data_bind="value: monthly_fee"), ) def is_new(self): return not self['rate_id'].value() def get_instance(self): return self.save(commit=False) class EnterprisePlanContactForm(forms.Form): name = forms.CharField( label=gettext_noop("Name") ) company_name = forms.CharField( required=False, label=gettext_noop("Company / Organization") ) message = forms.CharField( required=False, label=gettext_noop("Message"), widget=forms.Textarea(attrs={"class": "vertical-resize"}) ) def __init__(self, domain, web_user, data=None, *args, **kwargs): self.domain = domain self.web_user = web_user super(EnterprisePlanContactForm, self).__init__(data, *args, **kwargs) from corehq.apps.domain.views.accounting import SelectPlanView self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = "form-horizontal" self.helper.layout = crispy.Layout( 'name', 'company_name', 'message', hqcrispy.FormActions( hqcrispy.LinkButton( _("Select different plan"), reverse(SelectPlanView.urlname, args=[self.domain]), css_class="btn btn-default" ), StrictButton( _("Request Quote"), type="submit", css_class="btn-primary", ), ) ) def send_message(self): subject = "[Enterprise Plan Request] %s" % self.domain context = { 'name': self.cleaned_data['name'], 'company': self.cleaned_data['company_name'], 'message': self.cleaned_data['message'], 'domain': self.domain, 'email': self.web_user.email } html_content = render_to_string('accounting/email/sales_request.html', context) text_content = """ Email: %(email)s Name: %(name)s Company: %(company)s Domain: %(domain)s Message: %(message)s """ % context send_html_email_async.delay(subject, settings.BILLING_EMAIL, html_content, text_content, email_from=settings.DEFAULT_FROM_EMAIL) class AnnualPlanContactForm(forms.Form): name = forms.CharField( label=gettext_noop("Name") ) company_name = forms.CharField( required=False, label=gettext_noop("Company / Organization") ) message = forms.CharField( required=False, label=gettext_noop("Message"), widget=forms.Textarea(attrs={"class": "vertical-resize"}) ) def __init__(self, domain, web_user, on_annual_plan, data=None, *args, **kwargs): self.domain = domain self.web_user = web_user super(AnnualPlanContactForm, self).__init__(data, *args, **kwargs) from corehq.apps.domain.views.accounting import SelectPlanView, DomainSubscriptionView self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = "form-horizontal" if on_annual_plan: back_button_text = "Back to my Subscription" urlname = DomainSubscriptionView.urlname else: back_button_text = "Select different plan" urlname = SelectPlanView.urlname self.helper.layout = crispy.Layout( 'name', 'company_name', 'message', hqcrispy.FormActions( hqcrispy.LinkButton( _(back_button_text), reverse(urlname, args=[self.domain]), css_class="btn btn-default" ), StrictButton( _("Submit"), type="submit", css_class="btn-primary", ), ) ) def send_message(self): subject = "[Annual Plan Request] %s" % self.domain context = { 'name': self.cleaned_data['name'], 'company': self.cleaned_data['company_name'], 'message': self.cleaned_data['message'], 'domain': self.domain, 'email': self.web_user.email } html_content = render_to_string('accounting/email/sales_request.html', context) text_content = """ Email: %(email)s Name: %(name)s Company: %(company)s Domain: %(domain)s Message: %(message)s """ % context send_html_email_async.delay(subject, settings.BILLING_EMAIL, html_content, text_content, email_from=settings.DEFAULT_FROM_EMAIL) class TriggerInvoiceForm(forms.Form): month = forms.ChoiceField(label="Statement Period Month") year = forms.ChoiceField(label="Statement Period Year") domain = forms.CharField(label="Project Space", widget=forms.Select(choices=[])) num_users = forms.IntegerField( label="Number of Users", required=False, help_text="This is part of accounting tests and overwrites the " "DomainUserHistory recorded for this month. Please leave " "this blank to use what is already in the system." ) def __init__(self, *args, **kwargs): self.show_testing_options = kwargs.pop('show_testing_options') super(TriggerInvoiceForm, self).__init__(*args, **kwargs) today = datetime.date.today() one_month_ago = today - relativedelta(months=1) self.fields['month'].initial = one_month_ago.month self.fields['month'].choices = list(MONTHS.items()) self.fields['year'].initial = one_month_ago.year self.fields['year'].choices = [ (y, y) for y in range(one_month_ago.year, 2012, -1) ] self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form form-horizontal' details = [ 'Trigger Invoice Details', crispy.Field('month', css_class="input-large"), crispy.Field('year', css_class="input-large"), crispy.Field( 'domain', css_class="input-xxlarge accounting-async-select2", placeholder="Search for Project" ) ] if self.show_testing_options: details.append(crispy.Field('num_users', css_class='input_large')) else: del self.fields['num_users'] self.helper.layout = crispy.Layout( crispy.Fieldset(*details), hqcrispy.FormActions( StrictButton( "Trigger Invoice", css_class="btn-primary disable-on-submit", type="submit", ), ) ) @transaction.atomic def trigger_invoice(self): year = int(self.cleaned_data['year']) month = int(self.cleaned_data['month']) invoice_start, invoice_end = get_first_last_days(year, month) domain_obj = Domain.get_by_name(self.cleaned_data['domain']) self.clean_previous_invoices(invoice_start, invoice_end, domain_obj.name) if self.show_testing_options and self.cleaned_data['num_users']: num_users = int(self.cleaned_data['num_users']) existing_histories = DomainUserHistory.objects.filter( domain=domain_obj.name, record_date__gte=invoice_start, record_date__lte=invoice_end, ) if existing_histories.exists(): existing_histories.all().delete() DomainUserHistory.objects.create( domain=domain_obj.name, record_date=invoice_end, num_users=num_users ) invoice_factory = DomainInvoiceFactory( invoice_start, invoice_end, domain_obj, recipients=[settings.ACCOUNTS_EMAIL] ) invoice_factory.create_invoices() @staticmethod def clean_previous_invoices(invoice_start, invoice_end, domain_name): prev_invoices = Invoice.objects.filter( date_start__lte=invoice_end, date_end__gte=invoice_start, subscription__subscriber__domain=domain_name ) if prev_invoices.count() > 0: from corehq.apps.accounting.views import InvoiceSummaryView raise InvoiceError( "Invoices exist that were already generated with this same " "criteria. You must manually suppress these invoices: " "{invoice_list}".format( invoice_list=', '.join( ['<a href="{edit_url}">{name}</a>'.format( edit_url=reverse(InvoiceSummaryView.urlname, args=(x.id,)), name=x.invoice_number ) for x in prev_invoices.all()] ), ) ) def clean(self): today = datetime.date.today() year = int(self.cleaned_data['year']) month = int(self.cleaned_data['month']) if (year, month) >= (today.year, today.month): raise ValidationError('Statement period must be in the past') class TriggerCustomerInvoiceForm(forms.Form): month = forms.ChoiceField(label="Statement Period Month") year = forms.ChoiceField(label="Statement Period Year") customer_account = forms.CharField(label="Billing Account", widget=forms.Select(choices=[])) def __init__(self, *args, **kwargs): super(TriggerCustomerInvoiceForm, self).__init__(*args, **kwargs) today = datetime.date.today() one_month_ago = today - relativedelta(months=1) self.fields['month'].initial = one_month_ago.month self.fields['month'].choices = list(MONTHS.items()) self.fields['year'].initial = one_month_ago.year self.fields['year'].choices = [ (y, y) for y in range(one_month_ago.year, 2012, -1) ] self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form form-horizontal' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Trigger Customer Invoice Details', crispy.Field('month', css_class="input-large"), crispy.Field('year', css_class="input-large"), crispy.Field('customer_account', css_class="input-xxlarge accounting-async-select2", placeholder="Search for Customer Billing Account") ), hqcrispy.FormActions( StrictButton( "Trigger Customer Invoice", css_class="btn-primary disable-on-submit", type="submit", ), ) ) @transaction.atomic def trigger_customer_invoice(self): year = int(self.cleaned_data['year']) month = int(self.cleaned_data['month']) try: account = BillingAccount.objects.get(name=self.cleaned_data['customer_account']) invoice_start, invoice_end = self.get_invoice_dates(account, year, month) self.clean_previous_invoices(invoice_start, invoice_end, account) invoice_factory = CustomerAccountInvoiceFactory( date_start=invoice_start, date_end=invoice_end, account=account, recipients=[settings.ACCOUNTS_EMAIL] ) invoice_factory.create_invoice() except BillingAccount.DoesNotExist: raise InvoiceError( "There is no Billing Account associated with %s" % self.cleaned_data['customer_account'] ) @staticmethod def clean_previous_invoices(invoice_start, invoice_end, account): prev_invoices = CustomerInvoice.objects.filter( date_start__lte=invoice_end, date_end__gte=invoice_start, account=account ) if prev_invoices: from corehq.apps.accounting.views import CustomerInvoiceSummaryView raise InvoiceError( "Invoices exist that were already generated with this same " "criteria. You must manually suppress these invoices: " "{invoice_list}".format( invoice_list=', '.join( ['<a href="{edit_url}">{name}</a>'.format( edit_url=reverse(CustomerInvoiceSummaryView.urlname, args=(x.id,)), name=x.invoice_number ) for x in prev_invoices] ), ) ) def clean(self): today = datetime.date.today() year = int(self.cleaned_data['year']) month = int(self.cleaned_data['month']) if (year, month) >= (today.year, today.month): raise ValidationError('Statement period must be in the past') def get_invoice_dates(self, account, year, month): if account.invoicing_plan == InvoicingPlan.YEARLY: if month == 12: # Set invoice start date to January 1st return datetime.date(year, 1, 1), datetime.date(year, 12, 31) else: raise InvoiceError( "%s is set to be invoiced yearly, and you may not invoice in this month. " "You must select December in the year for which you are triggering an annual invoice." % self.cleaned_data['customer_account'] ) if account.invoicing_plan == InvoicingPlan.QUARTERLY: if month == 3: return datetime.date(year, 1, 1), datetime.date(year, 3, 31) # Quarter 1 if month == 6: return datetime.date(year, 4, 1), datetime.date(year, 6, 30) # Quarter 2 if month == 9: return datetime.date(year, 7, 1), datetime.date(year, 9, 30) # Quarter 3 if month == 12: return datetime.date(year, 10, 1), datetime.date(year, 12, 31) # Quarter 4 else: raise InvoiceError( "%s is set to be invoiced quarterly, and you may not invoice in this month. " "You must select the last month of a quarter to trigger a quarterly invoice." % self.cleaned_data['customer_account'] ) else: return get_first_last_days(year, month) class TriggerBookkeeperEmailForm(forms.Form): month = forms.ChoiceField(label="Invoice Month") year = forms.ChoiceField(label="Invoice Year") emails = forms.CharField(label="Email To", widget=forms.SelectMultiple(choices=[]),) def __init__(self, *args, **kwargs): super(TriggerBookkeeperEmailForm, self).__init__(*args, **kwargs) today = datetime.date.today() self.fields['month'].initial = today.month self.fields['month'].choices = list(MONTHS.items()) self.fields['year'].initial = today.year self.fields['year'].choices = [ (y, y) for y in range(today.year, 2012, -1) ] self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form form-horizontal' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Trigger Bookkeeper Email Details', crispy.Field('emails', css_class='input-xxlarge accounting-email-select2', data_initial=json.dumps(self.initial.get('emails'))), crispy.Field('month', css_class="input-large"), crispy.Field('year', css_class="input-large"), ), hqcrispy.FormActions( StrictButton( "Trigger Bookkeeper Email", css_class="btn-primary disable-on-submit", type="submit", ), ) ) def clean_emails(self): return self.data.getlist('emails') def trigger_email(self): from corehq.apps.accounting.tasks import send_bookkeeper_email send_bookkeeper_email( month=int(self.cleaned_data['month']), year=int(self.cleaned_data['year']), emails=self.cleaned_data['emails'] ) class TestReminderEmailFrom(forms.Form): days = forms.ChoiceField( label="Days Until Subscription Ends", choices=( (1, 1), (10, 10), (30, 30), ) ) def __init__(self, *args, **kwargs): super(TestReminderEmailFrom, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form form-horizontal' self.helper.layout = crispy.Layout( crispy.Fieldset( "Test Subscription Reminder Emails", 'days', ), crispy.Div( crispy.HTML( "Note that this will ONLY send emails to a billing admin " "for a domain IF the billing admin is an Accounting " "Previewer." ), css_class="alert alert-info" ), hqcrispy.FormActions( StrictButton( "Send Reminder Emails", type="submit", css_class='btn-primary disable-on-submit' ) ) ) def send_emails(self): send_subscription_reminder_emails(int(self.cleaned_data['days'])) class AdjustBalanceForm(forms.Form): adjustment_type = forms.ChoiceField( widget=forms.RadioSelect, ) custom_amount = forms.DecimalField( required=False, ) method = forms.ChoiceField( choices=( (CreditAdjustmentReason.MANUAL, "Register back office payment"), (CreditAdjustmentReason.TRANSFER, "Take from available credit lines"), ( CreditAdjustmentReason.FRIENDLY_WRITE_OFF, "Forgive amount with a friendly write-off" ), ) ) note = forms.CharField( required=True, widget=forms.Textarea(attrs={"class": "vertical-resize"}), ) invoice_id = forms.CharField( widget=forms.HiddenInput(), ) adjust = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, invoice, *args, **kwargs): self.invoice = invoice super().__init__(*args, **kwargs) self.fields['adjustment_type'].choices = ( ('current', 'Pay off Current Balance: %s' % get_money_str(self.invoice.balance)), ('credit', 'Pay off Custom Amount'), ) self.fields['invoice_id'].initial = invoice.id self.helper = FormHelper() self.helper.form_class = "form-horizontal" self.helper.label_class = 'col-sm-4 col-md-3' self.helper.field_class = 'col-sm-8 col-md-9' if invoice.is_customer_invoice: self.helper.form_action = reverse('customer_invoice_summary', args=[self.invoice.id]) else: self.helper.form_action = reverse('invoice_summary', args=[self.invoice.id]) self.helper.layout = crispy.Layout( crispy.Div( crispy.Field( 'adjustment_type', data_bind="checked: adjustmentType", ), crispy.HTML(''' <div id="div_id_custom_amount" class="form-group" data-bind="visible: showCustomAmount"> <label for="id_custom_amount" class="control-label col-sm-4 col-md-3"> Custom amount </label> <div class="col-sm-8 col-md-9"> <input class="textinput textInput form-control" id="id_custom_amount" name="custom_amount" type="number" step="any"> </div> </div> '''), crispy.Field('method'), crispy.Field('note'), crispy.Field('invoice_id'), 'adjust', css_class='modal-body ko-adjust-balance-form', ), crispy.Div( crispy.Submit( 'adjust_balance', 'Apply', css_class='disable-on-submit', data_loading_text='Submitting...', ), crispy.Button( 'close', 'Close', css_class='disable-on-submit btn-default', data_dismiss='modal', ), css_class='modal-footer', ), ) @property @memoized def amount(self): adjustment_type = self.cleaned_data['adjustment_type'] if adjustment_type == 'current': return self.invoice.balance elif adjustment_type == 'credit': return Decimal(self.cleaned_data['custom_amount']) else: raise ValidationError(_("Received invalid adjustment type: %s") % adjustment_type) @transaction.atomic def adjust_balance(self, web_user=None): method = self.cleaned_data['method'] kwargs = { 'account': (self.invoice.account if self.invoice.is_customer_invoice else self.invoice.subscription.account), 'note': self.cleaned_data['note'], 'reason': method, 'subscription': None if self.invoice.is_customer_invoice else self.invoice.subscription, 'web_user': web_user, } if method in [ CreditAdjustmentReason.MANUAL, CreditAdjustmentReason.FRIENDLY_WRITE_OFF, ]: if self.invoice.is_customer_invoice: CreditLine.add_credit( -self.amount, customer_invoice=self.invoice, **kwargs ) else: CreditLine.add_credit( -self.amount, invoice=self.invoice, **kwargs ) CreditLine.add_credit( self.amount, permit_inactive=True, **kwargs ) elif method == CreditAdjustmentReason.TRANSFER: if self.invoice.is_customer_invoice: subscription_invoice = None customer_invoice = self.invoice credit_line_balance = sum( credit_line.balance for credit_line in CreditLine.get_credits_for_customer_invoice(self.invoice) ) else: subscription_invoice = self.invoice customer_invoice = None credit_line_balance = sum( credit_line.balance for credit_line in CreditLine.get_credits_for_invoice(self.invoice) ) transfer_balance = ( min(self.amount, credit_line_balance) if credit_line_balance > 0 else min(0, self.amount) ) CreditLine.add_credit( -transfer_balance, invoice=subscription_invoice, customer_invoice=customer_invoice, **kwargs ) self.invoice.update_balance() self.invoice.save() class InvoiceInfoForm(forms.Form): subscription = forms.CharField() project = forms.CharField() account = forms.CharField() current_balance = forms.CharField() def __init__(self, invoice, *args, **kwargs): self.invoice = invoice subscription = invoice.subscription if not (invoice.is_wire or invoice.is_customer_invoice) else None super(InvoiceInfoForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form-horizontal' from corehq.apps.accounting.views import ( EditSubscriptionView, ManageBillingAccountView, ) if not invoice.is_wire and not invoice.is_customer_invoice: subscription_link = make_anchor_tag( reverse(EditSubscriptionView.urlname, args=(subscription.id,)), format_html( '{plan_name} ({start_date} - {end_date})', plan_name=subscription.plan_version, start_date=subscription.date_start, end_date=subscription.date_end, ) ) else: subscription_link = 'N/A' self.helper.layout = crispy.Layout( crispy.Fieldset( '{} Invoice #{}'.format('Customer' if invoice.is_customer_invoice else 'Wire' if invoice.is_wire else '', invoice.invoice_number), ) ) if not invoice.is_customer_invoice: self.helper.layout[0].extend([ hqcrispy.B3TextField( 'subscription', subscription_link ), hqcrispy.B3TextField( 'project', invoice.get_domain(), ) ]) self.helper.layout[0].extend([ hqcrispy.B3TextField( 'account', format_html( '<a href="{}">Super {}</a>', reverse( ManageBillingAccountView.urlname, args=(invoice.account.id,) ), invoice.account.name ), ), hqcrispy.B3TextField( 'current_balance', get_money_str(invoice.balance), ), hqcrispy.B3MultiField( 'Balance Adjustments', crispy.Button( 'submit', 'Adjust Balance', data_toggle='modal', data_target='#adjustBalanceModal-%d' % invoice.id, css_class=('btn-default disabled' if invoice.is_wire else 'btn-default') + ' disable-on-submit', ), ) ]) class ResendEmailForm(forms.Form): additional_recipients = forms.CharField( label="Additional Recipients:", required=False, ) resend = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, invoice, *args, **kwargs): self.invoice = invoice super(ResendEmailForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form-horizontal' self.helper.layout = crispy.Layout( crispy.Div( crispy.HTML( 'This will send an email to: %s.' % ', '.join(invoice.email_recipients) ), crispy.Field('additional_recipients'), 'resend', css_class='modal-body', ), crispy.Div( crispy.Submit( 'resend_email', 'Send Email', css_class='disable-on-submit', data_loading_text='Submitting...', ), crispy.Button( 'close', 'Close', css_class='disable-on-submit btn-default', data_dismiss='modal', ), css_class='modal-footer', ), ) def clean_additional_recipients(self): return [ email.strip() for email in self.cleaned_data['additional_recipients'].split(',') ] def resend_email(self): contact_emails = set(self.invoice.email_recipients) | set(self.cleaned_data['additional_recipients']) if self.invoice.is_wire: record = WireBillingRecord.generate_record(self.invoice) elif self.invoice.is_customer_invoice: record = CustomerBillingRecord.generate_record(self.invoice) else: record = BillingRecord.generate_record(self.invoice) for email in contact_emails: record.send_email(contact_email=email) class SuppressInvoiceForm(forms.Form): submit_kwarg = 'suppress' suppress = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, invoice, *args, **kwargs): self.invoice = invoice super(SuppressInvoiceForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form-horizontal' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Suppress invoice from all reports and user-facing statements', crispy.Div( crispy.HTML('Warning: this can only be undone by a developer.'), css_class='alert alert-danger', ), 'suppress', ), hqcrispy.FormActions( StrictButton( 'Suppress Invoice', css_class='btn-danger disable-on-submit', name=self.submit_kwarg, type='submit', ), ), ) def suppress_invoice(self): self.invoice.is_hidden_to_ops = True self.invoice.save() class HideInvoiceForm(forms.Form): submit_kwarg = 'hide' hide = forms.CharField(widget=forms.HiddenInput, required=False) def __init__(self, invoice, *args, **kwargs): self.invoice = invoice super(HideInvoiceForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form-horizontal' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Hide invoice from customer.', crispy.Div( crispy.HTML('Warning: this can only be undone by a developer.'), css_class='alert alert-danger', ), 'hide', ), hqcrispy.FormActions( StrictButton( 'Hide Invoice', css_class='btn-danger disable-on-submit', name=self.submit_kwarg, type='submit', ), ), ) def hide_invoice(self): self.invoice.is_hidden = True self.invoice.save() class CreateAdminForm(forms.Form): username = forms.CharField( required=False, ) def __init__(self, *args, **kwargs): super(CreateAdminForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_show_labels = False self.helper.form_style = 'inline' self.helper.layout = crispy.Layout( InlineField( 'username', css_id="select-admin-username", ), StrictButton( format_html('<i class="fa fa-plus"></i> {}', 'Add Admin'), css_class="btn-primary disable-on-submit", type="submit", ) ) @transaction.atomic def add_admin_user(self): # create UserRole for user username = self.cleaned_data['username'] try: user = User.objects.get(username=username) except User.DoesNotExist: raise CreateAccountingAdminError( "User '%s' does not exist" % username ) web_user = WebUser.get_by_username(username) if not web_user or not web_user.is_superuser: raise CreateAccountingAdminError( "The user '%s' is not a superuser." % username, ) try: user_role = UserRole.objects.get(user=user) except UserRole.DoesNotExist: user_privs = Role.objects.get_or_create( name="Privileges for %s" % user.username, slug="%s_privileges" % user.username, )[0] user_role = UserRole.objects.create( user=user, role=user_privs, ) ops_role = Role.objects.get(slug=privileges.OPERATIONS_TEAM) if not user_role.role.has_privilege(ops_role): Grant.objects.create(from_role=user_role.role, to_role=ops_role) return user class TriggerDowngradeForm(forms.Form): domain = forms.CharField(label="Project Space", widget=forms.Select(choices=[])) def __init__(self, *args, **kwargs): super(TriggerDowngradeForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form form-horizontal' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Trigger Downgrade Details', crispy.Field( 'domain', css_class="input-xxlarge accounting-async-select2", placeholder="Search for Project" ), ), hqcrispy.FormActions( StrictButton( "Trigger Downgrade", css_class="btn-primary disable-on-submit", type="submit", ), ) ) class TriggerAutopaymentsForm(forms.Form): domain = forms.CharField(label="Project Space", widget=forms.Select(choices=[])) def __init__(self, *args, **kwargs): super(TriggerAutopaymentsForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.form_class = 'form form-horizontal' self.helper.layout = crispy.Layout( crispy.Fieldset( 'Trigger Autopayments Details', crispy.Field( 'domain', css_class="input-xxlarge accounting-async-select2", placeholder="Search for Project" ), ), hqcrispy.FormActions( StrictButton( "Trigger Autopayments for Project", css_class="btn-primary disable-on-submit", type="submit", ), ) )
bsd-3-clause
e344909a047c67d472912df86278db02
37.749289
114
0.545066
4.315025
false
false
false
false
dimagi/commcare-hq
corehq/apps/toggle_ui/migrations/0002_toggleaudit.py
1
1136
# Generated by Django 2.2.16 on 2020-11-23 15:03 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('toggle_ui', '0001_reconcile_commtrack_flags'), ] operations = [ migrations.CreateModel( name='ToggleAudit', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now=True)), ('slug', models.TextField()), ('username', models.CharField(help_text='Username of user making change', max_length=256)), ('action', models.CharField(choices=[('add', 'add'), ('remove', 'remove'), ('random', 'random')], max_length=12)), ('namespace', models.CharField(choices=[('user', 'user'), ('domain', 'domain'), ('other', 'other')], max_length=12, null=True)), ('item', models.TextField(null=True)), ('randomness', models.DecimalField(decimal_places=5, max_digits=6, null=True)), ], ), ]
bsd-3-clause
107e425fb8b21d1b747fd3e6dc5219ed
39.571429
144
0.568662
4.191882
false
false
false
false
dimagi/commcare-hq
corehq/motech/repeaters/signals.py
1
4310
import time from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from corehq.form_processor.signals import sql_case_post_save from corehq.util.metrics import metrics_counter from couchforms.signals import successful_form_received from corehq.apps.locations.models import SQLLocation from corehq.apps.users.signals import commcare_user_post_save from corehq.form_processor.models import CommCareCase from corehq.motech.repeaters.models import ( CreateCaseRepeater, ReferCaseRepeater, UpdateCaseRepeater, domain_can_forward, DataRegistryCaseUpdateRepeater, ) from dimagi.utils.logging import notify_exception def create_form_repeat_records(sender, xform, **kwargs): from corehq.motech.repeaters.models import FormRepeater if not xform.is_duplicate: create_repeat_records(FormRepeater, xform) def create_case_repeat_records(sender, case, **kwargs): from corehq.motech.repeaters.models import CaseRepeater from corehq.motech.repeaters.expression.repeaters import CaseExpressionRepeater create_repeat_records(CaseRepeater, case) create_repeat_records(CreateCaseRepeater, case) create_repeat_records(UpdateCaseRepeater, case) create_repeat_records(ReferCaseRepeater, case) create_repeat_records(CaseExpressionRepeater, case) def create_short_form_repeat_records(sender, xform, **kwargs): from corehq.motech.repeaters.models import ShortFormRepeater if not xform.is_duplicate: create_repeat_records(ShortFormRepeater, xform) def create_repeat_records(repeater_cls, payload): # As a temporary fix for https://dimagi-dev.atlassian.net/browse/SUPPORT-12244 # Make a serious attempt to retry creating the repeat record # The real fix is to figure out why the form reprocessing system # isn't resulting in the signal getting re-fired and the repeat record getting created. for sleep_length in [.5, 1, 2, 4, 8] if not settings.UNIT_TESTING else [0, 0]: try: _create_repeat_records(repeater_cls, payload) except Exception: notify_exception(None, "create_repeat_records had an error resulting in a retry") metrics_counter('commcare.repeaters.error_creating_record', tags={ 'domain': payload.domain, 'repeater_type': repeater_cls.__name__, }) time.sleep(sleep_length) else: return metrics_counter('commcare.repeaters.failed_to_create_record', tags={ 'domain': payload.domain, 'repeater_type': repeater_cls.__name__, }) def _create_repeat_records(repeater_cls, payload, fire_synchronously=False): repeater_name = repeater_cls.__module__ + '.' + repeater_cls.__name__ if settings.REPEATERS_WHITELIST is not None and repeater_name not in settings.REPEATERS_WHITELIST: return domain = payload.domain if domain_can_forward(domain): repeaters = repeater_cls.by_domain(domain, stale_query=True) for repeater in repeaters: repeater.register(payload, fire_synchronously=fire_synchronously) @receiver(commcare_user_post_save, dispatch_uid="create_user_repeat_records") def create_user_repeat_records(sender, couch_user, **kwargs): from corehq.motech.repeaters.models import UserRepeater create_repeat_records(UserRepeater, couch_user) @receiver(post_save, sender=SQLLocation, dispatch_uid="create_location_repeat_records") def create_location_repeat_records(sender, raw=False, **kwargs): from corehq.motech.repeaters.models import LocationRepeater if raw: return create_repeat_records(LocationRepeater, kwargs['instance']) @receiver(sql_case_post_save, sender=CommCareCase, dispatch_uid="fire_synchronous_repeaters") def fire_synchronous_case_repeaters(sender, case, **kwargs): """These repeaters need to fire synchronously since the changes they make to cases must reflect by the end of form submission processing """ _create_repeat_records(DataRegistryCaseUpdateRepeater, case, fire_synchronously=True) successful_form_received.connect(create_form_repeat_records) successful_form_received.connect(create_short_form_repeat_records) sql_case_post_save.connect(create_case_repeat_records, CommCareCase)
bsd-3-clause
66848c17883bfa3242e7564dfc4c4a6d
40.047619
102
0.741995
3.652542
false
false
false
false
dimagi/commcare-hq
corehq/apps/users/views/mobile/users.py
1
61968
import io import json import re import time from braces.views import JsonRequestResponseMixin from couchdbkit import ResourceNotFound from django.contrib import messages from django.contrib.humanize.templatetags.humanize import naturaltime from django.core.exceptions import ValidationError from django.http import ( Http404, HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, ) from django.http.response import HttpResponseServerError, JsonResponse from django.shortcuts import redirect, render from django.template.loader import render_to_string from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.translation import gettext as _ from django.utils.translation import gettext_noop, override from django.views.decorators.http import require_GET, require_POST from django.views.generic import TemplateView, View from django_prbac.exceptions import PermissionDenied from django_prbac.utils import has_privilege from memoized import memoized from casexml.apps.phone.models import SyncLogSQL from corehq import privileges from corehq.apps.accounting.async_handlers import Select2BillingInfoHandler from corehq.apps.accounting.decorators import requires_privilege_with_fallback from corehq.apps.accounting.models import ( BillingAccount, BillingAccountType, EntryPoint, ) from corehq.apps.accounting.utils import domain_has_privilege from corehq.apps.analytics.tasks import track_workflow from corehq.apps.custom_data_fields.edit_entity import CustomDataEditor from corehq.apps.custom_data_fields.models import ( CUSTOM_DATA_FIELD_PREFIX, PROFILE_SLUG, ) from corehq.apps.domain.models import SMSAccountConfirmationSettings from corehq.apps.sms.api import send_sms from corehq.apps.domain.utils import guess_domain_language_for_sms from corehq.apps.domain.decorators import domain_admin_required, login_and_domain_required from corehq.apps.domain.extension_points import has_custom_clean_password from corehq.apps.domain.views.base import DomainViewMixin from corehq.apps.es import FormES from corehq.apps.groups.models import Group from corehq.apps.hqwebapp.async_handler import AsyncHandlerMixin from corehq.apps.hqwebapp.crispy import make_form_readonly from corehq.apps.hqwebapp.decorators import use_multiselect from corehq.apps.hqwebapp.utils import get_bulk_upload_form from corehq.apps.locations.analytics import users_have_locations from corehq.apps.locations.models import SQLLocation from corehq.apps.locations.permissions import ( location_safe, user_can_access_location_id, ) from corehq.apps.ota.utils import demo_restore_date_created, turn_off_demo_mode from corehq.apps.registration.forms import ( MobileWorkerAccountConfirmationBySMSForm, MobileWorkerAccountConfirmationForm ) from corehq.apps.sms.verify import initiate_sms_verification_workflow from corehq.apps.users.account_confirmation import ( send_account_confirmation_if_necessary, send_account_confirmation_sms_if_necessary, ) from corehq.apps.users.analytics import get_search_users_in_domain_es_query from corehq.apps.users.audit.change_messages import UserChangeMessage from corehq.apps.users.bulk_download import get_domains_from_user_filters from corehq.apps.users.dbaccessors import get_user_docs_by_username from corehq.apps.users.decorators import ( require_can_edit_commcare_users, require_can_edit_or_view_commcare_users, require_can_edit_web_users, require_can_use_filtered_user_download, ) from corehq.apps.users.exceptions import InvalidRequestException from corehq.apps.users.forms import ( CommCareAccountForm, CommCareUserFormSet, CommtrackUserForm, ConfirmExtraUserChargesForm, MultipleSelectionForm, NewMobileWorkerForm, SetUserPasswordForm, UserFilterForm, ) from corehq.apps.users.models import ( CommCareUser, CouchUser, DeactivateMobileWorkerTrigger, ) from corehq.apps.users.models_role import UserRole from corehq.apps.users.tasks import ( bulk_download_usernames_async, bulk_download_users_async, reset_demo_user_restore_task, turn_on_demo_mode_task, ) from corehq.apps.users.util import ( can_add_extra_mobile_workers, format_username, generate_mobile_username, log_user_change, raw_username, ) from corehq.apps.users.views import ( BaseEditUserView, BaseManageWebUserView, BaseUploadUser, UserUploadJobPollView, BaseUserSettingsView, get_domain_languages, ) from corehq.const import ( USER_CHANGE_VIA_BULK_IMPORTER, USER_CHANGE_VIA_WEB, USER_DATE_FORMAT, ) from corehq import toggles from corehq.motech.utils import b64_aes_decrypt from corehq.pillows.utils import MOBILE_USER_TYPE, WEB_USER_TYPE from corehq.util import get_document_or_404 from corehq.util.dates import iso_string_to_datetime from corehq.util.jqueryrmi import JSONResponseMixin, allow_remote_invocation from corehq.util.metrics import metrics_counter from corehq.util.workbook_json.excel import ( WorkbookJSONError, WorksheetNotFound, get_workbook, ) from couchexport.models import Format from couchexport.writers import Excel2007ExportWriter from soil import DownloadBase from soil.exceptions import TaskFailedError from soil.util import get_download_context from .custom_data_fields import UserFieldsView from ..utils import log_user_groups_change BULK_MOBILE_HELP_SITE = ("https://confluence.dimagi.com/display/commcarepublic" "/Create+and+Manage+CommCare+Mobile+Workers#Createand" "ManageCommCareMobileWorkers-B.UseBulkUploadtocreatem" "ultipleusersatonce") DEFAULT_USER_LIST_LIMIT = 10 BAD_MOBILE_USERNAME_REGEX = re.compile("[^A-Za-z0-9.+-_]") def _can_edit_workers_location(web_user, mobile_worker): if web_user.has_permission(mobile_worker.domain, 'access_all_locations'): return True loc_id = mobile_worker.location_id if not loc_id: return False return user_can_access_location_id(mobile_worker.domain, web_user, loc_id) @location_safe class EditCommCareUserView(BaseEditUserView): urlname = "edit_commcare_user" page_title = gettext_noop("Edit Mobile Worker") @property def page_name(self): if self.request.is_view_only: return _("Edit Mobile Worker (View Only)") return self.page_title @property def template_name(self): if self.editable_user.is_deleted(): return "users/deleted_account.html" else: return "users/edit_commcare_user.html" @use_multiselect @method_decorator(require_can_edit_or_view_commcare_users) def dispatch(self, request, *args, **kwargs): return super(EditCommCareUserView, self).dispatch(request, *args, **kwargs) @property def main_context(self): context = super(EditCommCareUserView, self).main_context profiles = [profile.to_json() for profile in self.form_user_update.custom_data.model.get_profiles()] context.update({ 'custom_fields_slugs': [f.slug for f in self.form_user_update.custom_data.fields], 'custom_fields_profiles': sorted(profiles, key=lambda x: x['name'].lower()), 'custom_fields_profile_slug': PROFILE_SLUG, 'edit_user_form_title': self.edit_user_form_title, 'strong_mobile_passwords': self.request.project.strong_mobile_passwords, 'has_any_sync_logs': self.has_any_sync_logs, 'token': self.backup_token, }) return context @property def has_any_sync_logs(self): return SyncLogSQL.objects.filter(user_id=self.editable_user_id).exists() @property @memoized def editable_user(self): try: user = CouchUser.get_by_user_id(self.editable_user_id, self.domain) except (ResourceNotFound, CouchUser.AccountTypeError, KeyError): raise Http404() if not user or not _can_edit_workers_location(self.couch_user, user): raise Http404() return user @property def edit_user_form_title(self): return _("Information for %s") % self.editable_user.human_friendly_name @property def is_currently_logged_in_user(self): return self.editable_user_id == self.couch_user._id @property @memoized def reset_password_form(self): return SetUserPasswordForm(self.request.project, self.editable_user_id, user="") @property @memoized def groups(self): if not self.editable_user: return [] return Group.by_user_id(self.editable_user_id) @property @memoized def all_groups(self): # note: will slow things down if there are loads of groups. worth it? # justification: ~every report already does this. return Group.by_domain(self.domain) @property @memoized def group_form(self): form = MultipleSelectionForm(initial={ 'selected_ids': [g._id for g in self.groups], }) form.fields['selected_ids'].choices = [(g._id, g.name) for g in self.all_groups] return form @property @memoized def commtrack_form(self): if self.request.method == "POST" and self.request.POST['form_type'] == "commtrack": return CommtrackUserForm(self.request.POST, request=self.request, domain=self.domain) # currently only support one location on the UI linked_loc = self.editable_user.location initial_id = linked_loc._id if linked_loc else None program_id = self.editable_user.get_domain_membership(self.domain).program_id assigned_locations = self.editable_user.assigned_location_ids return CommtrackUserForm( domain=self.domain, request=self.request, initial={ 'primary_location': initial_id, 'program_id': program_id, 'assigned_locations': assigned_locations} ) @property def page_context(self): if self.request.is_view_only: make_form_readonly(self.commtrack_form) make_form_readonly(self.form_user_update.user_form) make_form_readonly(self.form_user_update.custom_data.form) context = { 'are_groups': bool(len(self.all_groups)), 'groups_url': reverse('all_groups', args=[self.domain]), 'group_form': self.group_form, 'reset_password_form': self.reset_password_form, 'is_currently_logged_in_user': self.is_currently_logged_in_user, 'data_fields_form': self.form_user_update.custom_data.form, 'can_use_inbound_sms': domain_has_privilege(self.domain, privileges.INBOUND_SMS), 'show_deactivate_after_date': self.form_user_update.user_form.show_deactivate_after_date, 'can_create_groups': ( self.request.couch_user.has_permission(self.domain, 'edit_groups') and self.request.couch_user.has_permission(self.domain, 'access_all_locations') ), 'needs_to_downgrade_locations': ( users_have_locations(self.domain) and not has_privilege(self.request, privileges.LOCATIONS) ), 'demo_restore_date': naturaltime(demo_restore_date_created(self.editable_user)), 'group_names': [g.name for g in self.groups], } if self.commtrack_form.errors: messages.error(self.request, _( "There were some errors while saving user's locations. Please check the 'Locations' tab" )) if self.domain_object.commtrack_enabled or self.domain_object.uses_locations: context.update({ 'commtrack_enabled': self.domain_object.commtrack_enabled, 'uses_locations': self.domain_object.uses_locations, 'commtrack': { 'update_form': self.commtrack_form, }, }) return context @property def user_role_choices(self): role_choices = self.editable_role_choices default_role = UserRole.commcare_user_default(self.domain) return [(default_role.get_qualified_id(), default_role.name)] + role_choices @property @memoized def form_user_update(self): if (self.request.method == "POST" and self.request.POST['form_type'] == "update-user" and not self.request.is_view_only): data = self.request.POST else: data = None form = CommCareUserFormSet(data=data, domain=self.domain, editable_user=self.editable_user, request_user=self.request.couch_user, request=self.request) form.user_form.load_language(language_choices=get_domain_languages(self.domain)) if self.can_change_user_roles or self.couch_user.can_view_roles(): form.user_form.load_roles(current_role=self.existing_role, role_choices=self.user_role_choices) else: del form.user_form.fields['role'] return form @property def parent_pages(self): return [{ 'title': MobileWorkerListView.page_title, 'url': reverse(MobileWorkerListView.urlname, args=[self.domain]), }] def post(self, request, *args, **kwargs): if self.request.is_view_only: messages.error( request, _("You do not have permission to update Mobile Workers.") ) return super(EditCommCareUserView, self).get(request, *args, **kwargs) if self.request.POST['form_type'] == "add-phonenumber": phone_number = self.request.POST['phone_number'] phone_number = re.sub(r'\s', '', phone_number) if re.match(r'\d+$', phone_number): is_new_phone_number = phone_number not in self.editable_user.phone_numbers self.editable_user.add_phone_number(phone_number) self.editable_user.save(spawn_task=True) if is_new_phone_number: log_user_change( by_domain=self.request.domain, for_domain=self.editable_user.domain, couch_user=self.editable_user, changed_by_user=self.request.couch_user, changed_via=USER_CHANGE_VIA_WEB, change_messages=UserChangeMessage.phone_numbers_added([phone_number]) ) messages.success(request, _("Phone number added.")) else: messages.error(request, _("Please enter digits only.")) return super(EditCommCareUserView, self).post(request, *args, **kwargs) class ConfirmBillingAccountForExtraUsersView(BaseUserSettingsView, AsyncHandlerMixin): urlname = 'extra_users_confirm_billing' template_name = 'users/extra_users_confirm_billing.html' page_title = gettext_noop("Confirm Billing Information") async_handlers = [ Select2BillingInfoHandler, ] @property @memoized def account(self): account = BillingAccount.get_or_create_account_by_domain( self.domain, created_by=self.couch_user.username, account_type=BillingAccountType.USER_CREATED, entry_point=EntryPoint.SELF_STARTED, )[0] return account @property @memoized def billing_info_form(self): if self.request.method == 'POST': return ConfirmExtraUserChargesForm( self.account, self.domain, self.request.couch_user.username, data=self.request.POST ) return ConfirmExtraUserChargesForm(self.account, self.domain, self.request.couch_user.username) @property def page_context(self): return { 'billing_info_form': self.billing_info_form, } @method_decorator(domain_admin_required) def dispatch(self, request, *args, **kwargs): if self.account.date_confirmed_extra_charges is not None: return HttpResponseRedirect(reverse(MobileWorkerListView.urlname, args=[self.domain])) return super(ConfirmBillingAccountForExtraUsersView, self).dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): if self.async_response is not None: return self.async_response if self.billing_info_form.is_valid(): is_saved = self.billing_info_form.save() if not is_saved: messages.error( request, _("It appears that there was an issue updating your contact information. " "We've been notified of the issue. Please try submitting again, and if the problem " "persists, please try in a few hours.")) else: messages.success( request, _("Billing contact information was successfully confirmed. " "You may now add additional Mobile Workers.") ) return HttpResponseRedirect(reverse( MobileWorkerListView.urlname, args=[self.domain] )) return self.get(request, *args, **kwargs) @require_can_edit_commcare_users @location_safe @require_POST def delete_commcare_user(request, domain, user_id): user = CommCareUser.get_by_user_id(user_id, domain) if not _can_edit_workers_location(request.couch_user, user): raise PermissionDenied() if (user.user_location_id and SQLLocation.objects.get_or_None(location_id=user.user_location_id, user_id=user._id)): messages.error(request, _("This is a location user. You must delete the " "corresponding location before you can delete this user.")) return HttpResponseRedirect(reverse(EditCommCareUserView.urlname, args=[domain, user_id])) user.retire(request.domain, deleted_by=request.couch_user, deleted_via=USER_CHANGE_VIA_WEB) messages.success(request, "User %s has been deleted. All their submissions and cases will be permanently deleted in the next few minutes" % user.username) return HttpResponseRedirect(reverse(MobileWorkerListView.urlname, args=[domain])) @require_can_edit_commcare_users @location_safe @require_POST def force_user_412(request, domain, user_id): user = CommCareUser.get_by_user_id(user_id, domain) if not _can_edit_workers_location(request.couch_user, user): raise PermissionDenied() metrics_counter('commcare.force_user_412.count', tags={'domain': domain}) SyncLogSQL.objects.filter(user_id=user_id).delete() messages.success( request, "Mobile Worker {}'s device data will be hard refreshed the next time they sync." .format(user.human_friendly_name) ) return HttpResponseRedirect(reverse(EditCommCareUserView.urlname, args=[domain, user_id]) + '#user-permanent') @require_can_edit_commcare_users @require_POST def restore_commcare_user(request, domain, user_id): user = CommCareUser.get_by_user_id(user_id, domain) success, message = user.unretire(request.domain, unretired_by=request.couch_user, unretired_via=USER_CHANGE_VIA_WEB) if success: messages.success(request, "User %s and all their submissions have been restored" % user.username) else: messages.error(request, message) return HttpResponseRedirect(reverse(EditCommCareUserView.urlname, args=[domain, user_id])) @require_can_edit_commcare_users @require_POST def toggle_demo_mode(request, domain, user_id): user = CommCareUser.get_by_user_id(user_id, domain) demo_mode = request.POST.get('demo_mode', 'no') demo_mode = True if demo_mode == 'yes' else False edit_user_url = reverse(EditCommCareUserView.urlname, args=[domain, user_id]) # handle bad POST param if user.is_demo_user == demo_mode: warning = _("User is already in Demo mode!") if user.is_demo_user else _("User is not in Demo mode!") messages.warning(request, warning) return HttpResponseRedirect(edit_user_url) if demo_mode: download = DownloadBase() res = turn_on_demo_mode_task.delay(user.get_id, domain) download.set_task(res) return HttpResponseRedirect( reverse( DemoRestoreStatusView.urlname, args=[domain, download.download_id, user_id] ) ) else: from corehq.apps.app_manager.views.utils import unset_practice_mode_configured_apps, \ get_practice_mode_configured_apps # if the user is being used as practice user on any apps, check/ask for confirmation apps = get_practice_mode_configured_apps(domain) confirm_turn_off = True if (request.POST.get('confirm_turn_off', 'no')) == 'yes' else False if apps and not confirm_turn_off: return HttpResponseRedirect(reverse(ConfirmTurnOffDemoModeView.urlname, args=[domain, user_id])) turn_off_demo_mode(user) unset_practice_mode_configured_apps(domain, user.get_id) messages.success(request, _("Successfully turned off demo mode!")) return HttpResponseRedirect(edit_user_url) class BaseManageCommCareUserView(BaseUserSettingsView): @method_decorator(require_can_edit_commcare_users) def dispatch(self, request, *args, **kwargs): return super(BaseManageCommCareUserView, self).dispatch(request, *args, **kwargs) @property def parent_pages(self): return [{ 'title': MobileWorkerListView.page_title, 'url': reverse(MobileWorkerListView.urlname, args=[self.domain]), }] class ConfirmTurnOffDemoModeView(BaseManageCommCareUserView): template_name = 'users/confirm_turn_off_demo_mode.html' urlname = 'confirm_turn_off_demo_mode' page_title = gettext_noop("Turn off Demo mode") @property def page_context(self): from corehq.apps.app_manager.views.utils import get_practice_mode_configured_apps user_id = self.kwargs.pop('couch_user_id') user = CommCareUser.get_by_user_id(user_id, self.domain) practice_apps = get_practice_mode_configured_apps(self.domain, user_id) return { 'commcare_user': user, 'practice_apps': practice_apps, } def page_url(self): return reverse(self.urlname, args=self.args, kwargs=self.kwargs) class DemoRestoreStatusView(BaseManageCommCareUserView): urlname = 'demo_restore_status' page_title = gettext_noop('Demo User Status') def dispatch(self, request, *args, **kwargs): return super(DemoRestoreStatusView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): context = super(DemoRestoreStatusView, self).main_context context.update({ 'domain': self.domain, 'download_id': kwargs['download_id'], 'poll_url': reverse('demo_restore_job_poll', args=[self.domain, kwargs['download_id']]), 'title': _("Demo User status"), 'progress_text': _("Getting latest restore data, please wait"), 'error_text': _("There was an unexpected error! Please try again or report an issue."), 'next_url': reverse(EditCommCareUserView.urlname, args=[self.domain, kwargs['user_id']]), 'next_url_text': _("Go back to Edit Mobile Worker"), }) return render(request, 'hqwebapp/soil_status_full.html', context) def page_url(self): return reverse(self.urlname, args=self.args, kwargs=self.kwargs) @require_can_edit_commcare_users def demo_restore_job_poll(request, domain, download_id, template="users/mobile/partials/demo_restore_status.html"): try: context = get_download_context(download_id) except TaskFailedError: return HttpResponseServerError() context.update({ 'on_complete_short': _('Done'), 'on_complete_long': _('User is now in Demo mode with latest restore!'), }) return render(request, template, context) @require_can_edit_commcare_users @require_POST def reset_demo_user_restore(request, domain, user_id): user = CommCareUser.get_by_user_id(user_id, domain) if not user.is_demo_user: warning = _("The user is not a demo user.") messages.warning(request, warning) return HttpResponseRedirect(reverse(EditCommCareUserView.urlname, args=[domain, user_id])) download = DownloadBase() res = reset_demo_user_restore_task.delay(user.get_id, domain) download.set_task(res) return HttpResponseRedirect( reverse( DemoRestoreStatusView.urlname, args=[domain, download.download_id, user_id] ) ) @require_can_edit_commcare_users @require_POST def update_user_groups(request, domain, couch_user_id): form = MultipleSelectionForm(request.POST) form.fields['selected_ids'].choices = [(id, 'throwaway') for id in Group.ids_by_domain(domain)] if form.is_valid(): user = CommCareUser.get(couch_user_id) old_group_ids = user.get_group_ids() new_group_ids = form.cleaned_data['selected_ids'] assert user.doc_type == "CommCareUser" assert user.domain == domain user.set_groups(new_group_ids) if old_group_ids != new_group_ids: log_user_groups_change(domain, request, user, new_group_ids) messages.success(request, _("User groups updated!")) else: messages.error(request, _("Form not valid. A group may have been deleted while you were viewing this page" "Please try again.")) return HttpResponseRedirect(reverse(EditCommCareUserView.urlname, args=[domain, couch_user_id])) @location_safe class MobileWorkerListView(JSONResponseMixin, BaseUserSettingsView): template_name = 'users/mobile_workers.html' urlname = 'mobile_workers' page_title = gettext_noop("Mobile Workers") @method_decorator(require_can_edit_or_view_commcare_users) def dispatch(self, *args, **kwargs): return super(MobileWorkerListView, self).dispatch(*args, **kwargs) @property @memoized def can_access_all_locations(self): return self.couch_user.has_permission(self.domain, 'access_all_locations') @property def can_bulk_edit_users(self): return has_privilege(self.request, privileges.BULK_USER_MANAGEMENT) and not self.request.is_view_only @property def can_add_extra_users(self): return can_add_extra_mobile_workers(self.request) @property @memoized def new_mobile_worker_form(self): if self.request.method == "POST": return NewMobileWorkerForm(self.request.project, self.couch_user, self.request.POST) return NewMobileWorkerForm(self.request.project, self.couch_user) @property @memoized def custom_data(self): return CustomDataEditor( field_view=UserFieldsView, domain=self.domain, post_dict=self.request.POST if self.request.method == "POST" else None, required_only=True, ko_model="custom_fields", ) @property def two_stage_user_confirmation(self): return toggles.TWO_STAGE_USER_PROVISIONING.enabled( self.domain ) or toggles.TWO_STAGE_USER_PROVISIONING_BY_SMS.enabled(self.domain) @property def page_context(self): bulk_download_url = reverse(FilteredCommCareUserDownload.urlname, args=[self.domain]) profiles = [profile.to_json() for profile in self.custom_data.model.get_profiles()] return { 'new_mobile_worker_form': self.new_mobile_worker_form, 'custom_fields_form': self.custom_data.form, 'custom_fields_slugs': [f.slug for f in self.custom_data.fields], 'custom_fields_profiles': profiles, 'custom_fields_profile_slug': PROFILE_SLUG, 'can_bulk_edit_users': self.can_bulk_edit_users, 'can_add_extra_users': self.can_add_extra_users, 'can_access_all_locations': self.can_access_all_locations, 'skip_standard_password_validations': has_custom_clean_password(), 'pagination_limit_cookie_name': ( 'hq.pagination.limit.mobile_workers_list.%s' % self.domain), 'can_edit_billing_info': self.request.couch_user.is_domain_admin(self.domain), 'strong_mobile_passwords': self.request.project.strong_mobile_passwords, 'bulk_download_url': bulk_download_url, 'show_deactivate_after_date': self.new_mobile_worker_form.show_deactivate_after_date, 'two_stage_user_confirmation': self.two_stage_user_confirmation, } @property @memoized def query(self): return self.request.GET.get('query') @allow_remote_invocation def check_username(self, in_data): try: username = generate_mobile_username(in_data['username'].strip(), self.domain) except ValidationError as e: return {'error': e.message} else: return {'success': _('Username {} is available').format(username)} @allow_remote_invocation def create_mobile_worker(self, in_data): if self.request.is_view_only: return { 'error': _("You do not have permission to create mobile workers.") } try: self._ensure_proper_request(in_data) form_data = self._construct_form_data(in_data) except InvalidRequestException as e: return { 'error': str(e) } self.request.POST = form_data is_valid = lambda: self.new_mobile_worker_form.is_valid() and self.custom_data.is_valid() if not is_valid(): all_errors = [e for errors in self.new_mobile_worker_form.errors.values() for e in errors] all_errors += [e for errors in self.custom_data.errors.values() for e in errors] return {'error': _("Forms did not validate: {errors}").format( errors=', '.join(all_errors) )} couch_user = self._build_commcare_user() if self.new_mobile_worker_form.cleaned_data['send_account_confirmation_email']: send_account_confirmation_if_necessary(couch_user) if self.new_mobile_worker_form.cleaned_data['force_account_confirmation_by_sms']: phone_number = self.new_mobile_worker_form.cleaned_data['phone_number'] couch_user.set_default_phone_number(phone_number) send_account_confirmation_sms_if_necessary(couch_user) return { 'success': True, 'user_id': couch_user.userID, } def _build_commcare_user(self): username = self.new_mobile_worker_form.cleaned_data['username'] password = self.new_mobile_worker_form.cleaned_data['new_password'] first_name = self.new_mobile_worker_form.cleaned_data['first_name'] email = self.new_mobile_worker_form.cleaned_data['email'] last_name = self.new_mobile_worker_form.cleaned_data['last_name'] location_id = self.new_mobile_worker_form.cleaned_data['location_id'] is_account_confirmed = not ( self.new_mobile_worker_form.cleaned_data['force_account_confirmation'] or self.new_mobile_worker_form.cleaned_data['force_account_confirmation_by_sms']) role_id = UserRole.commcare_user_default(self.domain).get_id commcare_user = CommCareUser.create( self.domain, username, password, created_by=self.request.couch_user, created_via=USER_CHANGE_VIA_WEB, email=email, device_id="Generated from HQ", first_name=first_name, last_name=last_name, metadata=self.custom_data.get_data_to_save(), is_account_confirmed=is_account_confirmed, location=SQLLocation.objects.get(location_id=location_id) if location_id else None, role_id=role_id ) if self.new_mobile_worker_form.show_deactivate_after_date: DeactivateMobileWorkerTrigger.update_trigger( self.domain, commcare_user.user_id, self.new_mobile_worker_form.cleaned_data['deactivate_after_date'] ) return commcare_user def _ensure_proper_request(self, in_data): if not self.can_add_extra_users: raise InvalidRequestException(_("No Permission.")) if 'user' not in in_data: raise InvalidRequestException(_("Please provide mobile worker data.")) return None def _construct_form_data(self, in_data): try: user_data = in_data['user'] form_data = { 'username': user_data.get('username'), 'new_password': user_data.get('password'), 'first_name': user_data.get('first_name'), 'last_name': user_data.get('last_name'), 'location_id': user_data.get('location_id'), 'email': user_data.get('email'), 'force_account_confirmation': user_data.get('force_account_confirmation'), 'send_account_confirmation_email': user_data.get('send_account_confirmation_email'), 'force_account_confirmation_by_sms': user_data.get('force_account_confirmation_by_sms'), 'phone_number': user_data.get('phone_number'), 'deactivate_after_date': user_data.get('deactivate_after_date'), 'domain': self.domain, } for k, v in user_data.get('custom_fields', {}).items(): form_data["{}-{}".format(CUSTOM_DATA_FIELD_PREFIX, k)] = v return form_data except Exception as e: raise InvalidRequestException(_("Check your request: {}").format(e)) @require_can_edit_commcare_users @require_POST @location_safe def activate_commcare_user(request, domain, user_id): return _modify_user_status(request, domain, user_id, True) @require_can_edit_commcare_users @require_POST @location_safe def deactivate_commcare_user(request, domain, user_id): return _modify_user_status(request, domain, user_id, False) def _modify_user_status(request, domain, user_id, is_active): user = CommCareUser.get_by_user_id(user_id, domain) if (not _can_edit_workers_location(request.couch_user, user) or (is_active and not can_add_extra_mobile_workers(request))): return JsonResponse({ 'error': _("No Permission."), }) if not is_active and user.user_location_id: return JsonResponse({ 'error': _("This is a location user, archive or delete the " "corresponding location to deactivate it."), }) user.is_active = is_active user.save(spawn_task=True) log_user_change(by_domain=request.domain, for_domain=user.domain, couch_user=user, changed_by_user=request.couch_user, changed_via=USER_CHANGE_VIA_WEB, fields_changed={'is_active': user.is_active}) return JsonResponse({ 'success': True, }) @require_can_edit_commcare_users @require_POST @location_safe def send_confirmation_email(request, domain, user_id): user = CommCareUser.get_by_user_id(user_id, domain) send_account_confirmation_if_necessary(user) return JsonResponse(data={'success': True}) @require_POST @location_safe def send_confirmation_sms(request, domain, user_id): user = CommCareUser.get_by_user_id(user_id, domain) send_account_confirmation_sms_if_necessary(user) return JsonResponse(data={'success': True}) @require_can_edit_or_view_commcare_users @require_GET @location_safe def paginate_mobile_workers(request, domain): limit = int(request.GET.get('limit', 10)) page = int(request.GET.get('page', 1)) query = request.GET.get('query') deactivated_only = json.loads(request.GET.get('showDeactivatedUsers', "false")) def _user_query(search_string, page, limit): user_es = get_search_users_in_domain_es_query( domain=domain, search_string=search_string, offset=page * limit, limit=limit) if not request.couch_user.has_permission(domain, 'access_all_locations'): loc_ids = (SQLLocation.objects.accessible_to_user(domain, request.couch_user) .location_ids()) user_es = user_es.location(list(loc_ids)) return user_es.mobile_users() # backend pages start at 0 users_query = _user_query(query, page - 1, limit) # run with a blank query to fetch total records with same scope as in search if deactivated_only: users_query = users_query.show_only_inactive() users_data = users_query.source([ '_id', 'first_name', 'last_name', 'base_username', 'created_on', 'is_active', 'is_account_confirmed', ]).run() users = users_data.hits def _status_string(user_data): if user_data['is_active']: return _('Active') elif user_data['is_account_confirmed']: return _('Deactivated') else: return _('Pending Confirmation') for user in users: date_registered = user.pop('created_on', '') if date_registered: date_registered = iso_string_to_datetime(date_registered).strftime(USER_DATE_FORMAT) # make sure these are always set and default to true user['is_active'] = user.get('is_active', True) user['is_account_confirmed'] = user.get('is_account_confirmed', True) user.update({ 'username': user.pop('base_username', ''), 'user_id': user.pop('_id'), 'date_registered': date_registered, 'status': _status_string(user), }) return JsonResponse({ 'users': users, 'total': users_data.total, }) class CreateCommCareUserModal(JsonRequestResponseMixin, DomainViewMixin, View): template_name = "users/new_mobile_worker_modal.html" urlname = 'new_mobile_worker_modal' @method_decorator(require_can_edit_commcare_users) def dispatch(self, request, *args, **kwargs): if not can_add_extra_mobile_workers(request): raise PermissionDenied() return super(CreateCommCareUserModal, self).dispatch(request, *args, **kwargs) def render_form(self, status): if domain_has_privilege(self.domain, privileges.APP_USER_PROFILES): return self.render_json_response({ "status": "failure", "form_html": "<div class='alert alert-danger'>{}</div>".format(_(""" Cannot add new worker due to usage of user field profiles. Please add your new worker from the mobile workers page. """)), }) return self.render_json_response({ "status": status, "form_html": render_to_string(self.template_name, { 'form': self.new_commcare_user_form, 'data_fields_form': self.custom_data.form, }, request=self.request) }) def get(self, request, *args, **kwargs): return self.render_form("success") @property @memoized def custom_data(self): return CustomDataEditor( field_view=UserFieldsView, domain=self.domain, post_dict=self.request.POST if self.request.method == "POST" else None, ) @property @memoized def new_commcare_user_form(self): if self.request.method == "POST": data = self.request.POST.dict() form = CommCareAccountForm(data, domain=self.domain) else: form = CommCareAccountForm(domain=self.domain) return form @method_decorator(requires_privilege_with_fallback(privileges.OUTBOUND_SMS)) def post(self, request, *args, **kwargs): if self.new_commcare_user_form.is_valid() and self.custom_data.is_valid(): username = self.new_commcare_user_form.cleaned_data['username'] password = self.new_commcare_user_form.cleaned_data['password_1'] phone_number = self.new_commcare_user_form.cleaned_data['phone_number'] user = CommCareUser.create( self.domain, username, password, created_by=request.couch_user, created_via=USER_CHANGE_VIA_WEB, phone_number=phone_number, device_id="Generated from HQ", metadata=self.custom_data.get_data_to_save(), ) if 'location_id' in request.GET: try: loc = SQLLocation.objects.get(domain=self.domain, location_id=request.GET['location_id']) except SQLLocation.DoesNotExist: raise Http404() user.set_location(loc) if phone_number: initiate_sms_verification_workflow(user, phone_number) user_json = {'user_id': user._id, 'text': user.username_in_report} return self.render_json_response({"status": "success", "user": user_json}) return self.render_form("failure") def get_user_upload_context(domain, request_params, download_url, adjective, plural_noun): context = { 'bulk_upload': { "help_site": { "address": BULK_MOBILE_HELP_SITE, "name": _("CommCare Help Site"), }, "download_url": reverse(download_url, args=(domain,)), "adjective": _(adjective), "plural_noun": _(plural_noun), }, 'show_secret_settings': request_params.get("secret", False), } context.update({ 'bulk_upload_form': get_bulk_upload_form(context), }) return context class UploadCommCareUsers(BaseUploadUser): template_name = 'hqwebapp/bulk_upload.html' urlname = 'upload_commcare_users' page_title = gettext_noop("Bulk Upload Mobile Workers") is_web_upload = False @method_decorator(require_can_edit_commcare_users) @method_decorator(requires_privilege_with_fallback(privileges.BULK_USER_MANAGEMENT)) def dispatch(self, request, *args, **kwargs): return super(UploadCommCareUsers, self).dispatch(request, *args, **kwargs) @property def page_context(self): request_params = self.request.GET if self.request.method == 'GET' else self.request.POST return get_user_upload_context(self.domain, request_params, "download_commcare_users", "mobile worker", "mobile workers") def post(self, request, *args, **kwargs): return super(UploadCommCareUsers, self).post(request, *args, **kwargs) class UserUploadStatusView(BaseManageCommCareUserView): urlname = 'user_upload_status' page_title = gettext_noop('Mobile Worker Upload Status') def get(self, request, *args, **kwargs): context = super(UserUploadStatusView, self).main_context context.update({ 'domain': self.domain, 'download_id': kwargs['download_id'], 'poll_url': reverse(CommcareUserUploadJobPollView.urlname, args=[self.domain, kwargs['download_id']]), 'title': _("Mobile Worker Upload Status"), 'progress_text': _("Importing your data. This may take some time..."), 'error_text': _("Problem importing data! Please try again or report an issue."), 'next_url': reverse(MobileWorkerListView.urlname, args=[self.domain]), 'next_url_text': _("Return to manage mobile workers"), }) return render(request, 'hqwebapp/soil_status_full.html', context) def page_url(self): return reverse(self.urlname, args=self.args, kwargs=self.kwargs) class CommcareUserUploadJobPollView(UserUploadJobPollView): urlname = "commcare_user_upload_job_poll" on_complete_long = 'Mobile Worker upload has finished' user_type = 'mobile users' @method_decorator(require_can_edit_commcare_users) def dispatch(self, request, *args, **kwargs): return super(CommcareUserUploadJobPollView, self).dispatch(request, *args, **kwargs) @require_can_edit_or_view_commcare_users @location_safe def user_download_job_poll(request, domain, download_id, template="hqwebapp/partials/shared_download_status.html"): try: context = get_download_context(download_id, 'Preparing download') context.update({'link_text': _('Download Users')}) except TaskFailedError as e: return HttpResponseServerError(e.errors) return render(request, template, context) @location_safe class DownloadUsersStatusView(BaseUserSettingsView): urlname = 'download_users_status' page_title = gettext_noop('Download Users Status') @method_decorator(require_can_edit_or_view_commcare_users) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) @property def parent_pages(self): return [{ 'title': MobileWorkerListView.page_title, 'url': reverse(MobileWorkerListView.urlname, args=[self.domain]), }] def get(self, request, *args, **kwargs): context = super(DownloadUsersStatusView, self).main_context context.update({ 'domain': self.domain, 'download_id': kwargs['download_id'], 'poll_url': reverse('user_download_job_poll', args=[self.domain, kwargs['download_id']]), 'title': _("Download Users Status"), 'progress_text': _("Preparing user download."), 'error_text': _("There was an unexpected error! Please try again or report an issue."), 'next_url': reverse(MobileWorkerListView.urlname, args=[self.domain]), 'next_url_text': _("Go back to Mobile Workers"), }) return render(request, 'hqwebapp/soil_status_full.html', context) def page_url(self): return reverse(self.urlname, args=self.args, kwargs=self.kwargs) class FilteredUserDownload(BaseUserSettingsView): def get(self, request, domain, *args, **kwargs): form = UserFilterForm(request.GET, domain=domain, couch_user=request.couch_user, user_type=self.user_type) # To avoid errors on first page load form.empty_permitted = True context = self.main_context context.update({'form': form, 'count_users_url': reverse(self.count_view, args=[domain])}) return render( request, "users/filter_and_download.html", context ) @location_safe class FilteredCommCareUserDownload(FilteredUserDownload, BaseManageCommCareUserView): page_title = gettext_noop('Filter and Download Mobile Workers') urlname = 'filter_and_download_commcare_users' user_type = MOBILE_USER_TYPE count_view = 'count_commcare_users' @method_decorator(require_can_edit_commcare_users) def get(self, request, domain, *args, **kwargs): return super().get(request, domain, *args, **kwargs) @method_decorator([require_can_use_filtered_user_download], name='dispatch') class FilteredWebUserDownload(FilteredUserDownload, BaseManageWebUserView): page_title = gettext_noop('Filter and Download Users') urlname = 'filter_and_download_web_users' user_type = WEB_USER_TYPE count_view = 'count_web_users' @method_decorator(require_can_edit_web_users) def get(self, request, domain, *args, **kwargs): return super().get(request, domain, *args, **kwargs) class UsernameUploadMixin(object): """ Contains helper functions for working with a file that consists of a single column of usernames. """ def _get_usernames(self, request): """ Get username list from Excel supplied in request.FILES. Adds any errors to request.messages. """ sheet = self._get_sheet(request) if not sheet: return None try: usernames = [format_username(row['username'], request.domain) for row in sheet] except KeyError: messages.error(request, _("No users found. Please check your file contains a 'username' column.")) return None if not len(usernames): messages.error(request, _("No users found. Please check file is not empty.")) return None return usernames def _get_sheet(self, request): try: workbook = get_workbook(request.FILES.get('bulk_upload_file')) except WorkbookJSONError as e: messages.error(request, str(e)) return None try: sheet = workbook.get_worksheet() except WorksheetNotFound: messages.error(request, _("Workbook has no worksheets")) return None return sheet class DeleteCommCareUsers(BaseManageCommCareUserView, UsernameUploadMixin): urlname = 'delete_commcare_users' page_title = gettext_noop('Bulk Delete') template_name = 'users/bulk_delete.html' @property def page_context(self): context = self.main_context context.update({ 'bulk_upload_form': get_bulk_upload_form(), }) return context def post(self, request, *args, **kwargs): usernames = self._get_usernames(request) if not usernames: return self.get(request, *args, **kwargs) user_docs_by_id = {doc['_id']: doc for doc in get_user_docs_by_username(usernames)} user_ids_with_forms = self._get_user_ids_with_forms(request, user_docs_by_id) usernames_not_found = self._get_usernames_not_found(request, user_docs_by_id, usernames) if user_ids_with_forms or usernames_not_found: messages.error(request, _(""" No users deleted. Please address the above issue(s) and re-upload your updated file. """)) else: self._delete_users(request, user_docs_by_id, user_ids_with_forms) return self.get(request, *args, **kwargs) def _get_user_ids_with_forms(self, request, user_docs_by_id): """ Find users who have ever submitted a form, and add to request.messages if so. """ user_ids_with_forms = ( FormES() .domain(request.domain) .user_id(list(user_docs_by_id)) .terms_aggregation('form.meta.userID', 'user_id') ).run().aggregations.user_id.keys if user_ids_with_forms: message = _(""" The following users have form submissions and must be deleted individually: {}. """).format(", ".join([raw_username(user_docs_by_id[user_id]['username']) for user_id in user_ids_with_forms])) messages.error(request, message) return user_ids_with_forms def _get_usernames_not_found(self, request, user_docs_by_id, usernames): """ The only side effect of this is to possibly add to request.messages. """ usernames_not_found = set(usernames) - {doc['username'] for doc in user_docs_by_id.values()} if usernames_not_found: message = _("The following users were not found: {}.").format( ", ".join(map(raw_username, usernames_not_found))) messages.error(request, message) return usernames_not_found def _delete_users(self, request, user_docs_by_id, user_ids_with_forms): deleted_count = 0 for user_id, doc in user_docs_by_id.items(): if user_id not in user_ids_with_forms: CommCareUser.wrap(doc).delete(request.domain, deleted_by=request.couch_user, deleted_via=USER_CHANGE_VIA_BULK_IMPORTER) deleted_count += 1 if deleted_count: messages.success(request, f"{deleted_count} user(s) deleted.") class CommCareUsersLookup(BaseManageCommCareUserView, UsernameUploadMixin): urlname = 'commcare_users_lookup' page_title = gettext_noop('Mobile Workers Bulk Lookup') template_name = 'users/bulk_lookup.html' @property def page_context(self): context = self.main_context context.update({ 'bulk_upload_form': get_bulk_upload_form(), }) return context def post(self, request, *args, **kwargs): usernames = self._get_usernames(request) if not usernames: return self.get(request, *args, **kwargs) docs_by_username = {doc['username']: doc for doc in get_user_docs_by_username(usernames)} rows = [] for username in usernames: row = [raw_username(username)] if username in docs_by_username: row.extend([_("yes"), docs_by_username[username].get("is_active")]) else: row.extend([_("no"), ""]) rows.append(row) response = HttpResponse(content_type=Format.from_format('xlsx').mimetype) response['Content-Disposition'] = f'attachment; filename="{self.domain} users.xlsx"' response.write(self._excel_data(rows)) return response def _excel_data(self, rows): outfile = io.BytesIO() tab_name = "users" header_table = [(tab_name, [(_("username"), _("exists"), _("is_active"))])] writer = Excel2007ExportWriter() writer.open(header_table=header_table, file=outfile) writer.write([(tab_name, rows)]) writer.close() return outfile.getvalue() @require_can_edit_commcare_users @location_safe def count_commcare_users(request, domain): return _count_users(request, domain, MOBILE_USER_TYPE) @require_can_edit_web_users @require_can_use_filtered_user_download def count_web_users(request, domain): return _count_users(request, domain, WEB_USER_TYPE) @login_and_domain_required def _count_users(request, domain, user_type): if user_type not in [MOBILE_USER_TYPE, WEB_USER_TYPE]: raise AssertionError(f"Invalid user type for _count_users: {user_type}") from corehq.apps.users.dbaccessors import ( count_mobile_users_by_filters, count_web_users_by_filters, count_invitations_by_filters, ) form = UserFilterForm(request.GET, domain=domain, couch_user=request.couch_user, user_type=user_type) if form.is_valid(): user_filters = form.cleaned_data else: return HttpResponseBadRequest("Invalid Request") user_count = 0 (is_cross_domain, domains_list) = get_domains_from_user_filters(domain, user_filters) for current_domain in domains_list: if user_type == MOBILE_USER_TYPE: user_count += count_mobile_users_by_filters(current_domain, user_filters) else: user_count += count_web_users_by_filters(current_domain, user_filters) user_count += count_invitations_by_filters(current_domain, user_filters) return JsonResponse({ 'count': user_count }) @require_can_edit_or_view_commcare_users @location_safe def download_commcare_users(request, domain): return download_users(request, domain, user_type=MOBILE_USER_TYPE) @login_and_domain_required def download_users(request, domain, user_type): if user_type not in [MOBILE_USER_TYPE, WEB_USER_TYPE]: raise AssertionError(f"Invalid user type for download_users: {user_type}") form = UserFilterForm(request.GET, domain=domain, couch_user=request.couch_user, user_type=user_type) if form.is_valid(): user_filters = form.cleaned_data else: view = FilteredCommCareUserDownload if user_type == MOBILE_USER_TYPE else FilteredWebUserDownload return HttpResponseRedirect(reverse(view, args=[domain]) + "?" + request.GET.urlencode()) download = DownloadBase() if form.cleaned_data['domains'] != [domain]: # if additional domains added for download track_workflow(request.couch_user.username, f'Domain filter used for {user_type} download') if form.cleaned_data['columns'] == UserFilterForm.USERNAMES_COLUMN_OPTION: if user_type != MOBILE_USER_TYPE: raise AssertionError("USERNAME_COLUMN_OPTION only available for mobile users") res = bulk_download_usernames_async.delay(domain, download.download_id, user_filters, owner_id=request.couch_user.get_id) else: res = bulk_download_users_async.delay(domain, download.download_id, user_filters, (user_type == WEB_USER_TYPE), owner_id=request.couch_user.get_id) download.set_task(res) if user_type == MOBILE_USER_TYPE: view = DownloadUsersStatusView else: from corehq.apps.users.views import DownloadWebUsersStatusView view = DownloadWebUsersStatusView return redirect(view.urlname, domain, download.download_id) @location_safe class CommCareUserConfirmAccountView(TemplateView, DomainViewMixin): template_name = "users/commcare_user_confirm_account.html" urlname = "commcare_user_confirm_account" strict_domain_fetching = True @toggles.any_toggle_enabled(toggles.TWO_STAGE_USER_PROVISIONING_BY_SMS, toggles.TWO_STAGE_USER_PROVISIONING) def dispatch(self, request, *args, **kwargs): return super(CommCareUserConfirmAccountView, self).dispatch(request, *args, **kwargs) @property @memoized def user_id(self): return self.kwargs.get('user_id') @property @memoized def user(self): return get_document_or_404(CommCareUser, self.domain, self.user_id) @property @memoized def form(self): if self.request.method == 'POST': return MobileWorkerAccountConfirmationForm(self.request.POST) else: return MobileWorkerAccountConfirmationForm(initial={ 'username': self.user.raw_username, 'full_name': self.user.full_name, 'email': self.user.email, }) def get_context_data(self, **kwargs): context = super(CommCareUserConfirmAccountView, self).get_context_data(**kwargs) context.update({ 'domain_name': self.domain_object.display_name(), 'user': self.user, 'form': self.form, 'button_label': _('Confirm Account') }) return context def post(self, request, *args, **kwargs): form = self.form if form.is_valid(): user = self.user user.email = form.cleaned_data['email'] full_name = form.cleaned_data['full_name'] user.first_name = full_name[0] user.last_name = full_name[1] user.confirm_account(password=self.form.cleaned_data['password']) messages.success(request, _( f'You have successfully confirmed the {user.raw_username} account. ' 'You can now login' )) if hasattr(self, 'send_success_sms'): self.send_success_sms() return HttpResponseRedirect('{}?username={}'.format( reverse('domain_login', args=[self.domain]), user.raw_username, )) # todo: process form data and activate the account return self.get(request, *args, **kwargs) @location_safe class CommCareUserConfirmAccountBySMSView(CommCareUserConfirmAccountView): urlname = "commcare_user_confirm_account_sms" one_day_in_seconds = 60 * 60 * 24 @property @memoized def user_invite_hash(self): return json.loads(b64_aes_decrypt(self.kwargs.get('user_invite_hash'))) @property @memoized def user_id(self): return self.user_invite_hash.get('user_id') @property @memoized def form(self): if self.request.method == 'POST': return MobileWorkerAccountConfirmationBySMSForm(self.request.POST) else: return MobileWorkerAccountConfirmationBySMSForm(initial={ 'username': self.user.raw_username, 'full_name': self.user.full_name, 'email': "", }) def get_context_data(self, **kwargs): context = super(CommCareUserConfirmAccountBySMSView, self).get_context_data(**kwargs) context.update({ 'invite_expired': self.is_invite_valid() is False, }) return context def send_success_sms(self): settings = SMSAccountConfirmationSettings.get_settings(self.user.domain) template_params = { 'name': self.user.full_name, 'domain': self.user.domain, 'username': self.user.raw_username, 'hq_name': settings.project_name } lang = guess_domain_language_for_sms(self.user.domain) with override(lang): text_content = render_to_string( "registration/mobile/mobile_worker_account_confirmation_success_sms.txt", template_params ) send_sms( domain=self.user.domain, contact=None, phone_number=self.user.default_phone_number, text=text_content ) def is_invite_valid(self): hours_elapsed = float(int(time.time()) - self.user_invite_hash.get('time')) / self.one_day_in_seconds settings_obj = SMSAccountConfirmationSettings.get_settings(self.user.domain) if hours_elapsed <= settings_obj.confirmation_link_expiry_time: return True return False
bsd-3-clause
4ad67705915de694d3262dff8cd1d921
38.953578
158
0.641783
3.821411
false
false
false
false
dimagi/commcare-hq
corehq/apps/reports/standard/deployments.py
1
33431
from collections import namedtuple from datetime import date, datetime, timedelta from django.contrib.humanize.templatetags.humanize import naturaltime from django.db.models import Q from django.urls import reverse from django.utils.functional import cached_property from django.utils.html import format_html from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy from couchdbkit import ResourceNotFound from memoized import memoized from couchexport.export import SCALAR_NEVER_WAS from dimagi.utils.dates import safe_strftime from dimagi.utils.parsing import string_to_utc_datetime from phonelog.models import UserErrorEntry from corehq import toggles from corehq.apps.app_manager.dbaccessors import ( get_app, get_brief_apps_in_domain, ) from corehq.apps.es import UserES, filters from corehq.apps.es.aggregations import DateHistogram from corehq.apps.hqwebapp.decorators import use_nvd3 from corehq.apps.locations.models import SQLLocation from corehq.apps.locations.permissions import location_safe from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader from corehq.apps.reports.exceptions import BadRequestError from corehq.apps.reports.filters.select import SelectApplicationFilter from corehq.apps.reports.filters.users import ExpandedMobileWorkerFilter from corehq.apps.reports.generic import ( GenericTabularReport, GetParamsMixin, PaginatedReportMixin, ) from corehq.apps.reports.standard import ( ProjectReport, ProjectReportParametersMixin, ) from corehq.apps.reports.util import format_datatables_data from corehq.apps.users.util import user_display_string from corehq.const import USER_DATE_FORMAT from corehq.util.quickcache import quickcache class DeploymentsReport(GenericTabularReport, ProjectReport, ProjectReportParametersMixin): """ Base class for all deployments reports """ @location_safe class ApplicationStatusReport(GetParamsMixin, PaginatedReportMixin, DeploymentsReport): name = gettext_lazy("Application Status") slug = "app_status" emailable = True exportable = True exportable_all = True ajax_pagination = True fields = [ 'corehq.apps.reports.filters.users.ExpandedMobileWorkerFilter', 'corehq.apps.reports.filters.select.SelectApplicationFilter' ] primary_sort_prop = None @property def _columns(self): selected_app_info = "selected app version {app_id}".format( app_id=self.selected_app_id ) if self.selected_app_id else "for last built app" return [ DataTablesColumn(_("Username"), prop_name='username.exact', sql_col='user_dim__username'), DataTablesColumn(_("Last Submission"), prop_name='reporting_metadata.last_submissions.submission_date', alt_prop_name='reporting_metadata.last_submission_for_user.submission_date', sql_col='last_form_submission_date'), DataTablesColumn(_("Last Sync"), prop_name='reporting_metadata.last_syncs.sync_date', alt_prop_name='reporting_metadata.last_sync_for_user.sync_date', sql_col='last_sync_log_date'), DataTablesColumn(_("Application"), help_text=_("The name of the application from the user's last request."), sortable=False), DataTablesColumn(_("Application Version"), help_text=_("The application version from the user's last request."), prop_name='reporting_metadata.last_builds.build_version', alt_prop_name='reporting_metadata.last_build_for_user.build_version', sql_col='last_form_app_build_version'), DataTablesColumn(_("CommCare Version"), help_text=_("""The CommCare version from the user's last request"""), prop_name='reporting_metadata.last_submissions.commcare_version', alt_prop_name='reporting_metadata.last_submission_for_user.commcare_version', sql_col='last_form_app_commcare_version'), DataTablesColumn(_("Number of unsent forms in user's phone"), help_text=_("The number of unsent forms in users' phones for {app_info}".format( app_info=selected_app_info )), sortable=False), ] @property def headers(self): columns = self._columns if self.show_build_profile: columns.append( DataTablesColumn(_("Build Profile"), help_text=_("The build profile from the user's last hearbeat request."), sortable=False) ) headers = DataTablesHeader(*columns) headers.custom_sort = [[1, 'desc']] return headers @cached_property def show_build_profile(self): return toggles.SHOW_BUILD_PROFILE_IN_APPLICATION_STATUS.enabled(self.domain) @property def default_sort(self): if self.selected_app_id: self.primary_sort_prop = 'reporting_metadata.last_submissions.submission_date' return { self.primary_sort_prop: { 'order': 'desc', 'nested_filter': { 'term': { self.sort_filter: self.selected_app_id } } } } else: self.primary_sort_prop = 'reporting_metadata.last_submission_for_user.submission_date' return {'reporting_metadata.last_submission_for_user.submission_date': 'desc'} @property def sort_base(self): return '.'.join(self.primary_sort_prop.split('.')[:2]) @property def sort_filter(self): return self.sort_base + '.app_id' def get_sorting_block(self): sort_prop_name = 'prop_name' if self.selected_app_id else 'alt_prop_name' res = [] #the NUMBER of cols sorting sort_cols = int(self.request.GET.get('iSortingCols', 0)) if sort_cols > 0: for x in range(sort_cols): col_key = 'iSortCol_%d' % x sort_dir = self.request.GET['sSortDir_%d' % x] col_id = int(self.request.GET[col_key]) col = self.headers.header[col_id] sort_prop = getattr(col, sort_prop_name) or col.prop_name if x == 0: self.primary_sort_prop = sort_prop if self.selected_app_id: sort_dict = { sort_prop: { "order": sort_dir, "nested_filter": { "term": { self.sort_filter: self.selected_app_id } } } } sort_prop_path = sort_prop.split('.') if sort_prop_path[-1] == 'exact': sort_prop_path.pop() sort_prop_path.pop() if sort_prop_path: sort_dict[sort_prop]['nested_path'] = '.'.join(sort_prop_path) else: sort_dict = {sort_prop: sort_dir} res.append(sort_dict) if len(res) == 0 and self.default_sort is not None: res.append(self.default_sort) return res @property @memoized def selected_app_id(self): return self.request_params.get(SelectApplicationFilter.slug, None) @quickcache(['app_id'], timeout=60 * 60) def _get_app_details(self, app_id): try: app = get_app(self.domain, app_id) except ResourceNotFound: return {} return { 'name': app.name, 'build_profiles': { profile_id: profile.name for profile_id, profile in app.build_profiles.items() } } def get_app_name(self, app_id): return self._get_app_details(app_id).get('name') def get_data_for_app(self, options, app_id): try: return list(filter(lambda option: option['app_id'] == app_id, options))[0] except IndexError: return {} @memoized def user_query(self, pagination=True): mobile_user_and_group_slugs = set( # Cater for old ReportConfigs self.request.GET.getlist('location_restricted_mobile_worker') + self.request.GET.getlist(ExpandedMobileWorkerFilter.slug) ) user_query = ExpandedMobileWorkerFilter.user_es_query( self.domain, mobile_user_and_group_slugs, self.request.couch_user, ) user_query = (user_query .set_sorting_block(self.get_sorting_block())) if pagination: user_query = (user_query .size(self.pagination.count) .start(self.pagination.start)) if self.selected_app_id: # adding nested filter for reporting_metadata.last_submissions.app_id # and reporting_metadata.last_syncs.app_id when app is selected last_submission_filter = filters.nested('reporting_metadata.last_submissions', filters.term('reporting_metadata.last_submissions.app_id', self.selected_app_id) ) last_sync_filter = filters.nested('reporting_metadata.last_syncs', filters.term("reporting_metadata.last_syncs.app_id", self.selected_app_id) ) user_query = user_query.OR(last_submission_filter, last_sync_filter ) return user_query def get_location_columns(self, grouped_ancestor_locs): from corehq.apps.locations.models import LocationType location_types = LocationType.objects.by_domain(self.domain) all_user_locations = grouped_ancestor_locs.values() all_user_loc_types = {loc.location_type_id for user_locs in all_user_locations for loc in user_locs} required_loc_columns = [loc_type for loc_type in location_types if loc_type.id in all_user_loc_types] return required_loc_columns def user_locations(self, ancestors, location_types): ancestors_by_type_id = {loc.location_type_id: loc.name for loc in ancestors} return [ ancestors_by_type_id.get(location_type.id, '---') for location_type in location_types ] def get_bulk_ancestors(self, location_ids): """ Returns the grouped ancestors for the location ids passed in the dictionary of following pattern {location_id_1: [self, parent, parent_of_parent,.,.,.,], location_id_2: [self, parent, parent_of_parent,.,.,.,], } :param domain: domain for which locations is to be pulled out :param location_ids: locations ids whose ancestors needs to be find :param kwargs: extra parameters :return: dict """ where = Q(domain=self.domain, location_id__in=location_ids) location_ancestors = SQLLocation.objects.get_ancestors(where) location_by_id = {location.location_id: location for location in location_ancestors} location_by_pk = {location.id: location for location in location_ancestors} grouped_location = {} for location_id in location_ids: location_parents = [] current_location = location_by_id[location_id].id if location_id in location_by_id else None while current_location is not None: location_parents.append(location_by_pk[current_location]) current_location = location_by_pk[current_location].parent_id grouped_location[location_id] = location_parents return grouped_location def include_location_data(self): toggle = toggles.LOCATION_COLUMNS_APP_STATUS_REPORT return ( ( toggle.enabled(self.request.domain, toggles.NAMESPACE_DOMAIN) and self.rendered_as in ['export'] ) ) def process_rows(self, users, fmt_for_export=False): rows = [] users = list(users) if self.include_location_data(): location_ids = {user['location_id'] for user in users if user['location_id']} grouped_ancestor_locs = self.get_bulk_ancestors(location_ids) self.required_loc_columns = self.get_location_columns(grouped_ancestor_locs) for user in users: last_build = last_seen = last_sub = last_sync = last_sync_date = app_name = commcare_version = None last_build_profile_name = device = device_app_meta = num_unsent_forms = None is_commcare_user = user.get('doc_type') == 'CommCareUser' build_version = _("Unknown") devices = user.get('devices', None) if devices: device = max(devices, key=lambda dev: dev['last_used']) reporting_metadata = user.get('reporting_metadata', {}) if self.selected_app_id: last_submissions = reporting_metadata.get('last_submissions') if last_submissions: last_sub = self.get_data_for_app(last_submissions, self.selected_app_id) last_syncs = reporting_metadata.get('last_syncs') if last_syncs: last_sync = self.get_data_for_app(last_syncs, self.selected_app_id) if last_sync is None: last_sync = self.get_data_for_app(last_syncs, None) last_builds = reporting_metadata.get('last_builds') if last_builds: last_build = self.get_data_for_app(last_builds, self.selected_app_id) if device and is_commcare_user: device_app_meta = self.get_data_for_app(device.get('app_meta'), self.selected_app_id) else: last_sub = reporting_metadata.get('last_submission_for_user', {}) last_sync = reporting_metadata.get('last_sync_for_user', {}) last_build = reporting_metadata.get('last_build_for_user', {}) if last_build.get('app_id') and device and device.get('app_meta'): device_app_meta = self.get_data_for_app(device.get('app_meta'), last_build.get('app_id')) if last_sub and last_sub.get('commcare_version'): commcare_version = _get_commcare_version(last_sub.get('commcare_version')) else: if device and device.get('commcare_version', None): commcare_version = _get_commcare_version(device['commcare_version']) if last_sub and last_sub.get('submission_date'): last_seen = string_to_utc_datetime(last_sub['submission_date']) if last_sync and last_sync.get('sync_date'): last_sync_date = string_to_utc_datetime(last_sync['sync_date']) if device_app_meta: num_unsent_forms = device_app_meta.get('num_unsent_forms') if last_build: build_version = last_build.get('build_version') or build_version if last_build.get('app_id'): app_name = self.get_app_name(last_build['app_id']) if self.show_build_profile: last_build_profile_id = last_build.get('build_profile_id') if last_build_profile_id: last_build_profile_name = _("Unknown") build_profiles = self._get_app_details(last_build['app_id']).get('build_profiles', {}) if last_build_profile_id in build_profiles: last_build_profile_name = build_profiles[last_build_profile_id] row_data = [ user_display_string(user.get('username', ''), user.get('first_name', ''), user.get('last_name', '')), _fmt_date(last_seen, fmt_for_export), _fmt_date(last_sync_date, fmt_for_export), app_name or "---", build_version, commcare_version or '---', num_unsent_forms if num_unsent_forms is not None else "---", ] if self.show_build_profile: row_data.append(last_build_profile_name) if self.include_location_data(): location_data = self.user_locations(grouped_ancestor_locs.get(user['location_id'], []), self.required_loc_columns) row_data = location_data + row_data rows.append(row_data) return rows def process_facts(self, app_status_facts, fmt_for_export=False): rows = [] for fact in app_status_facts: rows.append([ user_display_string(fact.user_dim.username, fact.user_dim.first_name, fact.user_dim.last_name), _fmt_date(fact.last_form_submission_date, fmt_for_export), _fmt_date(fact.last_sync_log_date, fmt_for_export), getattr(fact.app_dim, 'name', '---'), fact.last_form_app_build_version, fact.last_form_app_commcare_version ]) return rows def get_sql_sort(self): res = None #the NUMBER of cols sorting sort_cols = int(self.request.GET.get('iSortingCols', 0)) if sort_cols > 0: for x in range(sort_cols): col_key = 'iSortCol_%d' % x sort_dir = self.request.GET['sSortDir_%d' % x] col_id = int(self.request.GET[col_key]) col = self.headers.header[col_id] if col.sql_col is not None: res = col.sql_col if sort_dir not in ('desc', 'asc'): raise BadRequestError( ('unexcpected sort direction: {}. ' 'sort direction must be asc or desc'.format(sort_dir)) ) if sort_dir == 'desc': res = '-{}'.format(res) break if res is None: res = '-last_form_submission_date' return res @property def total_records(self): if self._total_records: return self._total_records else: return 0 @property def rows(self): users = self.user_query().run() self._total_records = users.total return self.process_rows(users.hits) def get_user_ids(self): mobile_user_and_group_slugs = set( # Cater for old ReportConfigs self.request.GET.getlist('location_restricted_mobile_worker') + self.request.GET.getlist(ExpandedMobileWorkerFilter.slug) ) user_ids = ExpandedMobileWorkerFilter.user_es_query( self.domain, mobile_user_and_group_slugs, self.request.couch_user, ).values_list('_id', flat=True) return user_ids @property def get_all_rows(self): users = self.user_query(False).scroll() self._total_records = self.user_query(False).count() return self.process_rows(users, True) @property def export_table(self): def _fmt_timestamp(timestamp): if timestamp is not None and timestamp >= 0: return safe_strftime(date.fromtimestamp(timestamp), USER_DATE_FORMAT) return SCALAR_NEVER_WAS result = super(ApplicationStatusReport, self).export_table table = list(result[0][1]) location_colums = [] if self.include_location_data(): location_colums = ['{} Name'.format(loc_col.name.title()) for loc_col in self.required_loc_columns] table[0] = location_colums + table[0] for row in table[1:]: # Last submission row[len(location_colums) + 1] = _fmt_timestamp(row[len(location_colums) + 1]) # Last sync row[len(location_colums) + 2] = _fmt_timestamp(row[len(location_colums) + 2]) result[0][1] = table return result def _get_commcare_version(app_version_info): commcare_version = ( 'CommCare {}'.format(app_version_info) if app_version_info else _("Unknown CommCare Version") ) return commcare_version def _choose_latest_version(*app_versions): """ Chooses the latest version from a list of AppVersion objects - choosing the first one passed in with the highest version number. """ usable_versions = [_f for _f in app_versions if _f] if usable_versions: return sorted(usable_versions, key=lambda v: v.build_version)[-1] def _get_sort_key(date): if not date: return -1 else: return int(date.strftime("%s")) def _fmt_date(date, include_sort_key=True): def _timedelta_class(delta): return _bootstrap_class(delta, timedelta(days=7), timedelta(days=3)) if not date: text = format_html('<span class="label label-default">{}</span>', _("Never")) else: text = format_html( '<span class="{cls}">{text}</span>', cls=_timedelta_class(datetime.utcnow() - date), text=_(_naturaltime_with_hover(date)), ) if include_sort_key: return format_datatables_data(text, _get_sort_key(date)) else: return text def _naturaltime_with_hover(date): return format_html('<span title="{}">{}</span>', date, naturaltime(date) or '---') def _bootstrap_class(obj, severe, warn): """ gets a bootstrap class for an object comparing to thresholds. assumes bigger is worse and default is good. """ if obj > severe: return "label label-danger" elif obj > warn: return "label label-warning" else: return "label label-success" class ApplicationErrorReport(GenericTabularReport, ProjectReport): name = gettext_lazy("Application Error Report") slug = "application_error" ajax_pagination = True sortable = False fields = ['corehq.apps.reports.filters.select.SelectApplicationFilter'] # Filter parameters to pull from the URL model_fields_to_url_params = [ ('app_id', SelectApplicationFilter.slug), ('version_number', 'version_number'), ] @classmethod def show_in_navigation(cls, domain=None, project=None, user=None): return user and toggles.APPLICATION_ERROR_REPORT.enabled(user.username) @property def shared_pagination_GET_params(self): shared_params = super(ApplicationErrorReport, self).shared_pagination_GET_params shared_params.extend([ {'name': param, 'value': self.request.GET.get(param, None)} for model_field, param in self.model_fields_to_url_params ]) return shared_params @property def headers(self): return DataTablesHeader( DataTablesColumn(_("User")), DataTablesColumn(_("Expression")), DataTablesColumn(_("Message")), DataTablesColumn(_("Session")), DataTablesColumn(_("Application")), DataTablesColumn(_("App version")), DataTablesColumn(_("Date")), ) @property @memoized def _queryset(self): qs = UserErrorEntry.objects.filter(domain=self.domain) for model_field, url_param in self.model_fields_to_url_params: value = self.request.GET.get(url_param, None) if value: qs = qs.filter(**{model_field: value}) return qs @property def total_records(self): return self._queryset.count() @property @memoized def _apps_by_id(self): def link(app): return '<a href="{}">{}</a>'.format( reverse('view_app', args=[self.domain, app.get_id]), app.name, ) return { app.get_id: link(app) for app in get_brief_apps_in_domain(self.domain) } def _ids_to_users(self, user_ids): users = (UserES() .domain(self.domain) .user_ids(user_ids) .values('_id', 'username', 'first_name', 'last_name')) return { u['_id']: user_display_string(u['username'], u['first_name'], u['last_name']) for u in users } @property def rows(self): start = self.pagination.start end = start + self.pagination.count errors = self._queryset.order_by('-date')[start:end] users = self._ids_to_users({e.user_id for e in errors if e.user_id}) for error in errors: yield [ users.get(error.user_id, error.user_id), error.expr, error.msg, error.session, self._apps_by_id.get(error.app_id, error.app_id), error.version_number, str(error.date), ] @location_safe class AggregateUserStatusReport(ProjectReport, ProjectReportParametersMixin): slug = 'aggregate_user_status' report_template_path = "reports/async/aggregate_user_status.html" name = gettext_lazy("Aggregate User Status") description = gettext_lazy("See the last activity of your project's users in aggregate.") fields = [ 'corehq.apps.reports.filters.users.ExpandedMobileWorkerFilter', ] exportable = False emailable = False @use_nvd3 def decorator_dispatcher(self, request, *args, **kwargs): super(AggregateUserStatusReport, self).decorator_dispatcher(request, *args, **kwargs) @memoized def user_query(self): # partially inspired by ApplicationStatusReport.user_query mobile_user_and_group_slugs = set( self.request.GET.getlist(ExpandedMobileWorkerFilter.slug) ) or set(['t__0']) # default to all mobile workers on initial load user_query = ExpandedMobileWorkerFilter.user_es_query( self.domain, mobile_user_and_group_slugs, self.request.couch_user, ) user_query = user_query.aggregations([ DateHistogram( 'last_submission', 'reporting_metadata.last_submission_for_user.submission_date', DateHistogram.Interval.DAY, ), DateHistogram( 'last_sync', 'reporting_metadata.last_sync_for_user.sync_date', DateHistogram.Interval.DAY, ) ]) return user_query @property def template_context(self): class SeriesData(namedtuple('SeriesData', 'id title chart_color bucket_series help')): """ Utility class containing everything needed to render the chart in a template. """ def get_chart_data_series(self): return { 'key': _('Count of Users'), 'values': self.bucket_series.data_series, 'color': self.chart_color, } def get_chart_percent_series(self): return { 'key': _('Percent of Users'), 'values': self.bucket_series.percent_series, 'color': self.chart_color, } def get_buckets(self): return self.bucket_series.get_summary_data() class BucketSeries(namedtuple('Bucket', 'data_series total_series total user_count')): @property @memoized def percent_series(self): return [ { 'series': 0, 'x': row['x'], 'y': self._pct(row['y'], self.user_count) } for row in self.total_series ] def get_summary_data(self): def _readable_pct_from_total(total_series, index): return '{0:.0f}%'.format(total_series[index - 1]['y']) return [ [_readable_pct_from_total(self.percent_series, 3), _('in the last 3 days')], [_readable_pct_from_total(self.percent_series, 7), _('in the last week')], [_readable_pct_from_total(self.percent_series, 30), _('in the last 30 days')], [_readable_pct_from_total(self.percent_series, 60), _('in the last 60 days')], ] @property def total_percent(self): return '{0:.0f}%'.format(self._pct(self.total, self.user_count)) @staticmethod def _pct(val, total): return (100. * float(val) / float(total)) if total else 0 query = self.user_query().run() aggregations = query.aggregations last_submission_buckets = aggregations[0].normalized_buckets last_sync_buckets = aggregations[1].normalized_buckets total_users = query.total def _buckets_to_series(buckets, user_count): # start with N days of empty data # add bucket info to the data series # add last bucket days_of_history = 60 vals = { i: 0 for i in range(days_of_history) } extra = total = running_total = 0 today = datetime.today().date() for bucket_val in buckets: bucket_date = date.fromisoformat(bucket_val['key']) delta_days = (today - bucket_date).days val = bucket_val['doc_count'] if delta_days in vals: vals[delta_days] += val else: extra += val total += val daily_series = [] running_total_series = [] for i in range(days_of_history): running_total += vals[i] daily_series.append( { 'series': 0, 'x': '{}'.format(today - timedelta(days=i)), 'y': vals[i] } ) running_total_series.append( { 'series': 0, 'x': '{}'.format(today - timedelta(days=i)), 'y': running_total } ) # catchall / last row daily_series.append( { 'series': 0, 'x': 'more than {} days ago'.format(days_of_history), 'y': extra, } ) running_total_series.append( { 'series': 0, 'x': 'more than {} days ago'.format(days_of_history), 'y': running_total + extra, } ) return BucketSeries(daily_series, running_total_series, total, user_count) submission_series = SeriesData( id='submission', title=_('Users who have Submitted'), chart_color='#004abf', bucket_series=_buckets_to_series(last_submission_buckets, total_users), help=_( "<strong>Aggregate Percents</strong> shows the percent of users who have submitted " "<em>since</em> a certain date.<br><br>" "<strong>Daily Counts</strong> shows the count of users whose <em>last submission was on</em> " "that particular day." ) ) sync_series = SeriesData( id='sync', title=_('Users who have Synced'), chart_color='#f58220', bucket_series=_buckets_to_series(last_sync_buckets, total_users), help=_( "<strong>Aggregate Percents</strong> shows the percent of users who have synced " "<em>since</em> a certain date.<br><br>" "<strong>Daily Counts</strong> shows the count of users whose <em>last sync was on</em> " "that particular day." ) ) context = super().template_context context.update({ 'submission_series': submission_series, 'sync_series': sync_series, 'total_users': total_users, }) return context
bsd-3-clause
0f90104a7a1a13cd1cf3e785a371f1ed
39.18149
111
0.549849
4.244128
false
false
false
false
dimagi/commcare-hq
corehq/apps/data_interfaces/migrations/0017_alter_domaincaserulerun.py
1
1475
# Generated by Django 1.11.11 on 2018-03-20 16:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('data_interfaces', '0016_createscheduleinstanceactiondefinition_specific_start_date'), ] operations = [ migrations.AddField( model_name='domaincaserulerun', name='dbs_completed', field=models.JSONField(default=list), ), migrations.AlterField( model_name='domaincaserulerun', name='cases_checked', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='domaincaserulerun', name='num_closes', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='domaincaserulerun', name='num_creates', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='domaincaserulerun', name='num_related_closes', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='domaincaserulerun', name='num_related_updates', field=models.IntegerField(default=0), ), migrations.AlterField( model_name='domaincaserulerun', name='num_updates', field=models.IntegerField(default=0), ), ]
bsd-3-clause
f0f91c9b82661677e4f23145a76ed727
29.729167
95
0.575593
4.483283
false
false
false
false
dimagi/commcare-hq
corehq/apps/registry/helper.py
1
4263
import itertools from operator import attrgetter from corehq.apps.registry.exceptions import RegistryNotFound, RegistryAccessException from corehq.apps.registry.models import DataRegistry from corehq.apps.registry.utils import RegistryPermissionCheck from corehq.form_processor.models import CommCareCase class DataRegistryHelper: def __init__(self, current_domain, registry_slug=None, registry=None): self.current_domain = current_domain assert any([registry_slug, registry]) if registry and registry_slug: assert registry.slug == registry_slug if registry: self._registry = registry self.registry_slug = registry.slug else: self.registry_slug = registry_slug self._registry = None @property def registry(self): if not self._registry: try: self._registry = DataRegistry.objects.accessible_to_domain( self.current_domain, self.registry_slug ).get() except DataRegistry.DoesNotExist: raise RegistryNotFound(self.registry_slug) return self._registry @property def visible_domains(self): return {self.current_domain} | self.registry.get_granted_domains(self.current_domain) @property def participating_domains(self): self.registry.check_ownership(self.current_domain) return self.registry.get_participating_domains() def log_data_access(self, user, domain, related_object, filters=None): self.registry.logger.data_accessed(user, domain, related_object, filters) def get_case(self, case_id, couch_user, accessing_object): """ :param accessing_object: object that is calling 'get_case'. See ``corehq.apps.registry.models.RegistryAuditHelper.data_accessed`` :return: """ case = CommCareCase.objects.get_case(case_id) self.check_data_access(couch_user, [case.type], case.domain) self.log_data_access(couch_user.get_django_user(), case.domain, accessing_object, filters={ "case_type": case.type, "case_id": case_id }) return case def get_multi_domain_case_hierarchy(self, couch_user, cases): """Get the combined case hierarchy for a list of cases that spans multiple domains""" all_cases = list(itertools.chain.from_iterable( self.get_case_hierarchy(domain, couch_user, list(domain_cases)) for domain, domain_cases in itertools.groupby(cases, key=attrgetter("domain")) )) return all_cases def get_case_hierarchy(self, domain, couch_user, cases): """Get the combined case hierarchy for the input cases""" from casexml.apps.phone.data_providers.case.livequery import get_case_hierarchy self.check_data_access(couch_user, [case.type for case in cases], domain) return get_case_hierarchy(domain, cases) def check_data_access(self, couch_user, case_types, case_domain=None): """Perform all checks for data access. Will raise a RegistryAccessException if access should be denied. """ for case_type in case_types: self._check_case_type_in_registry(case_type) self._check_user_has_access(couch_user, case_domain) if case_domain is not None: self._check_domain_is_visible(case_domain) def _check_user_has_access(self, couch_user, case_domain=None): if case_domain and self.current_domain == case_domain: # always allow access data in the current domain return checker = RegistryPermissionCheck(self.current_domain, couch_user) if not checker.can_view_registry_data(self.registry_slug): raise RegistryAccessException("User not permitted to access registry data") def _check_case_type_in_registry(self, case_type): if case_type not in self.registry.wrapped_schema.case_types: raise RegistryAccessException(f"'{case_type}' not available in registry") def _check_domain_is_visible(self, domain): if domain not in self.visible_domains: raise RegistryAccessException("Data not available in registry")
bsd-3-clause
196e159488ab1be466019685b3e23fc5
41.207921
99
0.664086
4.126815
false
false
false
false
onepercentclub/bluebottle
bluebottle/payouts/migrations/0003_auto_20160719_1315.py
1
12373
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-07-19 11:15 from __future__ import unicode_literals import bluebottle.utils.fields from decimal import Decimal from django.db import migrations import djmoney.models.fields class Migration(migrations.Migration): dependencies = [ ('payouts', '0002_auto_20160523_1525'), ] operations = [ migrations.AddField( model_name='organizationpayout', name='organization_fee_excl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='organization_fee_incl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='organization_fee_vat_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='other_costs_excl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='other_costs_incl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='other_costs_vat_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='payable_amount_excl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='payable_amount_incl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='payable_amount_vat_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='psp_fee_excl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='psp_fee_incl_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='organizationpayout', name='psp_fee_vat_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='projectpayout', name='amount_payable_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='projectpayout', name='amount_raised_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AddField( model_name='projectpayout', name='organization_fee_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AlterField( model_name='organizationpayout', name='organization_fee_excl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='organization fee excluding VAT'), ), migrations.AlterField( model_name='organizationpayout', name='organization_fee_incl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='organization fee including VAT'), ), migrations.AlterField( model_name='organizationpayout', name='organization_fee_vat', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='organization fee VAT'), ), migrations.AlterField( model_name='organizationpayout', name='other_costs_excl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.00'), default_currency=b'EUR', help_text='Set either this value or inclusive VAT, make sure recalculate afterwards.', max_digits=12, verbose_name='other costs excluding VAT'), ), migrations.AlterField( model_name='organizationpayout', name='other_costs_incl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.00'), default_currency=b'EUR', help_text='Set either this value or exclusive VAT, make sure recalculate afterwards.', max_digits=12, verbose_name='other costs including VAT'), ), migrations.AlterField( model_name='organizationpayout', name='other_costs_vat', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.00'), default_currency=b'EUR', max_digits=12, verbose_name='other costs VAT'), ), migrations.AlterField( model_name='organizationpayout', name='payable_amount_excl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='payable amount excluding VAT'), ), migrations.AlterField( model_name='organizationpayout', name='payable_amount_incl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='payable amount including VAT'), ), migrations.AlterField( model_name='organizationpayout', name='payable_amount_vat', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='payable amount VAT'), ), migrations.AlterField( model_name='organizationpayout', name='psp_fee_excl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='PSP fee excluding VAT'), ), migrations.AlterField( model_name='organizationpayout', name='psp_fee_incl', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='PSP fee including VAT'), ), migrations.AlterField( model_name='organizationpayout', name='psp_fee_vat', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12, verbose_name='PSP fee VAT'), ), migrations.AlterField( model_name='projectpayout', name='amount_payable', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', help_text='Payable amount; raised amount minus organization fee.', max_digits=12, verbose_name='amount payable'), ), migrations.AlterField( model_name='projectpayout', name='amount_raised', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', help_text='Amount raised when Payout was created or last recalculated.', max_digits=12, verbose_name='amount raised'), ), migrations.AlterField( model_name='projectpayout', name='organization_fee', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', help_text='Fee subtracted from amount raised for the organization.', max_digits=12, verbose_name='organization fee'), ), ]
bsd-3-clause
4783ef96ccdb0574f973e6fc2130645e
56.018433
139
0.497454
4.681423
false
false
false
false
dimagi/commcare-hq
corehq/apps/ota/migrations/0004_mobilerecoverymeasure.py
1
2420
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ota', '0003_add_serial_id_model'), ] operations = [ migrations.CreateModel( name='MobileRecoveryMeasure', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('measure', models.CharField(choices=[('app_reinstall_ota', 'Reinstall App, OTA'), ('app_reinstall_local', 'Reinstall App, Local'), ('app_update', 'Update App'), ('clear_data', 'Clear User Data'), ('cc_reinstall', 'CC Reinstall Needed'), ('cc_update', 'CC Update Needed')], help_text="<strong>Reinstall App, OTA:</strong> Reinstall the current CommCare app by triggering an OTA install<br/><strong>Reinstall App, Local:</strong> Reinstall the current CommCare app (by triggering an offline install with a default .ccz that's already on the device, and then doing an OTA update from there)<br/><strong>Update App:</strong> Update the current CommCare app<br/><strong>Clear User Data:</strong> Clear data for the app's last logged in user<br/><strong>CC Reinstall Needed:</strong> Notify the user that CommCare needs to be reinstalled<br/><strong>CC Update Needed:</strong> Notify the user that CommCare needs to be updated", max_length=255)), ('domain', models.CharField(max_length=255)), ('app_id', models.CharField(max_length=50)), ('cc_all_versions', models.BooleanField(default=True, verbose_name='All CommCare Versions')), ('cc_version_min', models.CharField(blank=True, max_length=255, verbose_name='Min CommCare Version')), ('cc_version_max', models.CharField(blank=True, max_length=255, verbose_name='Max CommCare Version')), ('app_all_versions', models.BooleanField(default=True, verbose_name='All App Versions')), ('app_version_min', models.IntegerField(blank=True, max_length=255, null=True, verbose_name='Min App Version')), ('app_version_max', models.IntegerField(blank=True, max_length=255, null=True, verbose_name='Max App Version')), ('created_on', models.DateTimeField(auto_now_add=True)), ('username', models.CharField(editable=False, max_length=255)), ('notes', models.TextField(blank=True)), ], ), ]
bsd-3-clause
b024ad43e0c3b39c2fee8ed0d68f042b
82.448276
957
0.653719
3.973727
false
false
false
false
onepercentclub/bluebottle
bluebottle/funding_stripe/states.py
1
3546
from django.utils.translation import gettext_lazy as _ from bluebottle.fsm.effects import RelatedTransitionEffect from bluebottle.fsm.state import Transition, State, EmptyState from bluebottle.fsm.state import register from bluebottle.funding.states import BasePaymentStateMachine, PayoutAccountStateMachine, BankAccountStateMachine from bluebottle.funding_stripe.models import StripePayment, StripeSourcePayment, StripePayoutAccount, ExternalAccount @register(StripePayment) class StripePaymentStateMachine(BasePaymentStateMachine): pass @register(StripeSourcePayment) class StripeSourcePaymentStateMachine(BasePaymentStateMachine): charged = State(_('charged'), 'charged') canceled = State(_('canceled'), 'canceled') disputed = State(_('disputed'), 'disputed') def has_charge_token(self): return bool(self.instance.charge_token) def is_not_refunded(self): return self.instance.status not in ['refunded', 'disputed'] authorize = Transition( [ BasePaymentStateMachine.new, charged ], BasePaymentStateMachine.pending, name=_('Authorize'), automatic=True, effects=[ RelatedTransitionEffect('donation', 'succeed') ] ) succeed = Transition( [ BasePaymentStateMachine.new, BasePaymentStateMachine.pending, charged ], BasePaymentStateMachine.succeeded, name=_('Succeed'), automatic=True, effects=[ RelatedTransitionEffect('donation', 'succeed') ] ) charge = Transition( BasePaymentStateMachine.new, charged, name=_('Charge'), automatic=True, conditions=[has_charge_token] ) cancel = Transition( BasePaymentStateMachine.new, canceled, name=_('Canceled'), automatic=True, effects=[ RelatedTransitionEffect('donation', 'fail') ] ) dispute = Transition( [ BasePaymentStateMachine.new, BasePaymentStateMachine.succeeded, ], disputed, name=_('Dispute'), automatic=True, effects=[ RelatedTransitionEffect('donation', 'refund') ] ) @register(StripePayoutAccount) class StripePayoutAccountStateMachine(PayoutAccountStateMachine): pass @register(ExternalAccount) class StripeBankAccountStateMachine(BankAccountStateMachine): def account_verified(self): """the related connect account is verified""" return self.instance.connect_account and self.instance.connect_account.status == 'verified' initiate = Transition( EmptyState(), BankAccountStateMachine.unverified, name=_("Initiate"), description=_("Bank account details are entered.") ) reject = Transition( [ BankAccountStateMachine.verified, BankAccountStateMachine.unverified, BankAccountStateMachine.incomplete], BankAccountStateMachine.rejected, name=_('Reject'), description=_("Reject bank account"), automatic=True ) verify = Transition( [ BankAccountStateMachine.rejected, BankAccountStateMachine.incomplete, BankAccountStateMachine.unverified ], BankAccountStateMachine.verified, name=_('Verify'), description=_("Verify that the bank account is complete."), automatic=True )
bsd-3-clause
5925f0d873514a8684c17603f436116d
27.142857
117
0.643824
4.798376
false
false
false
false
onepercentclub/bluebottle
bluebottle/token_auth/management/commands/generate_auth_token.py
1
1929
from builtins import input from optparse import make_option from django.core.management.base import BaseCommand from bluebottle.token_auth.auth.booking import generate_token class Command(BaseCommand): help = "Generate a authentication token" def __init__(self): self.option_list = self.option_list + ( make_option('--email', '-e', dest='email', default=None, help="Email to generate a token for."), make_option('--first-name', '-f', dest='first-name', default=None, help="Last name for the user."), make_option('--last-name', '-l', dest='last-name', default=None, help="First name for the user."), ) super(Command, self).__init__() def handle(self, *args, **options): if options.get('email'): email = options['email'] else: email = None while not email: email = eval(input("Enter email address: ")) if options.get('first-name'): first_name = options['first-name'] else: default = email.split('@')[0].title() first_name = eval(input("Enter first name ({0}): ".format(default))) or default if options.get('last-name'): last_name = options['last-name'] else: default = email.split('@')[1].split('.')[0].title() last_name = eval(input("Enter last name ({0}): ".format(default))) or default if options.get('username'): username = options['username'] else: default = email.split('@')[0] username = eval(input("Enter username ({0}): ".format(default))) or default token = generate_token(email=email, username=username, first_name=first_name, last_name=last_name) self.stdout.write('Token: {0}'.format(token))
bsd-3-clause
45301ce44a10fa23d0903b2a09070318
36.823529
91
0.548471
4.325112
false
false
false
false
dimagi/commcare-hq
corehq/apps/userreports/alembic_diffs.py
1
4624
from functools import partial import attr from alembic.migration import MigrationContext def get_migration_context(connection, table_names=None): opts = {'compare_type': True} if table_names: opts['include_name'] = partial(include_name, table_names) opts['include_object'] = partial(include_object, table_names) return MigrationContext.configure(connection, opts=opts) def include_name(tables_to_include, name, type_, parent_names): """Checks if the object should be included. This is called prior to object reflection and is only called for existing database objects""" return _include_table(tables_to_include, type_, name) def include_object(tables_to_include, object, name, type_, reflected, compare_to): """Checks if the object should be included. This runs after reflection and will also be called with new objects that are only in the metadata""" return _include_table(tables_to_include, type_, name) def _include_table(tables_to_include, type_, name): if type_ == "table": return name in tables_to_include return True def get_tables_to_rebuild(diffs): return {diff.table_name for diff in diffs if diff.type in DiffTypes.TYPES_FOR_REBUILD} def reformat_alembic_diffs(raw_diffs): """ See: http://alembic.readthedocs.io/en/latest/api/autogenerate.html :param raw_diffs: from alembic :return: list of ``SimpleDiff`` tuples """ diffs = [] def _simplify_diff(raw_diff): type_ = raw_diff[0] if type_ in DiffTypes.TABLE_TYPES: diffs.append( SimpleDiff(type_, raw_diff[1].name, None, raw_diff) ) elif type_ in DiffTypes.CONSTRAINT_TYPES: any_column = list(raw_diff[1].columns.values())[0] table_name = any_column.table.name diffs.append( SimpleDiff(type_, table_name, raw_diff[1].name, raw_diff) ) elif type_ in DiffTypes.MODIFY_TYPES: diffs.append( SimpleDiff(type_, raw_diff[2], raw_diff[3], raw_diff) ) elif type_ == DiffTypes.ADD_COLUMN and raw_diff[3].nullable: diffs.append( SimpleDiff(DiffTypes.ADD_NULLABLE_COLUMN, raw_diff[2], raw_diff[3].name, raw_diff) ) elif type_ in DiffTypes.COLUMN_TYPES: diffs.append( SimpleDiff(type_, raw_diff[2], raw_diff[3].name, raw_diff) ) elif type_ in DiffTypes.INDEX_TYPES: diffs.append(SimpleDiff(type_, diff[1].table.name, diff[1].name, raw_diff)) else: diffs.append(SimpleDiff(type_, None, None, None)) for diff in raw_diffs: if isinstance(diff, list): for d in diff: _simplify_diff(d) else: _simplify_diff(diff) return diffs class DiffTypes(object): ADD_TABLE = 'add_table' REMOVE_TABLE = 'remove_table' TABLE_TYPES = (ADD_TABLE, REMOVE_TABLE) ADD_COLUMN = 'add_column' REMOVE_COLUMN = 'remove_column' COLUMN_TYPES = (ADD_COLUMN, REMOVE_COLUMN) MODIFY_NULLABLE = 'modify_nullable' MODIFY_TYPE = 'modify_type' MODIFY_DEFAULT = 'modify_default' MODIFY_TYPES = (MODIFY_TYPE, MODIFY_DEFAULT, MODIFY_NULLABLE) ADD_CONSTRAINT = 'add_constraint' REMOVE_CONSTRAINT = 'remove_constraint' ADD_INDEX = 'add_index' REMOVE_INDEX = 'remove_index' INDEX_TYPES = (ADD_INDEX, REMOVE_INDEX) ADD_NULLABLE_COLUMN = 'add_nullable_column' MIGRATEABLE_TYPES = (ADD_NULLABLE_COLUMN,) + INDEX_TYPES CONSTRAINT_TYPES = (ADD_CONSTRAINT, REMOVE_CONSTRAINT) + INDEX_TYPES ALL = TABLE_TYPES + COLUMN_TYPES + MODIFY_TYPES + CONSTRAINT_TYPES TYPES_FOR_REBUILD = TABLE_TYPES + COLUMN_TYPES + (MODIFY_TYPE, MODIFY_NULLABLE) TYPES_FOR_MIGRATION = INDEX_TYPES + (ADD_NULLABLE_COLUMN,) @attr.s(frozen=True) class SimpleDiff(object): type = attr.ib() table_name = attr.ib() item_name = attr.ib() raw = attr.ib(cmp=False) def to_dict(self): return { 'type': self.type, 'item_name': self.item_name } @property def column(self): return self._item(3, DiffTypes.COLUMN_TYPES + (DiffTypes.ADD_NULLABLE_COLUMN,)) @property def index(self): return self._item(1, DiffTypes.INDEX_TYPES) @property def constraint(self): return self._item(1, DiffTypes.CONSTRAINT_TYPES) def _item(self, index, supported_types): if self.type not in supported_types: raise NotImplementedError return self.raw[index]
bsd-3-clause
50821bdfdc760c3612a415afb2312a8a
31.111111
98
0.63192
3.598444
false
false
false
false
dimagi/commcare-hq
corehq/messaging/management/commands/export_conditional_alerts.py
1
10853
from corehq.apps.data_interfaces.models import ( AutomaticUpdateRule, MatchPropertyDefinition, CreateScheduleInstanceActionDefinition, ) from corehq.messaging.scheduling.models import ( Schedule, AlertSchedule, TimedSchedule, TimedEvent, SMSContent, ) from corehq.messaging.scheduling.scheduling_partitioned.models import CaseScheduleInstanceMixin from django.core.management.base import BaseCommand, CommandError import copy import json import jsonobject SIMPLE_SMS_DAILY_SCHEDULE_WITH_TIME = 1 SIMPLE_SMS_ALERT_SCHEDULE = 2 class MatchPropertyCriterion(jsonobject.JsonObject): property_name = jsonobject.StringProperty() property_value = jsonobject.StringProperty() match_type = jsonobject.StringProperty() class SimpleSchedulingRule(jsonobject.JsonObject): name = jsonobject.StringProperty() case_type = jsonobject.StringProperty() criteria = jsonobject.ListProperty(MatchPropertyCriterion) recipients = jsonobject.ListProperty(jsonobject.ListProperty(jsonobject.StringProperty(required=False))) reset_case_property_name = jsonobject.StringProperty() start_date_case_property = jsonobject.StringProperty() specific_start_date = jsonobject.DateProperty() scheduler_module_info = jsonobject.ObjectProperty(CreateScheduleInstanceActionDefinition.SchedulerModuleInfo) class ExtraSchedulingOptions(jsonobject.JsonObject): active = jsonobject.BooleanProperty() include_descendant_locations = jsonobject.BooleanProperty() default_language_code = jsonobject.StringProperty() custom_metadata = jsonobject.DictProperty(str) use_utc_as_default_timezone = jsonobject.BooleanProperty() user_data_filter = jsonobject.DictProperty(jsonobject.ListProperty(str)) stop_date_case_property_name = jsonobject.StringProperty() class SimpleSMSDailyScheduleWithTime(jsonobject.JsonObject): schedule_type = SIMPLE_SMS_DAILY_SCHEDULE_WITH_TIME time = jsonobject.TimeProperty() message = jsonobject.DictProperty(str) total_iterations = jsonobject.IntegerProperty() start_offset = jsonobject.IntegerProperty() start_day_of_week = jsonobject.IntegerProperty() extra_options = jsonobject.ObjectProperty(ExtraSchedulingOptions) repeat_every = jsonobject.IntegerProperty() class SimpleSMSAlertSchedule(jsonobject.JsonObject): schedule_type = SIMPLE_SMS_ALERT_SCHEDULE message = jsonobject.DictProperty(str) extra_options = jsonobject.ObjectProperty(ExtraSchedulingOptions) class Command(BaseCommand): help = "Export conditional alerts to file." def add_arguments(self, parser): parser.add_argument( 'domain', help="The project space from which to export conditional alerts.", ) def get_json_rule(self, rule): json_rule = SimpleSchedulingRule( name=rule.name, case_type=rule.case_type, ) for criterion in rule.memoized_criteria: definition = criterion.definition if not isinstance(definition, MatchPropertyDefinition): raise CommandError( "Rule %s references currently unsupported criterion definition for export. " "Either add support to this script for unsupported criteria or exclude rule " "from export." % rule.pk ) json_rule.criteria.append(MatchPropertyCriterion( property_name=definition.property_name, property_value=definition.property_value, match_type=definition.match_type, )) if len(rule.memoized_actions) != 1: raise CommandError( "Expected exactly one action for rule %s. This is an unexpected configuration. " "Was this rule created with the UI?" % rule.pk ) action = rule.memoized_actions[0].definition if not isinstance(action, CreateScheduleInstanceActionDefinition): raise CommandError( "Expected CreateScheduleInstanceActionDefinition for rule %s. This is an unexpected " "configuration. Was this rule created with the UI?" % rule.pk ) for recipient_type, recipient_id in action.recipients: if recipient_type not in ( CaseScheduleInstanceMixin.RECIPIENT_TYPE_SELF, CaseScheduleInstanceMixin.RECIPIENT_TYPE_CASE_OWNER, CaseScheduleInstanceMixin.RECIPIENT_TYPE_LAST_SUBMITTING_USER, CaseScheduleInstanceMixin.RECIPIENT_TYPE_PARENT_CASE, CaseScheduleInstanceMixin.RECIPIENT_TYPE_CUSTOM, ): raise CommandError( "Unsupported recipient_type %s referenced in rule %s. That's probably because the " "recipient type references a specific object like a user or location whose id cannot " "be guaranteed to be the same in the imported project. This rule must be excluded " "from export" % (recipient_type, rule.pk) ) if action.get_scheduler_module_info().enabled: raise CommandError( "Scheduler module integration is not supported for export because it references " "a form whose unique id is not guaranteed to be the same in the imported project. Please " "exclude rule %s from export." % rule.pk ) json_rule.recipients = copy.deepcopy(action.recipients) json_rule.reset_case_property_name = action.reset_case_property_name json_rule.start_date_case_property = action.start_date_case_property json_rule.specific_start_date = action.specific_start_date json_rule.scheduler_module_info = CreateScheduleInstanceActionDefinition.SchedulerModuleInfo(enabled=False) return json_rule def get_json_scheduling_options(self, schedule): return ExtraSchedulingOptions( active=schedule.active, include_descendant_locations=schedule.include_descendant_locations, default_language_code=schedule.default_language_code, custom_metadata=copy.deepcopy(schedule.custom_metadata), use_utc_as_default_timezone=schedule.use_utc_as_default_timezone, user_data_filter=copy.deepcopy(schedule.user_data_filter), stop_date_case_property_name=schedule.stop_date_case_property_name, ) def get_json_timed_schedule(self, schedule): if schedule.ui_type != Schedule.UI_TYPE_DAILY: raise CommandError( "Only simple daily TimedSchedules are supported by this export script. Either exclude " "rules with other types of TimedSchedules from export or add support to this script " "for the missing schedule types." ) json_schedule = SimpleSMSDailyScheduleWithTime( total_iterations=schedule.total_iterations, start_offset=schedule.start_offset, start_day_of_week=schedule.start_day_of_week, repeat_every=schedule.repeat_every, extra_options=self.get_json_scheduling_options(schedule), ) event = schedule.memoized_events[0] if not isinstance(event, TimedEvent): raise CommandError( "Only TimedSchedules which use simple TimedEvents are supported by this export " "script. Either exclude rules with other types of TimedEvents from export or add " "support to this script for the missing use cases." ) json_schedule.time = event.time content = event.content if not isinstance(content, SMSContent): raise CommandError( "Only Schedules which send SMSContent are supported by this export script. " "Either exclude rules with other content types from export or add support " "to this script for the missing use cases." ) json_schedule.message = copy.deepcopy(content.message) return json_schedule def get_json_alert_schedule(self, schedule): if schedule.ui_type != Schedule.UI_TYPE_IMMEDIATE: raise CommandError( "Only simple immediate AlertSchedules are supported by this export script. Either exclude " "rules with other types of AlertSchedules from export or add support to this script " "for the missing schedule types." ) json_schedule = SimpleSMSAlertSchedule( extra_options=self.get_json_scheduling_options(schedule), ) event = schedule.memoized_events[0] content = event.content if not isinstance(content, SMSContent): raise CommandError( "Only Schedules which send SMSContent are supported by this export script. " "Either exclude rules with other content types from export or add support " "to this script for the missing use cases." ) json_schedule.message = copy.deepcopy(content.message) return json_schedule def handle(self, domain, **options): result = [] for rule in AutomaticUpdateRule.by_domain( domain, AutomaticUpdateRule.WORKFLOW_SCHEDULING, active_only=False, ): json_rule = self.get_json_rule(rule) action = rule.memoized_actions[0].definition if action.schedule.location_type_filter: raise CommandError( "Expected location_type_filter to be empty for rule %s. Location type filtering " "references primary keys of LocationType objects which aren't guaranteed to be " "the same in the imported project. This rule must be excluded from export." % rule.pk ) if isinstance(action.schedule, TimedSchedule): json_schedule = self.get_json_timed_schedule(action.schedule) elif isinstance(action.schedule, AlertSchedule): json_schedule = self.get_json_alert_schedule(action.schedule) else: raise CommandError( "Unexpected Schedule type for rule %s. Support must be added to this script for " "anything other than TimedSchedules or AlertSchedules." % rule.pk ) result.append(json.dumps({ 'rule': json_rule.to_json(), 'schedule': json_schedule.to_json(), })) with open('conditional_alerts_for_%s.txt' % domain, 'w', encoding='utf-8') as f: for line in result: f.write(line) f.write('\n') print("Done")
bsd-3-clause
186b395e4097c0ea50f61d45a9155e1e
42.06746
115
0.653552
4.59289
false
false
false
false
onepercentclub/bluebottle
bluebottle/utils/staticfiles_finders.py
2
1192
from django.utils._os import safe_join import os from django.conf import settings from django.contrib.staticfiles.finders import FileSystemFinder from bluebottle.clients.models import Client class TenantStaticFilesFinder(FileSystemFinder): def find(self, path, all=False): """ Looks for files in the client static directories. static/assets/greatbarier/images/logo.jpg will translate to MULTI_TENANT_DIR/greatbarier/static/images/logo.jpg """ tenants = Client.objects.all() tenant_dir = getattr(settings, 'MULTI_TENANT_DIR', None) if not tenant_dir: return [] for tenant in tenants: if "{0}/".format(tenant.client_name) in path: tenant_path = path.replace('{0}/'.format(tenant.client_name), '{0}/static/'.format( tenant.client_name)) local_path = safe_join(tenant_dir, tenant_path) if os.path.exists(local_path): if all: return [local_path] return local_path return []
bsd-3-clause
ce3499b3e2a0a979febdb8be6c652f86
35.121212
77
0.564597
4.382353
false
false
false
false
onepercentclub/bluebottle
bluebottle/statistics/admin.py
1
3331
from builtins import object from adminsortable.admin import SortableAdmin from django.contrib import admin from django import forms from django.db import connection from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ from parler.admin import TranslatableAdmin from parler.forms import TranslatableModelForm from polymorphic.admin import PolymorphicParentModelAdmin, PolymorphicChildModelAdmin from tenant_schemas.postgresql_backend.base import FakeTenant from bluebottle.initiatives.models import InitiativePlatformSettings from bluebottle.statistics.models import ( BaseStatistic, ManualStatistic, DatabaseStatistic, ImpactStatistic ) class StatisticsChildAdmin(PolymorphicChildModelAdmin): list_display = ('name', 'active') readonly_fields = ('icon_preview',) base_model = BaseStatistic def icon_preview(self, obj): if not obj.icon: icon = 'default' else: icon = obj.icon return format_html(u'<img src="/goodicons/impact/{}-impact.svg">', icon) class IconWidget(forms.RadioSelect): option_template_name = 'admin/impact/select_icon_option.html' template_name = 'admin/impact/select_icon.html' class ManualStatisticForm(TranslatableModelForm): class Meta(object): model = ManualStatistic widgets = { 'icon': IconWidget(), } fields = '__all__' @admin.register(ManualStatistic) class ManualStatisticChildAdmin(TranslatableAdmin, StatisticsChildAdmin): model = ManualStatistic form = ManualStatisticForm @admin.register(DatabaseStatistic) class DatabaseStatisticChildAdmin(TranslatableAdmin, StatisticsChildAdmin): model = DatabaseStatistic @admin.register(ImpactStatistic) class ImpactStatisticChildAdmin(StatisticsChildAdmin): model = ImpactStatistic @admin.register(BaseStatistic) class StatisticAdmin(SortableAdmin, PolymorphicParentModelAdmin): base_model = BaseStatistic list_display = ('name', 'statistics_type', 'active') list_editable = ('active', ) child_models = ( DatabaseStatistic, ManualStatistic, ImpactStatistic ) def statistics_type(self, obj): return obj.get_real_instance_class()._meta.verbose_name statistics_type.short_description = _('Type') def get_child_models(self): if not isinstance(connection.tenant, FakeTenant): if not InitiativePlatformSettings.load().enable_impact: return tuple(x for x in self.child_models if x != ImpactStatistic) return self.child_models # We need this because Django Polymorphic uses a calculated property to # override change_list_template instead of using get_changelist_template. # adminsortable tries to set that value and then fails. _change_list_template = 'adminsortable/change_list_with_sort_link.html' @property def change_list_template(self): return self._change_list_template @change_list_template.setter def change_list_template(self, value): self._change_list_template = value def name(self, obj): for child in self.child_models: try: return getattr(obj, child.__name__.lower()).name except child.DoesNotExist: pass return obj
bsd-3-clause
0d6de12b8778e4e0df963c639244289c
31.028846
85
0.715401
4.158552
false
false
false
false
dimagi/commcare-hq
corehq/ex-submodules/pillowtop/dao/django.py
1
1684
from django.core.exceptions import ObjectDoesNotExist from pillowtop.dao.exceptions import DocumentNotFoundError from pillowtop.dao.interface import DocumentStore class DjangoDocumentStore(DocumentStore): """ An implementation of the DocumentStore that uses the Django ORM. """ def __init__(self, model_class, doc_generator_fn=None, model_manager=None, id_field='pk'): self._model_manager = model_manager if model_manager is None: self._model_manager = model_class.objects self._model_class = model_class self._doc_generator_fn = doc_generator_fn if not doc_generator_fn: try: self._doc_generator_fn = model_class.to_json except AttributeError: raise ValueError('DjangoDocumentStore must be supplied with a doc_generator_fn argument') self._id_field = id_field self._in_query_filter = f'{id_field}__in' def get_document(self, doc_id): try: model = self._model_manager.get(**{self._id_field: doc_id}) return self._doc_generator_fn(model) except ObjectDoesNotExist: raise DocumentNotFoundError() def iter_document_ids(self): return self._model_manager.all().values_list(self._id_field, flat=True) def iter_documents(self, ids): from dimagi.utils.chunked import chunked for chunk in chunked(ids, 500): chunk = list([_f for _f in chunk if _f]) filters = { self._in_query_filter: chunk } for model in self._model_manager.filter(**filters): yield self._doc_generator_fn(model)
bsd-3-clause
fd49bba15fadec21e5aca529ceb5fd21
39.095238
105
0.626485
4.147783
false
false
false
false
dimagi/commcare-hq
corehq/apps/aggregate_ucrs/views.py
1
3680
from django.contrib import messages from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404 from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.translation import gettext_lazy from corehq import toggles from corehq.apps.aggregate_ucrs.models import AggregateTableDefinition from corehq.apps.aggregate_ucrs.tasks import populate_aggregate_table_data_task from corehq.apps.domain.decorators import ( login_and_domain_required, login_or_basic, ) from corehq.apps.userreports.util import get_indicator_adapter from corehq.apps.userreports.views import ( BaseUserConfigReportsView, export_sql_adapter_view, swallow_programming_errors, ) from corehq.apps.users.decorators import require_permission from corehq.apps.users.models import HqPermissions @method_decorator(toggles.AGGREGATE_UCRS.required_decorator(), name='dispatch') class BaseAggregateUCRView(BaseUserConfigReportsView): @property def table_id(self): return self.kwargs.get('table_id') @property def table_definition(self): return get_object_or_404( AggregateTableDefinition, domain=self.domain, table_id=self.table_id ) @property def page_url(self): return reverse(self.urlname, args=(self.domain, self.table_id)) @property def page_context(self): return { 'aggregate_table': self.table_definition, } class AggregateUCRView(BaseAggregateUCRView): template_name = 'aggregate_ucrs/view_aggregate_ucr.html' urlname = 'aggregate_ucr' page_title = gettext_lazy("View Aggregate UCR") class PreviewAggregateUCRView(BaseAggregateUCRView): urlname = 'preview_aggregate_ucr' template_name = 'aggregate_ucrs/preview_aggregate_ucr.html' page_title = gettext_lazy("Preview Aggregate UCR") @method_decorator(swallow_programming_errors) def dispatch(self, request, *args, **kwargs): return super(PreviewAggregateUCRView, self).dispatch(request, *args, **kwargs) @property def page_context(self): context = super(PreviewAggregateUCRView, self).page_context adapter = get_indicator_adapter(self.table_definition) q = adapter.get_query_object() context.update({ 'columns': q.column_descriptions, 'data': [list(row) for row in q[:20]], 'total_rows': q.count(), }) return context @login_or_basic @require_permission(HqPermissions.view_reports) @swallow_programming_errors def export_aggregate_ucr(request, domain, table_id): table_definition = get_object_or_404( AggregateTableDefinition, domain=domain, table_id=table_id ) aggregate_table_adapter = get_indicator_adapter(table_definition, load_source='export_aggregate_ucr') url = reverse('export_aggregate_ucr', args=[domain, table_definition.table_id]) return export_sql_adapter_view(request, domain, aggregate_table_adapter, url) @login_and_domain_required @toggles.AGGREGATE_UCRS.required_decorator() def rebuild_aggregate_ucr(request, domain, table_id): table_definition = get_object_or_404( AggregateTableDefinition, domain=domain, table_id=table_id ) aggregate_table_adapter = get_indicator_adapter(table_definition) aggregate_table_adapter.rebuild_table( initiated_by=request.user.username, source='rebuild_aggregate_ucr' ) populate_aggregate_table_data_task.delay(table_definition.id) messages.success(request, 'Table rebuild successfully started.') return HttpResponseRedirect(reverse(AggregateUCRView.urlname, args=[domain, table_id]))
bsd-3-clause
0f29cf618ea9e55589ee93c11b44aee3
35.078431
105
0.729076
3.705942
false
false
false
false
dimagi/commcare-hq
corehq/apps/domain/deletion.py
1
21411
import logging from datetime import date from django.apps import apps from django.conf import settings from django.contrib.auth.models import User from django.db import transaction from django.db.models import Q from field_audit.models import AuditAction from dimagi.utils.chunked import chunked from corehq.apps.accounting.models import Subscription from corehq.apps.accounting.utils import get_change_status from corehq.apps.domain.utils import silence_during_tests from corehq.apps.userreports.dbaccessors import ( delete_all_ucr_tables_for_domain, ) from corehq.apps.users.audit.change_messages import UserChangeMessage from corehq.apps.users.dbaccessors import get_all_commcare_users_by_domain from corehq.apps.users.util import SYSTEM_USER_ID, log_user_change from corehq.blobs import CODES, get_blob_db from corehq.blobs.models import BlobMeta from corehq.elastic import ESError from corehq.form_processor.models import CommCareCase, XFormInstance from corehq.sql_db.util import ( get_db_aliases_for_partitioned_query, paginate_query_across_partitioned_databases, estimate_partitioned_row_count, ) from corehq.util.log import with_progress_bar from settings import HQ_ACCOUNT_ROOT logger = logging.getLogger(__name__) class BaseDeletion(object): def __init__(self, app_label, models): self.app_label = app_label self.models = models def get_model_classes(self): model_classes = [] for model_name in self.models: if '.' in model_name: model_class = apps.get_model(model_name) else: model_class = apps.get_model(self.app_label, model_name) model_classes.append(model_class) return model_classes def is_app_installed(self): try: return bool(apps.get_app_config(self.app_label)) except LookupError: return False class CustomDeletion(BaseDeletion): def __init__(self, app_label, deletion_fn, models): super(CustomDeletion, self).__init__(app_label, models) self.deletion_fn = deletion_fn def execute(self, domain_name): if self.is_app_installed(): self.deletion_fn(domain_name) class ModelDeletion(BaseDeletion): def __init__(self, app_label, model_name, domain_filter_kwarg, extra_models=None, audit_action=None): """Deletes all records of an app model matching the provided domain filter. :param app_label: label of the app containing the model(s) :param model_name: name of the model in the app :param domain_filter_kwarg: name of the model field to filter by domain :param extra_models: (optional) a collection of other models in the same app which will be deleted along with ``model_name`` via cascaded deletion. The ``extra_models`` is used only for auditing purposes. :param audit_action: (optional) an audit action to be provided as a keyword argument when deleting records (e.g. ``<QuerySet>.delete(audit_action=audit_action)``). Necessary for models whose manager is an instance of ``field_audit.models.AuditingManager``. The default (``None``) results in ``<QuerySet>.delete()`` being called without parameters. """ models = extra_models or [] models.append(model_name) super(ModelDeletion, self).__init__(app_label, models) self.domain_filter_kwarg = domain_filter_kwarg self.model_name = model_name self.delete_kwargs = {} if audit_action is None else {"audit_action": audit_action} def get_model_class(self): return apps.get_model(self.app_label, self.model_name) def execute(self, domain_name): if not domain_name: # The Django orm will properly turn a None domain_name to a # IS NULL filter. We don't want to allow deleting records for # NULL domain names since they might have special meaning (like # in some of the SMS models). raise RuntimeError("Expected a valid domain name") if self.is_app_installed(): model = self.get_model_class() model.objects.filter(**{self.domain_filter_kwarg: domain_name}).delete(**self.delete_kwargs) class PartitionedModelDeletion(ModelDeletion): def execute(self, domain_name): if not self.is_app_installed(): return model = self.get_model_class() for db_name in get_db_aliases_for_partitioned_query(): model.objects.using(db_name).filter(**{self.domain_filter_kwarg: domain_name}).delete() class DjangoUserRelatedModelDeletion(ModelDeletion): def execute(self, domain_name): if not self.is_app_installed(): return model = self.get_model_class() filter_kwarg = f"{self.domain_filter_kwarg}__contains" total, counts = model.objects.filter(**{filter_kwarg: f"@{domain_name}.commcarehq.org"}).delete() logger.info("Deleted %s %s", total, self.model_name) logger.info(counts) def _delete_domain_backend_mappings(domain_name): model = apps.get_model('sms', 'SQLMobileBackendMapping') model.objects.filter(is_global=False, domain=domain_name).delete() def _delete_domain_backends(domain_name): model = apps.get_model('sms', 'SQLMobileBackend') model.objects.filter(is_global=False, domain=domain_name).delete() def _delete_web_user_membership(domain_name): from corehq.apps.users.models import WebUser active_web_users = WebUser.by_domain(domain_name) inactive_web_users = WebUser.by_domain(domain_name, is_active=False) for web_user in list(active_web_users) + list(inactive_web_users): web_user.delete_domain_membership(domain_name) if settings.UNIT_TESTING and not web_user.domain_memberships: web_user.delete(domain_name, deleted_by=None) else: web_user.save() _log_web_user_membership_removed(web_user, domain_name, __name__ + "._delete_web_user_membership") def _log_web_user_membership_removed(user, domain, via): log_user_change(by_domain=None, for_domain=domain, couch_user=user, changed_by_user=SYSTEM_USER_ID, changed_via=via, change_messages=UserChangeMessage.domain_removal(domain)) def _terminate_subscriptions(domain_name): today = date.today() with transaction.atomic(): current_subscription = Subscription.get_active_subscription_by_domain(domain_name) if current_subscription: current_subscription.date_end = today current_subscription.is_active = False current_subscription.save() current_subscription.transfer_credits() _, downgraded_privs, upgraded_privs = get_change_status(current_subscription.plan_version, None) current_subscription.subscriber.deactivate_subscription( downgraded_privileges=downgraded_privs, upgraded_privileges=upgraded_privs, old_subscription=current_subscription, new_subscription=None, ) Subscription.visible_objects.filter( Q(date_start__gt=today) | Q(date_start=today, is_active=False), subscriber__domain=domain_name, ).update(is_hidden_to_ops=True) def delete_all_cases(domain_name): logger.info('Deleting cases...') case_ids = iter_ids(CommCareCase, 'case_id', domain_name) for chunk in chunked(case_ids, 1000, list): CommCareCase.objects.hard_delete_cases(domain_name, chunk) logger.info('Deleting cases complete.') def delete_all_forms(domain_name): logger.info('Deleting forms...') form_ids = iter_ids(XFormInstance, 'form_id', domain_name) for chunk in chunked(form_ids, 1000, list): XFormInstance.objects.hard_delete_forms(domain_name, chunk) logger.info('Deleting forms complete.') def iter_ids(model_class, field, domain, chunk_size=1000): where = Q(domain=domain) rows = paginate_query_across_partitioned_databases( model_class, where, values=[field], load_source='delete_domain', query_size=chunk_size, ) with silence_during_tests() as stream: yield from with_progress_bar( (r[0] for r in rows), estimate_partitioned_row_count(model_class, where), prefix="", oneline="concise", stream=stream, ) def _delete_data_files(domain_name): get_blob_db().bulk_delete(metas=list(BlobMeta.objects.partitioned_query(domain_name).filter( parent_id=domain_name, type_code=CODES.data_file, ))) def _delete_sms_content_events_schedules(domain_name): models = [ 'SMSContent', 'EmailContent', 'SMSSurveyContent', 'IVRSurveyContent', 'SMSCallbackContent', 'CustomContent' ] filters = [ 'alertevent__schedule__domain', 'timedevent__schedule__domain', 'randomtimedevent__schedule__domain', 'casepropertytimedevent__schedule__domain' ] _delete_filtered_models('scheduling', models, [ Q(**{name: domain_name}) for name in filters ]) def _delete_django_users(domain_name): total, counts = User.objects.filter( username__contains=f"@{domain_name}.{HQ_ACCOUNT_ROOT}" ).delete() logger.info("Deleted %s Django users", total) logger.info(counts) def _delete_filtered_models(app_name, models, domain_filters): for model_name in models: model = apps.get_model(app_name, model_name) for q_filter in domain_filters: total, counts = model.objects.filter(q_filter).delete() if total: logger.info("Deleted %s", counts) def _delete_demo_user_restores(domain_name): from corehq.apps.ota.models import DemoUserRestore from corehq.apps.users.dbaccessors import get_practice_mode_mobile_workers try: users = get_practice_mode_mobile_workers(domain_name) except ESError: # Fallback in case of ES Error users = get_all_commcare_users_by_domain(domain_name) for user in users: if getattr(user, "demo_restore_id", None): try: DemoUserRestore.objects.get(id=user.demo_restore_id).delete() except DemoUserRestore.DoesNotExist: pass # We use raw queries instead of ORM because Django queryset delete needs to # fetch objects into memory to send signals and handle cascades. It makes deletion very slow # if we have a millions of rows in stock data tables. DOMAIN_DELETE_OPERATIONS = [ DjangoUserRelatedModelDeletion('otp_static', 'StaticDevice', 'user__username', ['StaticToken']), DjangoUserRelatedModelDeletion('otp_totp', 'TOTPDevice', 'user__username'), DjangoUserRelatedModelDeletion('two_factor', 'PhoneDevice', 'user__username'), DjangoUserRelatedModelDeletion('users', 'HQApiKey', 'user__username'), CustomDeletion('auth', _delete_django_users, ['User']), ModelDeletion('products', 'SQLProduct', 'domain'), ModelDeletion('locations', 'SQLLocation', 'domain'), ModelDeletion('locations', 'LocationType', 'domain'), ModelDeletion('domain', 'AllowedUCRExpressionSettings', 'domain'), ModelDeletion('domain_migration_flags', 'DomainMigrationProgress', 'domain'), ModelDeletion('sms', 'DailyOutboundSMSLimitReached', 'domain'), ModelDeletion('sms', 'SMS', 'domain'), ModelDeletion('sms', 'Email', 'domain'), ModelDeletion('sms', 'SQLLastReadMessage', 'domain'), ModelDeletion('sms', 'ExpectedCallback', 'domain'), ModelDeletion('ivr', 'Call', 'domain'), ModelDeletion('sms', 'Keyword', 'domain', ['KeywordAction']), ModelDeletion('sms', 'PhoneNumber', 'domain'), ModelDeletion('sms', 'MessagingSubEvent', 'parent__domain'), ModelDeletion('sms', 'MessagingEvent', 'domain'), ModelDeletion('sms', 'QueuedSMS', 'domain'), ModelDeletion('sms', 'PhoneBlacklist', 'domain'), CustomDeletion('sms', _delete_domain_backend_mappings, ['SQLMobileBackendMapping']), ModelDeletion('sms', 'MobileBackendInvitation', 'domain'), CustomDeletion('sms', _delete_domain_backends, ['SQLMobileBackend']), CustomDeletion('users', _delete_web_user_membership, []), CustomDeletion('accounting', _terminate_subscriptions, ['Subscription']), CustomDeletion('form_processor', delete_all_cases, ['CommCareCase']), CustomDeletion('form_processor', delete_all_forms, ['XFormInstance']), ModelDeletion('aggregate_ucrs', 'AggregateTableDefinition', 'domain', [ 'PrimaryColumn', 'SecondaryColumn', 'SecondaryTableDefinition', 'TimeAggregationDefinition', ]), ModelDeletion('app_manager', 'AppReleaseByLocation', 'domain'), ModelDeletion('app_manager', 'LatestEnabledBuildProfiles', 'domain'), ModelDeletion('app_manager', 'ResourceOverride', 'domain'), ModelDeletion('app_manager', 'GlobalAppConfig', 'domain'), ModelDeletion('app_manager', 'ApplicationReleaseLog', 'domain'), ModelDeletion('case_importer', 'CaseUploadRecord', 'domain', [ 'CaseUploadFileMeta', 'CaseUploadFormRecord' ]), ModelDeletion('case_search', 'CaseSearchConfig', 'domain'), ModelDeletion('case_search', 'FuzzyProperties', 'domain'), ModelDeletion('case_search', 'IgnorePatterns', 'domain'), ModelDeletion('cloudcare', 'ApplicationAccess', 'domain', ['SQLAppGroup']), ModelDeletion('commtrack', 'CommtrackConfig', 'domain', [ 'ActionConfig', 'AlertConfig', 'ConsumptionConfig', 'StockLevelsConfig', 'StockRestoreConfig', ]), ModelDeletion('consumption', 'DefaultConsumption', 'domain'), ModelDeletion('custom_data_fields', 'CustomDataFieldsDefinition', 'domain', [ 'CustomDataFieldsProfile', 'Field', ]), ModelDeletion('data_analytics', 'GIRRow', 'domain_name'), ModelDeletion('data_analytics', 'MALTRow', 'domain_name'), ModelDeletion('data_dictionary', 'CaseType', 'domain', [ 'CaseProperty', 'CasePropertyAllowedValue', 'fhir.FHIRResourceType', 'fhir.FHIRResourceProperty', ]), ModelDeletion('scheduling', 'MigratedReminder', 'rule__domain'), ModelDeletion('data_interfaces', 'ClosedParentDefinition', 'caserulecriteria__rule__domain'), ModelDeletion('data_interfaces', 'CustomMatchDefinition', 'caserulecriteria__rule__domain'), ModelDeletion('data_interfaces', 'MatchPropertyDefinition', 'caserulecriteria__rule__domain'), ModelDeletion('data_interfaces', 'LocationFilterDefinition', 'caserulecriteria__rule__domain'), ModelDeletion('data_interfaces', 'UCRFilterDefinition', 'caserulecriteria__rule__domain'), ModelDeletion('data_interfaces', 'CustomActionDefinition', 'caseruleaction__rule__domain'), ModelDeletion('data_interfaces', 'UpdateCaseDefinition', 'caseruleaction__rule__domain'), ModelDeletion('data_interfaces', 'CaseDuplicate', 'action__caseruleaction__rule__domain'), ModelDeletion('data_interfaces', 'CaseDeduplicationActionDefinition', 'caseruleaction__rule__domain'), ModelDeletion('data_interfaces', 'CreateScheduleInstanceActionDefinition', 'caseruleaction__rule__domain'), ModelDeletion('data_interfaces', 'CaseRuleAction', 'rule__domain'), ModelDeletion('data_interfaces', 'CaseRuleCriteria', 'rule__domain'), ModelDeletion('data_interfaces', 'CaseRuleSubmission', 'rule__domain'), ModelDeletion('data_interfaces', 'CaseRuleSubmission', 'domain'), # TODO ModelDeletion('data_interfaces', 'AutomaticUpdateRule', 'domain'), ModelDeletion('data_interfaces', 'DomainCaseRuleRun', 'domain'), ModelDeletion('integration', 'DialerSettings', 'domain'), ModelDeletion('integration', 'GaenOtpServerSettings', 'domain'), ModelDeletion('integration', 'HmacCalloutSettings', 'domain'), ModelDeletion('integration', 'SimprintsIntegration', 'domain'), ModelDeletion('linked_domain', 'DomainLink', 'linked_domain', ['DomainLinkHistory']), CustomDeletion('scheduling', _delete_sms_content_events_schedules, [ 'SMSContent', 'EmailContent', 'SMSSurveyContent', 'IVRSurveyContent', 'SMSCallbackContent', 'CustomContent' ]), ModelDeletion('scheduling', 'MigratedReminder', 'broadcast__domain'), ModelDeletion('scheduling', 'AlertEvent', 'schedule__domain'), ModelDeletion('scheduling', 'TimedEvent', 'schedule__domain'), ModelDeletion('scheduling', 'RandomTimedEvent', 'schedule__domain'), ModelDeletion('scheduling', 'CasePropertyTimedEvent', 'schedule__domain'), ModelDeletion('scheduling', 'AlertSchedule', 'domain'), ModelDeletion('scheduling', 'ScheduledBroadcast', 'domain'), ModelDeletion('scheduling', 'ImmediateBroadcast', 'domain'), ModelDeletion('scheduling', 'TimedSchedule', 'domain'), PartitionedModelDeletion('scheduling_partitioned', 'AlertScheduleInstance', 'domain'), PartitionedModelDeletion('scheduling_partitioned', 'CaseAlertScheduleInstance', 'domain'), PartitionedModelDeletion('scheduling_partitioned', 'CaseTimedScheduleInstance', 'domain'), PartitionedModelDeletion('scheduling_partitioned', 'TimedScheduleInstance', 'domain'), ModelDeletion('domain', 'TransferDomainRequest', 'domain'), ModelDeletion('export', 'EmailExportWhenDoneRequest', 'domain'), ModelDeletion('export', 'LedgerSectionEntry', 'domain'), ModelDeletion('export', 'IncrementalExport', 'domain', ['IncrementalExportCheckpoint']), CustomDeletion('export', _delete_data_files, []), ModelDeletion('locations', 'LocationFixtureConfiguration', 'domain'), ModelDeletion('ota', 'MobileRecoveryMeasure', 'domain'), ModelDeletion('ota', 'SerialIdBucket', 'domain'), ModelDeletion('ota', 'DeviceLogRequest', 'domain'), ModelDeletion('phone', 'SyncLogSQL', 'domain'), CustomDeletion('ota', _delete_demo_user_restores, ['DemoUserRestore']), ModelDeletion('phonelog', 'ForceCloseEntry', 'domain'), ModelDeletion('phonelog', 'UserErrorEntry', 'domain'), ModelDeletion('registration', 'RegistrationRequest', 'domain'), ModelDeletion('reminders', 'EmailUsage', 'domain'), ModelDeletion('registry', 'DataRegistry', 'domain', [ 'RegistryInvitation', 'RegistryGrant', 'RegistryAuditLog' ]), ModelDeletion('registry', 'RegistryGrant', 'from_domain'), ModelDeletion('registry', 'RegistryInvitation', 'domain'), ModelDeletion('reports', 'TableauServer', 'domain'), ModelDeletion('reports', 'TableauVisualization', 'domain'), ModelDeletion('reports', 'TableauConnectedApp', 'server__domain'), ModelDeletion('reports', 'TableauUser', 'server__domain'), ModelDeletion('reports', 'TableauGroup', 'server__domain'), ModelDeletion('smsforms', 'SQLXFormsSession', 'domain'), ModelDeletion('translations', 'TransifexOrganization', 'transifexproject__domain'), ModelDeletion('translations', 'SMSTranslations', 'domain'), ModelDeletion('translations', 'TransifexBlacklist', 'domain'), ModelDeletion('translations', 'TransifexProject', 'domain'), ModelDeletion( 'generic_inbound', 'ConfigurableAPI', 'domain', extra_models=["ConfigurableApiValidation", "RequestLog", "ProcessingAttempt"], audit_action=AuditAction.AUDIT ), ModelDeletion('userreports', 'AsyncIndicator', 'domain'), ModelDeletion('userreports', 'DataSourceActionLog', 'domain'), ModelDeletion('userreports', 'InvalidUCRData', 'domain'), ModelDeletion('userreports', 'ReportComparisonDiff', 'domain'), ModelDeletion('userreports', 'ReportComparisonException', 'domain'), ModelDeletion('userreports', 'ReportComparisonTiming', 'domain'), ModelDeletion('userreports', 'UCRExpression', 'domain'), ModelDeletion('users', 'DomainRequest', 'domain'), ModelDeletion('users', 'DeactivateMobileWorkerTrigger', 'domain'), ModelDeletion('users', 'Invitation', 'domain'), ModelDeletion('users', 'UserReportingMetadataStaging', 'domain'), ModelDeletion('users', 'UserRole', 'domain', [ 'RolePermission', 'RoleAssignableBy', 'Permission' ], audit_action=AuditAction.AUDIT), ModelDeletion('user_importer', 'UserUploadRecord', 'domain'), ModelDeletion('zapier', 'ZapierSubscription', 'domain'), ModelDeletion('dhis2', 'SQLDataValueMap', 'dataset_map__domain'), ModelDeletion('dhis2', 'SQLDataSetMap', 'domain'), ModelDeletion('motech', 'RequestLog', 'domain'), ModelDeletion('fhir', 'FHIRImportConfig', 'domain', [ 'FHIRImportResourceType', 'ResourceTypeRelationship', 'FHIRImportResourceProperty', ]), ModelDeletion('repeaters', 'SQLRepeater', 'domain'), ModelDeletion('motech', 'ConnectionSettings', 'domain'), ModelDeletion('repeaters', 'SQLRepeatRecord', 'domain'), ModelDeletion('repeaters', 'SQLRepeatRecordAttempt', 'repeat_record__domain'), ModelDeletion('couchforms', 'UnfinishedSubmissionStub', 'domain'), ModelDeletion('couchforms', 'UnfinishedArchiveStub', 'domain'), ModelDeletion('fixtures', 'LookupTable', 'domain'), CustomDeletion('ucr', delete_all_ucr_tables_for_domain, []), ModelDeletion('domain', 'OperatorCallLimitSettings', 'domain'), ModelDeletion('domain', 'SMSAccountConfirmationSettings', 'domain'), ] def apply_deletion_operations(domain_name): for op in DOMAIN_DELETE_OPERATIONS: op.execute(domain_name)
bsd-3-clause
8680c28ff2e9b76a3ff14fc9bf45de6c
46.369469
111
0.689365
3.832289
false
false
false
false
dimagi/commcare-hq
corehq/apps/hqadmin/management/commands/cchq_prbac_grandfather_privs.py
1
3867
from django.core.management.base import BaseCommand from corehq.apps.accounting.models import SoftwarePlanVersion from corehq.apps.accounting.utils import ensure_grants from corehq.privileges import MAX_PRIVILEGES class Command(BaseCommand): help = 'Grandfather privileges to all roles above a certain plan level and custom roles' def handle(self, privs, **kwargs): dry_run = kwargs.get('dry_run') verbose = kwargs.get('verbose') noinput = kwargs.get('noinput') skip_edition = kwargs.get('skip_edition') query = SoftwarePlanVersion.objects skipped_editions = [] if skip_edition: skipped_editions = skip_edition.split(',') query = query.exclude(plan__edition__in=skipped_editions) all_role_slugs = set( query.distinct('role__slug').values_list('role__slug', flat=True) ) all_plan_slugs = ( all_role_slugs - set(MAX_PRIVILEGES) - # no privileges should be in software plan roles, this is just a safeguard set(plan_slug.strip() for plan_slug in kwargs.get('skip', '').split(',')) ) # make sure that these roles are not attached to SoftwarePlanEditions # that they aren't meant to be attached to. e.g. thw pro_plan_v1 role # attached to a SoftwarePlanVersion under the Advanced edition. # see https://dimagi-dev.atlassian.net/browse/SAASP-10124 all_plan_slugs = [ plan_slug for plan_slug in all_plan_slugs if _get_role_edition(plan_slug) not in skipped_editions ] if not dry_run and not noinput and not _confirm('Are you sure you want to grant {} to {}?'.format( ', '.join(privs), ', '.join(all_plan_slugs), )): print('Aborting') return if not all(priv in MAX_PRIVILEGES for priv in privs): print('Not all specified privileges are valid: {}'.format(', '.join(privs))) return grants_to_privs = ((role_slug, privs) for role_slug in all_plan_slugs) ensure_grants(grants_to_privs, dry_run=dry_run, verbose=verbose) def add_arguments(self, parser): parser.add_argument( 'privs', nargs='+', ) parser.add_argument( '--dry-run', action='store_true', default=False, help='Do not actually modify the database, just verbosely log what would happen' ), parser.add_argument( '--noinput', action='store_true', default=False, help='Whether to skip confirmation dialogs' ), parser.add_argument( "-s", "--skip", dest="skip", default="", help="A comma separated list of plan roles to skip if any", ), parser.add_argument( "--skip-edition", dest="skip_edition", help="A comma separated list of plan editions to skip if any", ), parser.add_argument( "--verbose", action='store_false', dest="verbose", help="Verbose logging", default=True, ) def _confirm(msg): confirm_update = input(msg + ' [y/N] ') if not confirm_update: return False return confirm_update.lower() == 'y' def _get_role_edition(role_slug): all_editions = SoftwarePlanVersion.objects.filter( role__slug=role_slug).distinct( 'plan__edition').values_list('plan__edition', flat=True) if len(all_editions) == 1: return all_editions[0] def _count_edition(edition): return SoftwarePlanVersion.objects.filter( role__slug=role_slug, plan__edition=edition).count() return max(all_editions, key=_count_edition)
bsd-3-clause
ade984641cb1e667f7d4aa094a5b826b
33.526786
109
0.582622
3.886432
false
false
false
false
dimagi/commcare-hq
custom/samveg/case_importer/operations.py
1
1619
from datetime import datetime import pytz class BaseRowOperation(object): """ Perform an operation on each row of case upload. """ def __init__(self, **kwargs): """ Possible values in kwargs :param row_num: 1-based row number. Headers are in row zero. :param raw_row: Row dict. :param fields_to_update: Current set of fields to update :param import_context: import context available during import for extensions :param domain_name: name of the domain for which upload operation is done """ self.fields_to_update = kwargs.get("fields_to_update") self.error_messages = [] def run(self): raise NotImplementedError class AddCustomCaseProperties(BaseRowOperation): def run(self): """ :return: fields to update, list of errors """ self.fields_to_update['last_upload_change'] = str(_get_today_date()) self.fields_to_update['visit_type'] = self._get_visit_type() return self.fields_to_update, self.error_messages def _get_visit_type(self): from custom.samveg.case_importer.validators import _get_latest_call_value_and_number _, latest_call_number = _get_latest_call_value_and_number(self.fields_to_update) return { 'Call1': 'anc', 'Call2': 'hrp', 'Call3': 'childbirth', 'Call4': 'sncu', 'Call5': 'penta_3', 'Call6': 'opv_booster', }[f"Call{latest_call_number}"] def _get_today_date(): return datetime.now(pytz.timezone('Asia/Kolkata')).date()
bsd-3-clause
401087bd38cc68a52721072ecb6db03b
30.134615
92
0.609636
3.800469
false
true
false
false
dimagi/commcare-hq
corehq/apps/export/tests/test_incremental.py
1
9499
import uuid from datetime import datetime, timedelta from django.test import TestCase from couchexport.models import Format from pillowtop.es_utils import initialize_index_and_mapping import requests_mock from corehq.apps.export.models import ( CaseExportInstance, ExportColumn, ExportItem, PathNode, TableConfiguration, ) from corehq.apps.export.models.incremental import ( IncrementalExport, IncrementalExportStatus, _generate_incremental_export, _send_incremental_export, ) from corehq.apps.users.dbaccessors import delete_all_users from corehq.apps.locations.tests.util import delete_all_locations from corehq.apps.domain.shortcuts import create_domain from corehq.apps.es.tests.utils import es_test from corehq.apps.locations.models import SQLLocation from corehq.apps.locations.tests.util import setup_locations_and_types from corehq.apps.export.tests.util import DEFAULT_CASE_TYPE, new_case from corehq.apps.users.models import CommCareUser from corehq.elastic import get_es_new, send_to_elasticsearch from corehq.motech.const import BASIC_AUTH from corehq.motech.models import ConnectionSettings from corehq.pillows.mappings.case_mapping import CASE_INDEX_INFO from corehq.pillows.mappings.user_mapping import USER_INDEX_INFO from corehq.util.elastic import ensure_index_deleted from corehq.util.es.interface import ElasticsearchInterface from corehq.util.test_utils import trap_extra_setup @es_test class TestIncrementalExport(TestCase): @classmethod def setUpClass(cls): super().setUpClass() with trap_extra_setup(ConnectionError, msg="cannot connect to elasicsearch"): cls.es = get_es_new() initialize_index_and_mapping(cls.es, CASE_INDEX_INFO) initialize_index_and_mapping(cls.es, USER_INDEX_INFO) cls.domain = uuid.uuid4().hex create_domain(cls.domain) cls.now = datetime.utcnow() cases = [ new_case(domain=cls.domain, case_json={"foo": "apple", "bar": "banana"}, server_modified_on=cls.now - timedelta(hours=3)), new_case(domain=cls.domain, case_json={"foo": "orange", "bar": "pear"}, server_modified_on=cls.now - timedelta(hours=2)), ] for case in cases: send_to_elasticsearch('cases', case.to_json()) cls.es.indices.refresh(CASE_INDEX_INFO.index) @classmethod def tearDownClass(cls): ensure_index_deleted(CASE_INDEX_INFO.index) super().tearDownClass() def setUp(self): super().setUp() self.export_instance = CaseExportInstance( export_format=Format.UNZIPPED_CSV, domain=self.domain, case_type=DEFAULT_CASE_TYPE, tables=[TableConfiguration( label="My table", selected=True, path=[], columns=[ ExportColumn( label="Foo column", item=ExportItem( path=[PathNode(name="foo")] ), selected=True, ), ExportColumn( label="Bar column", item=ExportItem( path=[PathNode(name="bar")] ), selected=True, ) ] )] ) self.export_instance.save() connection_settings = ConnectionSettings.objects.create( domain=self.domain, name='test conn', url='http://commcarehq.org', auth_type=BASIC_AUTH, username='user@example.com', password='s3cr3t', ) self.incremental_export = IncrementalExport.objects.create( domain=self.domain, name='test_export', export_instance_id=self.export_instance.get_id, connection_settings=connection_settings, ) def tearDown(self): self.incremental_export.delete() self.export_instance.delete() super().tearDown() def _cleanup_case(self, case_id): def _clean(): interface = ElasticsearchInterface(self.es) interface.delete_doc(CASE_INDEX_INFO.alias, CASE_INDEX_INFO.type, case_id) self.es.indices.refresh(CASE_INDEX_INFO.index) return _clean def test_initial(self): checkpoint = _generate_incremental_export(self.incremental_export) data = checkpoint.get_blob().read().decode('utf-8-sig') expected = "Foo column,Bar column\r\napple,banana\r\norange,pear\r\n" self.assertEqual(data, expected) self.assertEqual(checkpoint.doc_count, 2) return checkpoint def test_initial_failure(self): # calling it twice should result in the same output since the checkpoints were not # marked as success self.test_initial() self.test_initial() def test_incremental_success(self): checkpoint = self.test_initial() checkpoint.status = IncrementalExportStatus.SUCCESS checkpoint.save() case = new_case( domain=self.domain, case_json={"foo": "peach", "bar": "plumb"}, server_modified_on=datetime.utcnow(), ) send_to_elasticsearch('cases', case.to_json()) self.es.indices.refresh(CASE_INDEX_INFO.index) self.addCleanup(self._cleanup_case(case.case_id)) checkpoint = _generate_incremental_export(self.incremental_export, last_doc_date=checkpoint.last_doc_date) data = checkpoint.get_blob().read().decode('utf-8-sig') expected = "Foo column,Bar column\r\npeach,plumb\r\n" self.assertEqual(data, expected) self.assertEqual(checkpoint.doc_count, 1) checkpoint = _generate_incremental_export( self.incremental_export, last_doc_date=self.now - timedelta(hours=2, minutes=1) ) data = checkpoint.get_blob().read().decode("utf-8-sig") expected = "Foo column,Bar column\r\norange,pear\r\npeach,plumb\r\n" self.assertEqual(data, expected) self.assertEqual(checkpoint.doc_count, 2) self.assertEqual(self.incremental_export.checkpoints.count(), 3) def test_sending_success(self): self._test_sending(200, IncrementalExportStatus.SUCCESS) def test_sending_fail(self): self._test_sending(401, IncrementalExportStatus.FAILURE) def _test_sending(self, status_code, expected_status): checkpoint = self.test_initial() with requests_mock.Mocker() as m: m.post('http://commcarehq.org/', status_code=status_code) _send_incremental_export(self.incremental_export, checkpoint) checkpoint.refresh_from_db() self.assertEqual(checkpoint.status, expected_status) self.assertEqual(checkpoint.request_log.response_status, status_code) def test_owner_filter(self): setup_locations_and_types( self.domain, ['state', 'health-department', 'team', 'sub-team'], [], [ ('State1', [ ('HealthDepartment1', [ ('Team1', [ ('SubTeam1', []), ('SubTeam2', []), ]), ('Team2', []), ]), ]) ] ) team1 = SQLLocation.objects.filter(domain=self.domain, name='Team1').first() health_department = SQLLocation.objects.filter(domain=self.domain, name='HealthDepartment1').first() self.addCleanup(delete_all_locations) user = CommCareUser.create(self.domain, 'm2', 'abc', None, None, location=team1) send_to_elasticsearch('users', user.to_json()) self.es.indices.refresh(USER_INDEX_INFO.index) self.addCleanup(delete_all_users) cases = [ new_case( domain=self.domain, case_json={"foo": "peach", "bar": "plumb"}, server_modified_on=datetime.utcnow() + timedelta(hours=-1), owner_id='123', ), new_case( domain=self.domain, case_json={"foo": "orange", "bar": "melon"}, server_modified_on=datetime.utcnow(), owner_id=user.user_id, # this user is part of the team1 location. ), new_case( domain=self.domain, case_json={"foo": "grape", "bar": "pineapple"}, server_modified_on=datetime.utcnow(), ), ] for case in cases: send_to_elasticsearch("cases", case.to_json()) self.addCleanup(self._cleanup_case(case.case_id)) self.es.indices.refresh(CASE_INDEX_INFO.index) self.export_instance.filters.show_project_data = False self.export_instance.filters.locations = [health_department.location_id] self.export_instance.filters.users = ['123'] self.export_instance.save() checkpoint = _generate_incremental_export(self.incremental_export) data = checkpoint.get_blob().read().decode("utf-8-sig") expected = "Foo column,Bar column\r\npeach,plumb\r\norange,melon\r\n" self.assertEqual(data, expected)
bsd-3-clause
485df924da605e1aee58ef18ab1e6f48
36.844622
114
0.594694
4.09087
false
true
false
false
onepercentclub/bluebottle
bluebottle/notifications/messages.py
1
7333
# -*- coding: utf-8 -*- from builtins import object from builtins import str from operator import attrgetter from functools import partial import logging from celery import shared_task from django.db import connection from django.core.cache import cache from django.contrib.admin.options import get_content_type_for_model from django.template import loader from django.utils.html import format_html from future.utils import python_2_unicode_compatible from bluebottle.clients import properties from bluebottle.notifications.models import Message, MessageTemplate from bluebottle.utils import translation from bluebottle.utils.utils import get_current_language, to_text logger = logging.getLogger(__name__) @python_2_unicode_compatible class TransitionMessage(object): """ Base model for sending message When the subject contains a variable it should be specified in context, e.g. subject = "Un update on {initiative_title}" context = {'initiative_title': 'title'} The value is taken as an attribute of the related object (self.obj). So in the example if the transition is on initiative it wil be `initiative.title`. """ subject = 'Status changed' template = 'messages/base' context = {} send_once = False delay = None def __reduce__(self): return (partial(self.__class__, self.obj, **self.options), ()) @property def task_id(self): return f'{self.__class__.__name__}-{self.obj.id}' def get_generic_context(self): language = get_current_language() context = { 'obj': self.obj, 'site': 'https://[site domain]', 'site_name': '[site name]', 'language': language, 'contact_email': '[platform manager email]', 'recipient_name': '[first name]', } for key, item in list(self.context.items()): try: context[key] = attrgetter(item)(self.obj) except AttributeError: logger.error(f'Missing attribute in message context: {item}') context[key] = item if 'context' in self.options: context.update(self.options['context']) return context @property def generic_subject(self): context = self.get_generic_context() return str(self.subject.format(**context)) @property def generic_content(self): context = self.get_generic_context() template = loader.get_template("mails/{}.html".format(self.template)) return template.render(context) @property def generic_content_html(self): context = self.get_generic_context() template = loader.get_template("mails/{}.html".format(self.template)) return template.render(context) @property def generic_content_text(self): return to_text.handle(self.generic_content_html) def get_content_html(self, recipient): context = self.get_context(recipient) template = loader.get_template("mails/{}.html".format(self.template)) return template.render(context) def get_content_text(self, recipient): return to_text.handle(self.get_content_html(recipient)) def get_context(self, recipient): from bluebottle.clients.utils import tenant_url, tenant_name context = { 'site': tenant_url(), 'site_name': tenant_name(), 'language': recipient.primary_language, 'contact_email': properties.CONTACT_EMAIL, 'recipient_name': recipient.first_name, 'first_name': recipient.first_name, 'action_link': getattr(self, 'action_link', None), 'action_title': getattr(self, 'action_title', None) } for key, item in list(self.context.items()): try: context[key] = attrgetter(item)(self.obj) except AttributeError: context[key] = None if 'context' in self.options: context.update(self.options['context']) return context def __init__(self, obj, **options): self.obj = obj self.options = options def __str__(self): return self.subject def get_template(self): return self.template def get_message_template(self): path = "{}.{}".format(self.__module__, self.__class__.__name__) return MessageTemplate.objects.filter(message=path).first() def already_send(self, recipient): return Message.objects.filter( template=self.get_template(), recipient=recipient, content_type=get_content_type_for_model(self.obj), object_id=self.obj.pk ).count() > 0 def get_messages(self, **base_context): custom_message = self.options.get('custom_message', '') custom_template = self.get_message_template() recipients = list(set(self.get_recipients())) for recipient in filter(None, recipients): with translation.override(recipient.primary_language): if self.send_once and self.already_send(recipient): continue context = self.get_context(recipient, **base_context) subject = str(self.subject.format(**context)) body_html = None body_txt = None if not custom_message and custom_template: custom_template.set_current_language(recipient.primary_language) try: subject = custom_template.subject.format(**context) body_html = format_html(custom_template.body_html, **context) body_txt = custom_template.body_txt.format(**context) except custom_template.DoesNotExist: # Translation for current language not set, use default. pass yield Message( template=self.get_template(), subject=subject, content_object=self.obj, recipient=recipient, body_html=body_html, body_txt=body_txt, bcc=self.get_bcc_addresses(), custom_message=custom_message ) def get_recipients(self): """the owner""" return [self.obj.owner] def get_bcc_addresses(self): return [] def compose_and_send(self, **base_context): for message in self.get_messages(**base_context): context = self.get_context(message.recipient, **base_context) message.save() message.send(**context) @property def is_delayed(self): return cache.get(self.task_id) def send_delayed(self): cache.set(self.task_id, True, self.delay) compose_and_send.apply_async( [self, connection.tenant], countdown=self.delay, task_id=self.task_id ) @shared_task def compose_and_send(message, tenant): from bluebottle.clients.utils import LocalTenant with LocalTenant(tenant, clear_tenant=True): try: message.compose_and_send() except Exception as e: print('!!!!!', e) logger.error(e)
bsd-3-clause
42822a44f48eb46b627f6c400a8c12e9
32.637615
86
0.597164
4.328808
false
false
false
false
onepercentclub/bluebottle
bluebottle/time_based/migrations/0035_auto_20201120_1318.py
1
1409
# -*- coding: utf-8 -*- # Generated by Django 1.11.17 on 2020-11-20 12:18 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('time_based', '0034_auto_20201120_1306'), ] operations = [ migrations.RenameModel( old_name='Duration', new_name='TimeContribution', ), migrations.AlterModelOptions( name='dateparticipant', options={'permissions': (('api_read_dateparticipant', 'Can view participant through the API'), ('api_add_dateparticipant', 'Can add participant through the API'), ('api_change_dateparticipant', 'Can change participant through the API'), ('api_delete_dateparticipant', 'Can delete participant through the API'), ('api_read_own_dateparticipant', 'Can view own participant through the API'), ('api_add_own_dateparticipant', 'Can add own participant through the API'), ('api_change_own_dateparticipant', 'Can change own participant through the API'), ('api_delete_own_dateparticipant', 'Can delete own participant through the API')), 'verbose_name': 'Participant on a date', 'verbose_name_plural': 'Participants on a date'}, ), migrations.AlterModelOptions( name='timecontribution', options={'verbose_name': 'Contribution', 'verbose_name_plural': 'Contributions'}, ), ]
bsd-3-clause
6a4920e9a3949fd6e7840429844797cd
51.185185
732
0.669979
4.131965
false
false
false
false
onepercentclub/bluebottle
bluebottle/deeds/admin.py
1
2817
from django.contrib import admin from django.urls import reverse from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ from django_admin_inline_paginator.admin import TabularInlinePaginated from django_summernote.widgets import SummernoteWidget from bluebottle.activities.admin import ( ActivityChildAdmin, ContributorChildAdmin, ActivityForm, TeamInline ) from bluebottle.deeds.models import Deed, DeedParticipant from bluebottle.utils.admin import export_as_csv_action class DeedAdminForm(ActivityForm): class Meta(object): model = Deed fields = '__all__' widgets = { 'description': SummernoteWidget(attrs={'height': 400}) } @admin.register(DeedParticipant) class DeedParticipantAdmin(ContributorChildAdmin): readonly_fields = ['created'] raw_id_fields = ['user', 'activity'] fields = ['activity', 'user', 'status', 'states'] + readonly_fields list_display = ['__str__', 'activity_link', 'status'] class DeedParticipantInline(TabularInlinePaginated): model = DeedParticipant per_page = 20 ordering = ['-created'] raw_id_fields = ['user'] readonly_fields = ['edit', 'created', 'status'] fields = ['edit', 'user', 'created', 'status'] extra = 0 def edit(self, obj): url = reverse('admin:deeds_deedparticipant_change', args=(obj.id,)) return format_html('<a href="{}">{}</a>', url, _('Edit participant')) edit.short_description = _('Edit participant') @admin.register(Deed) class DeedAdmin(ActivityChildAdmin): base_model = Deed form = DeedAdminForm inlines = (TeamInline, DeedParticipantInline,) + ActivityChildAdmin.inlines list_filter = ['status'] search_fields = ['title', 'description'] readonly_fields = ActivityChildAdmin.readonly_fields + ['team_activity'] list_display = ActivityChildAdmin.list_display + [ 'start', 'end', 'enable_impact', 'target', 'participant_count', ] def participant_count(self, obj): return obj.participants.count() participant_count.short_description = _('Participants') detail_fields = ActivityChildAdmin.detail_fields + ( 'start', 'end', 'enable_impact', 'target', ) export_as_csv_fields = ( ('title', 'Title'), ('description', 'Description'), ('status', 'Status'), ('created', 'Created'), ('initiative__title', 'Initiative'), ('registration_deadline', 'Registration Deadline'), ('owner__full_name', 'Owner'), ('owner__email', 'Email'), ('office_location', 'Office Location'), ('start', 'Start'), ('end', 'End'), ) actions = [export_as_csv_action(fields=export_as_csv_fields)]
bsd-3-clause
ce91af20daf0b1a489c2029fbd3515c1
30.651685
79
0.642173
3.880165
false
false
false
false
onepercentclub/bluebottle
bluebottle/test/factory_models/cms.py
1
2384
from builtins import object from datetime import timedelta import factory from django.utils.timezone import now from bluebottle.cms.models import ( ResultPage, HomePage, Stat, Quote, SiteLinks, LinkGroup, Link, LinkPermission, Step, ContentLink, Greeting ) from bluebottle.slides.models import Slide from bluebottle.test.factory_models.utils import LanguageFactory class ResultPageFactory(factory.DjangoModelFactory): class Meta(object): model = ResultPage title = factory.Sequence(lambda n: 'Result Page Title {0}'.format(n)) slug = factory.Sequence(lambda n: 'slug-{0}'.format(n)) description = factory.Sequence(lambda n: 'Results description {0}'.format(n)) start_date = now() - timedelta(days=300) end_date = now() + timedelta(days=65) class HomePageFactory(factory.DjangoModelFactory): class Meta(object): model = HomePage class StatFactory(factory.DjangoModelFactory): class Meta(object): model = Stat type = 'manual' value = 500 class QuoteFactory(factory.DjangoModelFactory): class Meta(object): model = Quote name = factory.Sequence(lambda n: 'Name {}'.format(n)) quote = factory.Sequence(lambda n: 'Quote {}'.format(n)) class ContentLinkFactory(factory.DjangoModelFactory): class Meta(object): model = ContentLink class SlideFactory(factory.DjangoModelFactory): class Meta(object): model = Slide class StepFactory(factory.DjangoModelFactory): class Meta(object): model = Step class GreetingFactory(factory.DjangoModelFactory): class Meta(object): model = Greeting class SiteLinksFactory(factory.DjangoModelFactory): class Meta(object): model = SiteLinks language = factory.SubFactory(LanguageFactory) class LinkGroupFactory(factory.DjangoModelFactory): class Meta(object): model = LinkGroup django_get_or_create = ('name',) site_links = factory.SubFactory(SiteLinksFactory) name = factory.Sequence(lambda n: 'Link Group {}'.format(n)) class LinkFactory(factory.DjangoModelFactory): class Meta(object): model = Link link_group = factory.SubFactory(LinkGroupFactory) title = factory.Sequence(lambda n: 'Title {}'.format(n)) class LinkPermissionFactory(factory.DjangoModelFactory): class Meta(object): model = LinkPermission
bsd-3-clause
51d16eb8e159180a1ef0fafdfb6da1c6
24.361702
81
0.709312
4.027027
false
false
false
false
onepercentclub/bluebottle
bluebottle/time_based/migrations/0027_auto_20201110_1613.py
1
1711
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-05-24 09:59 from __future__ import unicode_literals from django.db import migrations, connection from bluebottle.utils.utils import update_group_permissions from bluebottle.clients import properties from bluebottle.clients.models import Client from bluebottle.clients.utils import LocalTenant def add_group_permissions(apps, schema_editor): tenant = Client.objects.get(schema_name=connection.tenant.schema_name) with LocalTenant(tenant): group_perms = { 'Staff': { 'perms': ( 'add_dateactivity', 'change_dateactivity', 'delete_dateactivity', 'add_periodactivity', 'change_periodactivity', 'delete_periodactivity', ) }, 'Anonymous': { 'perms': ( 'api_read_dateactivity', 'api_read_periodactivity', ) if not properties.CLOSED_SITE else () }, 'Authenticated': { 'perms': ( 'api_read_dateactivity', 'api_add_own_dateactivity', 'api_change_own_dateactivity', 'api_delete_own_dateactivity', 'api_read_periodactivity', 'api_add_own_periodactivity', 'api_change_own_periodactivity', 'api_delete_own_periodactivity', ) } } update_group_permissions('time_based', group_perms, apps) class Migration(migrations.Migration): dependencies = [ ('time_based', '0026_auto_20201110_1558'), ] operations = [ migrations.RunPython( add_group_permissions, migrations.RunPython.noop ) ]
bsd-3-clause
eb77b23afc23d09c0cfda20d8fd53542
31.903846
142
0.58796
4.214286
false
false
false
false
dimagi/commcare-hq
corehq/messaging/pillow.py
1
3336
from datetime import datetime import attr from corehq.apps.change_feed.consumer.feed import KafkaChangeFeed, KafkaCheckpointEventHandler from corehq.apps.change_feed.topics import CASE_TOPICS from corehq.apps.data_interfaces.models import AutomaticUpdateRule from corehq.form_processor.exceptions import CaseNotFound from corehq.form_processor.models import CommCareCase from corehq.messaging.tasks import sync_case_for_messaging from corehq.pillows.base import is_couch_change_for_sql_domain from pillowtop.checkpoints.manager import KafkaPillowCheckpoint from pillowtop.const import DEFAULT_PROCESSOR_CHUNK_SIZE from pillowtop.pillow.interface import ConstructedPillow from pillowtop.processors import BulkPillowProcessor @attr.s class CaseRules(object): date_loaded = attr.ib() by_case_type = attr.ib() def expired(self): return (datetime.utcnow() - self.date_loaded).total_seconds() > 30 * 60 class CaseMessagingSyncProcessor(BulkPillowProcessor): """ Reads from: - Case data source - Update Rules Writes to: - PhoneNumber - Runs rules for SMS (can be many different things) """ def __init__(self): self.rules_by_domain = {} def _get_rules(self, domain, case_type): domain_rules = self.rules_by_domain.get(domain) if not domain_rules or domain_rules.expired(): rules = AutomaticUpdateRule.by_domain_cached(domain, AutomaticUpdateRule.WORKFLOW_SCHEDULING) domain_rules = CaseRules( datetime.utcnow(), AutomaticUpdateRule.organize_rules_by_case_type(rules) ) self.rules_by_domain[domain] = domain_rules return domain_rules.by_case_type.get(case_type, []) def process_change(self, change): if is_couch_change_for_sql_domain(change): return sync_case_for_messaging(change.metadata.domain, change.id, self._get_rules) def process_changes_chunk(self, changes_chunk): errors = [] for change in changes_chunk: try: self.process_change(change) except Exception as e: errors.append((change, e)) return [], errors def get_case_messaging_sync_pillow(pillow_id='case_messaging_sync_pillow', topics=None, num_processes=1, process_num=0, processor_chunk_size=DEFAULT_PROCESSOR_CHUNK_SIZE, **kwargs): """Pillow for synchronizing messaging data with case data. Processors: - :py:class:`corehq.messaging.pillow.CaseMessagingSyncProcessor` """ if topics: assert set(topics).issubset(CASE_TOPICS), set(topics) - set(CASE_TOPICS) topics = topics or CASE_TOPICS change_feed = KafkaChangeFeed( topics, client_id=pillow_id, num_processes=num_processes, process_num=process_num ) checkpoint = KafkaPillowCheckpoint(pillow_id, topics) event_handler = KafkaCheckpointEventHandler( checkpoint=checkpoint, checkpoint_frequency=1000, change_feed=change_feed, ) return ConstructedPillow( name=pillow_id, change_feed=change_feed, checkpoint=checkpoint, change_processed_event_handler=event_handler, processor=[CaseMessagingSyncProcessor()], processor_chunk_size=processor_chunk_size )
bsd-3-clause
c36439d11db809fb84629942c957c896
35.659341
105
0.686151
3.731544
false
false
false
false
onepercentclub/bluebottle
bluebottle/news/serializers.py
1
1250
from builtins import object from fluent_contents.rendering import render_placeholder from django.utils.safestring import mark_safe from rest_framework import serializers from bluebottle.bluebottle_drf2.serializers import SorlImageField from bluebottle.members.serializers import UserPreviewSerializer from .models import NewsItem class NewsItemContentsField(serializers.Field): def to_representation(self, obj): request = self.context.get('request', None) contents_html = mark_safe(render_placeholder(request, obj).html) return contents_html class NewsItemSerializer(serializers.ModelSerializer): id = serializers.CharField(source='slug') body = NewsItemContentsField(source='contents') main_image = SorlImageField('800x400') author = UserPreviewSerializer() class Meta(object): model = NewsItem fields = ('id', 'title', 'body', 'main_image', 'author', 'publication_date', 'allow_comments', 'language', 'main_image') class NewsItemPreviewSerializer(serializers.ModelSerializer): id = serializers.CharField(source='slug') class Meta(object): model = NewsItem fields = ('id', 'title', 'publication_date', 'language')
bsd-3-clause
641dde6b9c70d91992df66d456da4de6
31.894737
72
0.7136
4.251701
false
false
false
false
dimagi/commcare-hq
corehq/apps/mobile_auth/xml.py
1
3016
""" This file contains the spec for the XML for mobile auth (from https://github.com/dimagi/commcare/wiki/CentralAuthAPI) <!-- Exactly one. The block of auth key records.--> <!-- @domain: Exactly one. The client should only accept keys from domains that match the request --> <!-- @issued: Exactly one. An ISO8601 timestamp from the server which denotes the date and time that the key requests were processed. This is the value that should be provided as the {{{last_issued}}} parameter to future requests. --> <auth_keys domain="" issued=""> <!-- At Least One: A record for a key that the authenticating user has access to --> <!-- @valid: Exactly one - The first date on which this key should be trusted --> <!-- @expires: At Most one - A date on which the key was supplanted. If expires is not present, the phone will assume that it is currently valid --> <key_record valid="" expires=""> <!-- Exactly One: A unique ID for this key. The same key record can be issued to multiple users (for superuser functions, etc). --> <!-- @title: At most one. An optional description of the sandbox, to allow differentiating between different datastores --> <uuid title=""/> <!-- Exactly One: The key content. Should be Base64 Encoded --> <!-- @type: Exactly one. The type of key being shared. Currently only AES256 is supported as either (AES, AES256) --> <key type=""/> </key_record> </auth_keys> """ from eulxml.xmlmap import ( DateTimeField, NodeField, NodeListField, StringField, XmlObject, ) def CustomDateTimeField(*args, **kwargs): # As of at least CommCare 2.20, the phone does not parse microseconds # in this particular handler (though it does everywhere else). # For now, we're going to continue sending down without microseconds return DateTimeField(format='%Y-%m-%dT%H:%M:%SZ', *args, **kwargs) class KeyRecord(XmlObject): ROOT_NAME = 'key_record' valid = CustomDateTimeField('@valid', required=True) expires = CustomDateTimeField('@expires', required=False) uuid = StringField('uuid', required=True) type = StringField('key/@type', choices=['AES256'], required=True) key = StringField('key', required=True) class AuthKeys(XmlObject): ROOT_NAME = 'auth_keys' domain = StringField('@domain', required=True) issued = CustomDateTimeField('@issued', required=True) key_records = NodeListField('key_record', KeyRecord, required=True) class OpenRosaResponse(XmlObject): ROOT_NAME = 'OpenRosaResponse' xmlns = StringField('@xmlns') message_nature = StringField('message/@nature') message = StringField('message') auth_keys = NodeField('auth_keys', AuthKeys) def __init__(self, *args, **kwargs): super(OpenRosaResponse, self).__init__(*args, **kwargs) self.xmlns = 'http://openrosa.org/http/response' self.message_nature = 'submit_success'
bsd-3-clause
7cb01f650bba0fa07e7f6cb3753cabaa
43.352941
238
0.665451
4.026702
false
false
false
false
onepercentclub/bluebottle
bluebottle/events/migrations/0012_auto_20200217_1106.py
1
1292
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2020-02-17 10:06 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('events', '0011_event_update_contribution_date'), ] operations = [ migrations.AlterField( model_name='event', name='capacity', field=models.PositiveIntegerField(blank=True, null=True, verbose_name='attendee limit'), ), migrations.AlterField( model_name='event', name='is_online', field=models.NullBooleanField(default=None, verbose_name='is online'), ), migrations.AlterField( model_name='event', name='registration_deadline', field=models.DateField(blank=True, null=True, verbose_name='deadline to apply'), ), migrations.AlterField( model_name='event', name='start_date', field=models.DateField(blank=True, null=True, verbose_name='start date'), ), migrations.AlterField( model_name='event', name='start_time', field=models.TimeField(blank=True, null=True, verbose_name='start time'), ), ]
bsd-3-clause
5125ce6daee08a14bb8e9af05172b272
31.3
100
0.582817
4.394558
false
false
false
false
onepercentclub/bluebottle
bluebottle/funding/migrations/0057_auto_20201112_1519.py
1
4069
# -*- coding: utf-8 -*- # Generated by Django 1.11.17 on 2020-11-12 14:19 from __future__ import unicode_literals import bluebottle.files.fields import bluebottle.utils.fields from django.db import migrations, models import django.db.models.deletion import djmoney.models.fields class Migration(migrations.Migration): dependencies = [ ('funding', '0056_auto_20201112_1509'), ] operations = [ migrations.AlterModelOptions( name='bankaccount', options={'ordering': ('id',)}, ), migrations.AlterModelOptions( name='plainpayoutaccount', options={'verbose_name': 'Plain KYC account', 'verbose_name_plural': 'Plain KYC accounts'}, ), migrations.RenameField( model_name='donation', old_name='contribution_ptr', new_name='contributor_ptr', ), migrations.AlterField( model_name='budgetline', name='amount', field=bluebottle.utils.fields.MoneyField(currency_choices=[('EUR', 'Euro')], decimal_places=2, default_currency='EUR', max_digits=12), ), migrations.AlterField( model_name='budgetline', name='amount_currency', field=djmoney.models.fields.CurrencyField(choices=[('EUR', 'Euro')], default='EUR', editable=False, max_length=50), ), migrations.AlterField( model_name='budgetline', name='description', field=models.CharField(default='', max_length=255, verbose_name='description'), ), migrations.AlterField( model_name='donation', name='amount', field=bluebottle.utils.fields.MoneyField(currency_choices=[('EUR', 'Euro')], decimal_places=2, default_currency='EUR', max_digits=12), ), migrations.AlterField( model_name='donation', name='amount_currency', field=djmoney.models.fields.CurrencyField(choices=[('EUR', 'Euro')], default='EUR', editable=False, max_length=50), ), migrations.AlterField( model_name='donation', name='payout_amount', field=bluebottle.utils.fields.MoneyField(currency_choices=[('EUR', 'Euro')], decimal_places=2, default_currency='EUR', max_digits=12), ), migrations.AlterField( model_name='funding', name='target_currency', field=djmoney.models.fields.CurrencyField(choices=[('EUR', 'Euro')], default='EUR', editable=False, max_length=50), ), migrations.AlterField( model_name='fundraiser', name='amount', field=bluebottle.utils.fields.MoneyField(currency_choices=[('EUR', 'Euro')], decimal_places=2, default_currency='EUR', max_digits=12, verbose_name='amount'), ), migrations.AlterField( model_name='fundraiser', name='amount_currency', field=djmoney.models.fields.CurrencyField(choices=[('EUR', 'Euro')], default='EUR', editable=False, max_length=50), ), migrations.AlterField( model_name='paymentcurrency', name='code', field=models.CharField(default='EUR', max_length=50), ), migrations.AlterField( model_name='plainpayoutaccount', name='document', field=bluebottle.files.fields.PrivateDocumentField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='files.PrivateDocument'), ), migrations.AlterField( model_name='reward', name='amount', field=bluebottle.utils.fields.MoneyField(currency_choices=[('EUR', 'Euro')], decimal_places=2, default_currency='EUR', max_digits=12, verbose_name='Amount'), ), migrations.AlterField( model_name='reward', name='amount_currency', field=djmoney.models.fields.CurrencyField(choices=[('EUR', 'Euro')], default='EUR', editable=False, max_length=50), ), ]
bsd-3-clause
2be54cde5726409cf3933da84f352740
40.948454
169
0.596461
4.093561
false
false
false
false
dimagi/commcare-hq
corehq/motech/dhis2/tests/test_entities_helpers.py
1
20922
import doctest import json from unittest.mock import Mock, call, patch from uuid import uuid4 from django.test import SimpleTestCase, TestCase from fakecouch import FakeCouchDb from casexml.apps.case.mock import CaseFactory, CaseIndex, CaseStructure from corehq.apps.domain.shortcuts import create_domain from corehq.apps.locations.models import LocationType, SQLLocation from corehq.apps.users.models import WebUser from corehq.motech.auth import AuthManager from corehq.motech.dhis2.const import DHIS2_DATA_TYPE_DATE, LOCATION_DHIS_ID from corehq.motech.dhis2.dhis2_config import ( Dhis2CaseConfig, Dhis2EntityConfig, Dhis2FormConfig, RelationshipConfig, ) from corehq.motech.dhis2.entities_helpers import ( create_relationships, get_programs_by_id, get_supercase, send_dhis2_entities, validate_tracked_entity, ) from corehq.motech.dhis2.forms import Dhis2ConfigForm from corehq.motech.dhis2.repeaters import Dhis2Repeater from corehq.motech.exceptions import ConfigurationError from corehq.motech.models import ConnectionSettings from corehq.motech.requests import Requests from corehq.motech.value_source import ( CaseTriggerInfo, get_case_trigger_info_for_case, get_form_question_values, ) DOMAIN = 'test-domain' class ValidateTrackedEntityTests(SimpleTestCase): def test_valid(self): """ validate_tracked_entity() should not raise ConfigurationError """ tracked_entity = { "orgUnit": "abc123", "trackedEntityType": "def456", } validate_tracked_entity(tracked_entity) def test_extra_key(self): tracked_entity = { "orgUnit": "abc123", "trackedEntityType": "def456", "hasWensleydale": False } with self.assertRaises(ConfigurationError): validate_tracked_entity(tracked_entity) def test_missing_key(self): tracked_entity = { "trackedEntityType": "def456", } with self.assertRaises(ConfigurationError): validate_tracked_entity(tracked_entity) def test_bad_data_type(self): tracked_entity = { "orgUnit": 0xabc123, "trackedEntityType": 0xdef456 } with self.assertRaises(ConfigurationError): validate_tracked_entity(tracked_entity) class TestDhis2EntitiesHelpers(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.domain = create_domain(DOMAIN) location_type = LocationType.objects.create( domain=DOMAIN, name='test_location_type', ) cls.location = SQLLocation.objects.create( domain=DOMAIN, name='test location', location_id='test_location', location_type=location_type, latitude='-33.6543', longitude='19.1234', metadata={LOCATION_DHIS_ID: "dhis2_location_id"}, ) cls.user = WebUser.create(DOMAIN, 'test', 'passwordtest', None, None) cls.user.set_location(DOMAIN, cls.location) @classmethod def tearDownClass(cls): cls.user.delete(DOMAIN, deleted_by=None) cls.location.delete() cls.domain.delete() super().tearDownClass() def setUp(self): self.db = Dhis2Repeater.get_db() self.fakedb = FakeCouchDb() Dhis2Repeater.set_db(self.fakedb) def tearDown(self): Dhis2Repeater.set_db(self.db) def test_get_programs_by_id(self): program_id = 'test program' form = { "domain": DOMAIN, "form": { "@xmlns": "test_xmlns", "event_date": "2017-05-25T21:06:27.012000", "completed_date": "2017-05-25T21:06:27.012000", "event_location": "-33.6543213 19.12344312 abcdefg", "name": "test event", "meta": { "location": 'test location', "timeEnd": "2017-05-25T21:06:27.012000", "timeStart": "2017-05-25T21:06:17.739000", "userID": self.user.user_id, "username": self.user.username } }, "received_on": "2017-05-26T09:17:23.692083Z", } config = { 'form_configs': json.dumps([{ 'xmlns': 'test_xmlns', 'program_id': program_id, 'event_status': 'COMPLETED', 'event_location': { 'form_question': '/data/event_location' }, 'completed_date': { 'doc_type': 'FormQuestion', 'form_question': '/data/completed_date', 'external_data_type': DHIS2_DATA_TYPE_DATE }, 'org_unit_id': { 'doc_type': 'FormUserAncestorLocationField', 'form_user_ancestor_location_field': LOCATION_DHIS_ID }, 'datavalue_maps': [ { 'data_element_id': 'dhis2_element_id', 'value': { 'doc_type': 'FormQuestion', 'form_question': '/data/name' } } ] }]) } config_form = Dhis2ConfigForm(data=config) self.assertTrue(config_form.is_valid()) data = config_form.cleaned_data repeater = Dhis2Repeater(domain=DOMAIN) conn = ConnectionSettings(domain=DOMAIN, url="http://dummy.com") conn.save() repeater.dhis2_config.form_configs = [Dhis2FormConfig.wrap(fc) for fc in data['form_configs']] repeater.connection_settings_id = conn.id repeater.save() info = CaseTriggerInfo( domain=DOMAIN, case_id=None, owner_id='test_location', form_question_values=get_form_question_values(form), ) programs = get_programs_by_id(info, repeater.dhis2_config) self.assertDictEqual( programs[program_id]['geometry'], {'type': 'Point', 'coordinates': [-33.6543, 19.1234]} ) class TestCreateRelationships(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.domain_obj = create_domain(DOMAIN) cls.factory = CaseFactory(domain=DOMAIN) @classmethod def tearDownClass(cls): cls.domain_obj.delete() super().tearDownClass() def setUp(self): self.child_case, self.parent_case = set_up_cases(self.factory) patcher = patch('corehq.motech.dhis2.entities_helpers.create_relationship') self.create_relationship_func = patcher.start() self.addCleanup(patcher.stop) self.supercase_config = Dhis2CaseConfig.wrap({ 'case_type': 'mother', 'te_type_id': 'person12345', 'tei_id': {'case_property': 'external_id'}, 'org_unit_id': {'case_property': 'dhis2_org_unit_id'}, 'attributes': {}, 'form_configs': [], 'finder_config': {}, }) def test_no_relationships(self): requests = object() case_trigger_info = get_case_trigger_info_for_case( self.child_case, [{'case_property': 'external_id'}, {'case_property': 'dhis2_org_unit_id'}] ) subcase_config = Dhis2CaseConfig.wrap({ 'case_type': 'child', 'te_type_id': 'person12345', 'tei_id': {'case_property': 'external_id'}, 'org_unit_id': {'case_property': 'dhis2_org_unit_id'}, 'attributes': {}, 'form_configs': [], 'finder_config': {}, 'relationships_to_export': [{ 'identifier': 'parent', 'referenced_type': 'mother', # No DHIS2 relationship types configured }] }) dhis2_entity_config = Dhis2EntityConfig( case_configs=[subcase_config, self.supercase_config] ) create_relationships( requests, case_trigger_info, subcase_config, dhis2_entity_config, ) self.create_relationship_func.assert_not_called() def test_one_relationship_given(self): requests = object() case_trigger_info = get_case_trigger_info_for_case( self.child_case, [{'case_property': 'external_id'}, {'case_property': 'dhis2_org_unit_id'}] ) subcase_config = Dhis2CaseConfig.wrap({ 'case_type': 'child', 'te_type_id': 'person12345', 'tei_id': {'case_property': 'external_id'}, 'org_unit_id': {'case_property': 'dhis2_org_unit_id'}, 'attributes': {}, 'form_configs': [], 'finder_config': {}, 'relationships_to_export': [{ 'identifier': 'parent', 'referenced_type': 'mother', 'subcase_to_supercase_dhis2_id': 'b2a12345678', }] }) dhis2_entity_config = Dhis2EntityConfig( case_configs=[subcase_config, self.supercase_config] ) create_relationships( requests, case_trigger_info, subcase_config, dhis2_entity_config, ) self.create_relationship_func.assert_called_with( requests, 'b2a12345678', 'johnny12345', 'alice123456', ) def test_index_given_twice(self): requests = object() case_trigger_info = get_case_trigger_info_for_case( self.child_case, [{'case_property': 'external_id'}, {'case_property': 'dhis2_org_unit_id'}] ) subcase_config = Dhis2CaseConfig.wrap({ 'case_type': 'child', 'te_type_id': 'person12345', 'tei_id': {'case_property': 'external_id'}, 'org_unit_id': {'case_property': 'dhis2_org_unit_id'}, 'attributes': {}, 'form_configs': [], 'finder_config': {}, 'relationships_to_export': [{ 'identifier': 'parent', 'referenced_type': 'mother', 'subcase_to_supercase_dhis2_id': 'b2a12345678', }, { 'identifier': 'parent', 'referenced_type': 'mother', 'supercase_to_subcase_dhis2_id': 'a2b12345678', }] }) dhis2_entity_config = Dhis2EntityConfig( case_configs=[subcase_config, self.supercase_config] ) create_relationships( requests, case_trigger_info, subcase_config, dhis2_entity_config, ) self.create_relationship_func.assert_any_call( requests, 'b2a12345678', 'johnny12345', 'alice123456', ) self.create_relationship_func.assert_called_with( requests, 'a2b12345678', 'alice123456', 'johnny12345', ) def test_both_relationships_given(self): requests = object() case_trigger_info = get_case_trigger_info_for_case( self.child_case, [{'case_property': 'external_id'}, {'case_property': 'dhis2_org_unit_id'}] ) subcase_config = Dhis2CaseConfig.wrap({ 'case_type': 'child', 'te_type_id': 'person12345', 'tei_id': {'case_property': 'external_id'}, 'org_unit_id': {'case_property': 'dhis2_org_unit_id'}, 'attributes': {}, 'form_configs': [], 'finder_config': {}, 'relationships_to_export': [{ 'identifier': 'parent', 'referenced_type': 'mother', 'subcase_to_supercase_dhis2_id': 'b2a12345678', 'supercase_to_subcase_dhis2_id': 'a2b12345678', }] }) dhis2_entity_config = Dhis2EntityConfig( case_configs=[subcase_config, self.supercase_config] ) create_relationships( requests, case_trigger_info, subcase_config, dhis2_entity_config, ) self.create_relationship_func.assert_any_call( requests, 'a2b12345678', 'alice123456', 'johnny12345', ) self.create_relationship_func.assert_called_with( requests, 'b2a12345678', 'johnny12345', 'alice123456', ) class TestRequests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.domain_obj = create_domain(DOMAIN) cls.factory = CaseFactory(domain=DOMAIN) @classmethod def tearDownClass(cls): cls.domain_obj.delete() super().tearDownClass() def setUp(self): self.child_case, self.parent_case = set_up_cases( self.factory, with_dhis2_id=False, ) self.supercase_config = Dhis2CaseConfig.wrap({ 'case_type': 'mother', 'te_type_id': 'person12345', 'tei_id': {'case_property': 'external_id'}, 'org_unit_id': {'case_property': 'dhis2_org_unit_id'}, 'attributes': { 'w75KJ2mc4zz': { 'case_property': 'first_name' }, 'zDhUuAYrxNC': { 'case_property': 'last_name' } }, 'form_configs': [], 'finder_config': {}, }) self.subcase_config = Dhis2CaseConfig.wrap({ 'case_type': 'child', 'te_type_id': 'person12345', 'tei_id': {'case_property': 'external_id'}, 'org_unit_id': {'case_property': 'dhis2_org_unit_id'}, 'attributes': { 'w75KJ2mc4zz': { 'case_property': 'first_name' }, 'zDhUuAYrxNC': { 'case_property': 'last_name' }, 'iESIqZ0R0R0': { 'case_property': 'date_of_birth' } }, 'form_configs': [], 'finder_config': {}, 'relationships_to_export': [{ 'identifier': 'parent', 'referenced_type': 'mother', 'subcase_to_supercase_dhis2_id': 'b2a12345678', 'supercase_to_subcase_dhis2_id': 'a2b12345678', }] }) patcher = patch('corehq.motech.requests.Requests.post') self.post_func = patcher.start() self.addCleanup(patcher.stop) self.post_func.side_effect = [ Response({'response': {'importSummaries': [{'reference': 'ParentTEI12'}]}}), Response({'response': {'importSummaries': [{'reference': 'ChildTEI123'}]}}), Response({'response': {'imported': 1}}), Response({'response': {'imported': 1}}), ] def test_requests(self): repeater = Mock() repeater.dhis2_entity_config = Dhis2EntityConfig( case_configs=[self.subcase_config, self.supercase_config] ) requests = Requests( DOMAIN, 'https://dhis2.example.com/', auth_manager=AuthManager(), ) value_source_configs = [ {'case_property': 'external_id'}, {'case_property': 'first_name'}, {'case_property': 'last_name'}, {'case_property': 'date_of_birth'}, {'case_property': 'dhis2_org_unit_id'}, ] case_trigger_infos = [ get_case_trigger_info_for_case(self.parent_case, value_source_configs), get_case_trigger_info_for_case(self.child_case, value_source_configs) ] send_dhis2_entities(requests, repeater, case_trigger_infos) calls = [ call( '/api/trackedEntityInstances/', json={ 'trackedEntityType': 'person12345', 'orgUnit': 'abcdef12345', 'attributes': [ {'attribute': 'w75KJ2mc4zz', 'value': 'Alice'}, {'attribute': 'zDhUuAYrxNC', 'value': 'Appleseed'} ] }, raise_for_status=True, ), call( '/api/trackedEntityInstances/', json={ 'trackedEntityType': 'person12345', 'orgUnit': 'abcdef12345', 'attributes': [ {'attribute': 'w75KJ2mc4zz', 'value': 'Johnny'}, {'attribute': 'zDhUuAYrxNC', 'value': 'Appleseed'}, {'attribute': 'iESIqZ0R0R0', 'value': '2021-08-27'}, ] }, raise_for_status=True, ), call( '/api/relationships/', json={ 'relationshipType': 'a2b12345678', 'from': {'trackedEntityInstance': {'trackedEntityInstance': 'ParentTEI12'}}, 'to': {'trackedEntityInstance': {'trackedEntityInstance': 'ChildTEI123'}}, }, raise_for_status=True, ), call( '/api/relationships/', json={ 'relationshipType': 'b2a12345678', 'from': {'trackedEntityInstance': {'trackedEntityInstance': 'ChildTEI123'}}, 'to': {'trackedEntityInstance': {'trackedEntityInstance': 'ParentTEI12'}}, }, raise_for_status=True, ) ] self.post_func.assert_has_calls(calls) def set_up_cases(factory, with_dhis2_id=True): child_id = str(uuid4()) parent_id = str(uuid4()) child, parent = factory.create_or_update_case( CaseStructure( case_id=child_id, attrs={ 'create': True, 'case_type': 'child', 'case_name': 'Johnny APPLESEED', 'owner_id': 'b0b', 'external_id': 'johnny12345' if with_dhis2_id else '', 'update': { 'first_name': 'Johnny', 'last_name': 'Appleseed', 'date_of_birth': '2021-08-27', 'dhis2_org_unit_id': 'abcdef12345', }, }, indices=[CaseIndex( CaseStructure( case_id=parent_id, attrs={ 'create': True, 'case_type': 'mother', 'case_name': 'Alice APPLESEED', 'owner_id': 'b0b', 'external_id': 'alice123456' if with_dhis2_id else '', 'update': { 'first_name': 'Alice', 'last_name': 'Appleseed', 'dhis2_org_unit_id': 'abcdef12345', }, }, ), relationship='child', related_type='mother', identifier='parent', )], ) ) return child, parent class TestGetSupercase(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.domain_obj = create_domain(DOMAIN) cls.factory = CaseFactory(domain=DOMAIN) @classmethod def tearDownClass(cls): cls.domain_obj.delete() super().tearDownClass() def setUp(self): self.child_case, self.parent_case = set_up_cases(self.factory) def test_happy_path(self): rel_config = RelationshipConfig.wrap({ 'identifier': 'parent', 'referenced_type': 'mother', 'relationship': 'child', }) value_source_configs = [{'case_property': 'external_id'}] info = get_case_trigger_info_for_case(self.child_case, value_source_configs) parent_case = get_supercase(info, rel_config) self.assertTrue(are_cases_equal(parent_case, self.parent_case)) def test_doctests(): from corehq.motech.dhis2 import entities_helpers results = doctest.testmod(entities_helpers) assert results.failed == 0 def are_cases_equal(a, b): # or at least equal enough for our test attrs = ('domain', 'case_id', 'type', 'name', 'owner_id') return all(getattr(a, attr) == getattr(b, attr) for attr in attrs) class Response: def __init__(self, data): self.data = data def json(self): return self.data
bsd-3-clause
9d64701155174536e13f7fd8c4a2af16
33.074919
102
0.513479
3.994273
false
true
false
false
onepercentclub/bluebottle
bluebottle/assignments/migrations/0003_auto_20190909_1355.py
1
1822
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-09-09 11:55 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('geo', '0013_auto_20190524_0958'), ('assignments', '0002_auto_20190529_0858'), ] operations = [ migrations.RemoveField( model_name='assignment', name='location', ), migrations.AddField( model_name='assignment', name='duration', field=models.FloatField(blank=True, null=True, verbose_name='duration'), ), migrations.AddField( model_name='assignment', name='place', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='geo.Geolocation', verbose_name='Assignment location'), ), migrations.AlterField( model_name='assignment', name='capacity', field=models.PositiveIntegerField(blank=True, null=True, verbose_name='Capacity'), ), migrations.AlterField( model_name='assignment', name='deadline', field=models.DateField(blank=True, null=True, verbose_name='deadline'), ), migrations.AlterField( model_name='assignment', name='expertise', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='tasks.Skill', verbose_name='expertise'), ), migrations.AlterField( model_name='assignment', name='registration_deadline', field=models.DateTimeField(blank=True, null=True, verbose_name='registration deadline'), ), ]
bsd-3-clause
670c0e8e9ea122089a87acadcfb602c8
34.72549
163
0.598793
4.307329
false
false
false
false
dimagi/commcare-hq
corehq/ex-submodules/couchforms/tests/test_archive.py
1
19362
import os from unittest import mock from datetime import datetime, timedelta from django.test import TestCase from corehq.form_processor.signals import sql_case_post_save from corehq.form_processor.tasks import reprocess_archive_stubs from corehq.apps.change_feed import topics from corehq.apps.receiverwrapper.util import submit_form_locally from corehq.form_processor.models import CommCareCase, XFormInstance from corehq.util.context_managers import drop_connected_signals, catch_signal from couchforms.signals import xform_archived, xform_unarchived from corehq.form_processor.tests.utils import FormProcessorTestUtils, sharded from corehq.util.test_utils import TestFileMixin from couchforms.models import UnfinishedArchiveStub from testapps.test_pillowtop.utils import capture_kafka_changes_context @sharded class TestFormArchiving(TestCase, TestFileMixin): file_path = ('data', 'sample_xforms') root = os.path.dirname(__file__) def setUp(self): super(TestFormArchiving, self).setUp() self.casedb = CommCareCase.objects self.formdb = XFormInstance.objects def tearDown(self): FormProcessorTestUtils.delete_all_xforms() FormProcessorTestUtils.delete_all_cases() super(TestFormArchiving, self).tearDown() def testArchive(self): case_id = 'ddb8e2b3-7ce0-43e4-ad45-d7a2eebe9169' xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform self.assertTrue(xform.is_normal) self.assertEqual(0, len(xform.history)) lower_bound = datetime.utcnow() - timedelta(seconds=1) xform.archive(user_id='mr. librarian') upper_bound = datetime.utcnow() + timedelta(seconds=1) xform = self.formdb.get_form(xform.form_id) self.assertTrue(xform.is_archived) case = self.casedb.get_case(case_id, 'test-domain') self.assertTrue(case.is_deleted) self.assertEqual(case.xform_ids, []) [archival] = xform.history self.assertTrue(lower_bound <= archival.date <= upper_bound) self.assertEqual('archive', archival.operation) self.assertEqual('mr. librarian', archival.user) lower_bound = datetime.utcnow() - timedelta(seconds=1) xform.unarchive(user_id='mr. researcher') upper_bound = datetime.utcnow() + timedelta(seconds=1) xform = self.formdb.get_form(xform.form_id) self.assertTrue(xform.is_normal) case = self.casedb.get_case(case_id, 'test-domain') self.assertFalse(case.is_deleted) self.assertEqual(case.xform_ids, [xform.form_id]) [archival, restoration] = xform.history self.assertTrue(lower_bound <= restoration.date <= upper_bound) self.assertEqual('unarchive', restoration.operation) self.assertEqual('mr. researcher', restoration.user) def testUnfinishedArchiveStub(self): # Test running the celery task reprocess_archive_stubs on an existing archive stub case_id = 'ddb8e2b3-7ce0-43e4-ad45-d7a2eebe9169' xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform self.assertTrue(xform.is_normal) self.assertEqual(0, len(xform.history)) # Mock the archive function throwing an error with mock.patch('couchforms.signals.xform_archived.send') as mock_send: try: mock_send.side_effect = Exception xform.archive(user_id='librarian') except Exception: pass # Get the form with the updated history, it should be archived xform = self.formdb.get_form(xform.form_id) self.assertEqual(1, len(xform.history)) self.assertTrue(xform.is_archived) [archival] = xform.history self.assertEqual('archive', archival.operation) self.assertEqual('librarian', archival.user) # The case associated with the form should still exist, it was not rebuilt because of the exception case = self.casedb.get_case(case_id, 'test-domain') self.assertFalse(case.is_deleted) # There should be a stub for the unfinished archive unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 1) self.assertEqual(unfinished_archive_stubs[0].history_updated, True) self.assertEqual(unfinished_archive_stubs[0].user_id, 'librarian') self.assertEqual(unfinished_archive_stubs[0].domain, 'test-domain') self.assertEqual(unfinished_archive_stubs[0].archive, True) # Manually call the periodic celery task that reruns archiving/unarchiving actions reprocess_archive_stubs() # The case and stub should both be deleted now case = self.casedb.get_case(case_id, 'test-domain') self.assertTrue(case.is_deleted) unfinished_archive_stubs_after_reprocessing = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs_after_reprocessing), 0) def testUnfinishedUnarchiveStub(self): # Test running the celery task reprocess_archive_stubs on an existing unarchive stub case_id = 'ddb8e2b3-7ce0-43e4-ad45-d7a2eebe9169' xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform self.assertTrue(xform.is_normal) self.assertEqual(0, len(xform.history)) # Archive the form successfully xform.archive(user_id='librarian') # Mock the unarchive function throwing an error with mock.patch('couchforms.signals.xform_unarchived.send') as mock_send: try: mock_send.side_effect = Exception xform.unarchive(user_id='librarian') except Exception: pass # Make sure the history only has an archive and an unarchive xform = self.formdb.get_form(xform.form_id) self.assertEqual(2, len(xform.history)) self.assertFalse(xform.is_archived) self.assertEqual('archive', xform.history[0].operation) self.assertEqual('librarian', xform.history[0].user) self.assertEqual('unarchive', xform.history[1].operation) self.assertEqual('librarian', xform.history[1].user) # The case should not exist because the unarchived form was not rebuilt case = self.casedb.get_case(case_id, 'test-domain') self.assertTrue(case.is_deleted) # There should be a stub for the unfinished unarchive unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 1) self.assertEqual(unfinished_archive_stubs[0].history_updated, True) self.assertEqual(unfinished_archive_stubs[0].user_id, 'librarian') self.assertEqual(unfinished_archive_stubs[0].domain, 'test-domain') self.assertEqual(unfinished_archive_stubs[0].archive, False) # Manually call the periodic celery task that reruns archiving/unarchiving actions reprocess_archive_stubs() # The case should be back, and the stub should be deleted now case = self.casedb.get_case(case_id, 'test-domain') self.assertFalse(case.is_deleted) unfinished_archive_stubs_after_reprocessing = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs_after_reprocessing), 0) def testUnarchivingWithArchiveStub(self): # Test a user-initiated unarchive with an existing archive stub case_id = 'ddb8e2b3-7ce0-43e4-ad45-d7a2eebe9169' xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform self.assertTrue(xform.is_normal) self.assertEqual(0, len(xform.history)) # Mock the archive function throwing an error with mock.patch('couchforms.signals.xform_archived.send') as mock_send: try: mock_send.side_effect = Exception xform.archive(user_id='librarian') except Exception: pass # There should be a stub for the unfinished archive unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 1) self.assertEqual(unfinished_archive_stubs[0].history_updated, True) self.assertEqual(unfinished_archive_stubs[0].user_id, 'librarian') self.assertEqual(unfinished_archive_stubs[0].domain, 'test-domain') self.assertEqual(unfinished_archive_stubs[0].archive, True) # Call an unarchive xform.unarchive(user_id='librarian') # The unfinished archive stub should be deleted unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 0) # The case should exist because the case close was unarchived case = self.casedb.get_case(case_id, 'test-domain') self.assertFalse(case.is_deleted) # Manually call the periodic celery task that reruns archiving/unarchiving actions reprocess_archive_stubs() # Make sure the case still exists (to double check that the archive stub was deleted) case = self.casedb.get_case(case_id, 'test-domain') self.assertFalse(case.is_deleted) def testArchivingWithUnarchiveStub(self): # Test a user-initiated archive with an existing unarchive stub case_id = 'ddb8e2b3-7ce0-43e4-ad45-d7a2eebe9169' xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform self.assertTrue(xform.is_normal) self.assertEqual(0, len(xform.history)) # Archive the form successfully xform.archive(user_id='librarian') # Mock the unarchive function throwing an error with mock.patch('couchforms.signals.xform_unarchived.send') as mock_send: try: mock_send.side_effect = Exception xform.unarchive(user_id='librarian') except Exception: pass # There should be a stub for the unfinished unarchive unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 1) self.assertEqual(unfinished_archive_stubs[0].history_updated, True) self.assertEqual(unfinished_archive_stubs[0].user_id, 'librarian') self.assertEqual(unfinished_archive_stubs[0].domain, 'test-domain') self.assertEqual(unfinished_archive_stubs[0].archive, False) # Call an archive xform.archive(user_id='librarian') # The unfinished archive stub should be deleted unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 0) # The case should not exist because the case close was archived case = self.casedb.get_case(case_id, 'test-domain') self.assertTrue(case.is_deleted) # Manually call the periodic celery task that reruns archiving/unarchiving actions reprocess_archive_stubs() # The history should not have been added to, make sure that it still only has one entry # Make sure the case still does not exist (to double check that the unarchive stub was deleted) case = self.casedb.get_case(case_id, 'test-domain') self.assertTrue(case.is_deleted) def testUnfinishedArchiveStubErrorAddingHistory(self): # Test running the celery task reprocess_archive_stubs on an existing archive stub where the archive # initially failed on updating the history case_id = 'ddb8e2b3-7ce0-43e4-ad45-d7a2eebe9169' xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform self.assertTrue(xform.is_normal) self.assertEqual(0, len(xform.history)) tmp = 'corehq.form_processor.models.XFormInstance.objects.set_archived_state' with mock.patch(tmp) as mock_operation_sql: try: mock_operation_sql.side_effect = Exception xform.archive(user_id='librarian') except Exception: pass # Get the form with the updated history, make sure it has not been archived yet xform = self.formdb.get_form(xform.form_id) self.assertEqual(0, len(xform.history)) self.assertFalse(xform.is_archived) # The case associated with the form should still exist, it was not rebuilt because of the exception case = self.casedb.get_case(case_id, 'test-domain') self.assertFalse(case.is_deleted) # There should be a stub for the unfinished archive, and the history should not be updated yet unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 1) self.assertEqual(unfinished_archive_stubs[0].history_updated, False) self.assertEqual(unfinished_archive_stubs[0].user_id, 'librarian') self.assertEqual(unfinished_archive_stubs[0].domain, 'test-domain') self.assertEqual(unfinished_archive_stubs[0].archive, True) # Manually call the periodic celery task that reruns archiving/unarchiving actions reprocess_archive_stubs() # Make sure the history shows an archive now xform = self.formdb.get_form(xform.form_id) self.assertEqual(1, len(xform.history)) self.assertTrue(xform.is_archived) [archival] = xform.history self.assertEqual('archive', archival.operation) self.assertEqual('librarian', archival.user) # The case and stub should both be deleted now case = self.casedb.get_case(case_id, 'test-domain') self.assertTrue(case.is_deleted) unfinished_archive_stubs_after_reprocessing = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs_after_reprocessing), 0) def testUnfinishedUnarchiveStubErrorAddingHistory(self): # Test running the celery task reprocess_archive_stubs on an existing archive stub where the archive # initially failed on updating the history case_id = 'ddb8e2b3-7ce0-43e4-ad45-d7a2eebe9169' xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform self.assertTrue(xform.is_normal) self.assertEqual(0, len(xform.history)) # Archive the form successfully xform.archive(user_id='librarian') tmp = 'corehq.form_processor.models.XFormInstance.objects.set_archived_state' with mock.patch(tmp) as mock_operation_sql: try: mock_operation_sql.side_effect = Exception xform.unarchive(user_id='librarian') except Exception: pass # Get the form with the updated history, make sure it only has one entry (the archive) xform = self.formdb.get_form(xform.form_id) self.assertEqual(1, len(xform.history)) self.assertTrue(xform.is_archived) [archival] = xform.history self.assertEqual('archive', archival.operation) self.assertEqual('librarian', archival.user) # The case associated with the form should not exist, it was not rebuilt because of the exception case = self.casedb.get_case(case_id, 'test-domain') self.assertTrue(case.is_deleted) # There should be a stub for the unfinished archive, and the history should not be updated yet unfinished_archive_stubs = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs), 1) self.assertEqual(unfinished_archive_stubs[0].history_updated, False) self.assertEqual(unfinished_archive_stubs[0].user_id, 'librarian') self.assertEqual(unfinished_archive_stubs[0].domain, 'test-domain') self.assertEqual(unfinished_archive_stubs[0].archive, False) # Manually call the periodic celery task that reruns archiving/unarchiving actions reprocess_archive_stubs() # Make sure the history shows an archive and an unarchive now xform = self.formdb.get_form(xform.form_id) self.assertEqual(2, len(xform.history)) self.assertFalse(xform.is_archived) self.assertEqual('archive', xform.history[0].operation) self.assertEqual('librarian', xform.history[0].user) self.assertEqual('unarchive', xform.history[1].operation) self.assertEqual('librarian', xform.history[1].user) # The case should be back, and the stub should be deleted now case = self.casedb.get_case(case_id, 'test-domain') self.assertFalse(case.is_deleted) unfinished_archive_stubs_after_reprocessing = UnfinishedArchiveStub.objects.filter() self.assertEqual(len(unfinished_archive_stubs_after_reprocessing), 0) def testSignal(self): xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) case_id = result.case.case_id with catch_signal(xform_archived) as unarchive_form_handler, \ catch_signal(sql_case_post_save) as archive_case_handler: result.xform.archive() self.assertEqual(result.xform.form_id, unarchive_form_handler.call_args[1]['xform'].form_id) self.assertEqual(case_id, archive_case_handler.call_args[1]['case'].case_id) xform = self.formdb.get_form(result.xform.form_id) with catch_signal(xform_unarchived) as unarchive_form_handler, \ catch_signal(sql_case_post_save) as unarchive_case_handler: xform.unarchive() self.assertEqual(result.xform.form_id, unarchive_form_handler.call_args[1]['xform'].form_id) self.assertEqual(case_id, unarchive_case_handler.call_args[1]['case'].case_id) def testPublishChanges(self): xml_data = self.get_xml('basic') result = submit_form_locally( xml_data, 'test-domain', ) xform = result.xform with capture_kafka_changes_context(topics.FORM_SQL) as change_context: with drop_connected_signals(xform_archived), drop_connected_signals(sql_case_post_save): xform.archive() self.assertEqual(1, len(change_context.changes)) self.assertEqual(change_context.changes[0].id, xform.form_id) xform = self.formdb.get_form(xform.form_id) with capture_kafka_changes_context(topics.FORM_SQL) as change_context: with drop_connected_signals(xform_unarchived), drop_connected_signals(sql_case_post_save): xform.unarchive() self.assertEqual(1, len(change_context.changes)) self.assertEqual(change_context.changes[0].id, xform.form_id)
bsd-3-clause
de87b0cc80e52465a00feae997039ec2
43.819444
108
0.666873
3.80767
false
true
false
false
dimagi/commcare-hq
corehq/apps/app_manager/tests/test_suite_formats.py
1
9879
import hashlib import commcare_translations from django.test import SimpleTestCase from corehq.apps.app_manager.models import ( Application, DetailColumn, MappingItem, Module, ) from corehq.apps.app_manager.tests.util import TestXmlMixin, patch_get_xform_resource_overrides @patch_get_xform_resource_overrides() class SuiteFormatsTest(SimpleTestCase, TestXmlMixin): file_path = ('data', 'suite') def _test_media_format(self, detail_format, template_form): app = Application.wrap(self.get_json('app_audio_format')) details = app.get_module(0).case_details details.short.get_column(0).format = detail_format details.long.get_column(0).format = detail_format expected = """ <partial> <template form="{0}"> <text> <xpath function="picproperty"/> </text> </template> <template form="{0}"> <text> <xpath function="picproperty"/> </text> </template> </partial> """.format(template_form) self.assertXmlPartialEqual(expected, app.create_suite(), "./detail/field/template") def test_audio_format(self, *args): self._test_media_format('audio', 'audio') def test_image_format(self, *args): self._test_media_format('picture', 'image') def test_case_detail_conditional_enum(self, *args): app = Application.new_app('domain', 'Untitled Application') module = app.add_module(Module.new_module('Unititled Module', None)) module.case_type = 'patient' module.case_details.short.columns = [ DetailColumn( header={'en': 'Gender'}, model='case', field='gender', format='conditional-enum', enum=[ MappingItem(key="gender = 'male' and age <= 21", value={'en': 'Boy'}), MappingItem(key="gender = 'female' and age <= 21", value={'en': 'Girl'}), MappingItem(key="gender = 'male' and age > 21", value={'en': 'Man'}), MappingItem(key="gender = 'female' and age > 21", value={'en': 'Woman'}), ], ), ] key1_varname = hashlib.md5("gender = 'male' and age <= 21".encode('utf-8')).hexdigest()[:8] key2_varname = hashlib.md5("gender = 'female' and age <= 21".encode('utf-8')).hexdigest()[:8] key3_varname = hashlib.md5("gender = 'male' and age > 21".encode('utf-8')).hexdigest()[:8] key4_varname = hashlib.md5("gender = 'female' and age > 21".encode('utf-8')).hexdigest()[:8] icon_mapping_spec = """ <partial> <template> <text> <xpath function="if(gender = 'male' and age &lt;= 21, $h{key1_varname}, if(gender = 'female' and age &lt;= 21, $h{key2_varname}, if(gender = 'male' and age &gt; 21, $h{key3_varname}, if(gender = 'female' and age &gt; 21, $h{key4_varname}, ''))))"> <variable name="h{key4_varname}"> <locale id="m0.case_short.case_gender_1.enum.h{key4_varname}"/> </variable> <variable name="h{key2_varname}"> <locale id="m0.case_short.case_gender_1.enum.h{key2_varname}"/> </variable> <variable name="h{key3_varname}"> <locale id="m0.case_short.case_gender_1.enum.h{key3_varname}"/> </variable> <variable name="h{key1_varname}"> <locale id="m0.case_short.case_gender_1.enum.h{key1_varname}"/> </variable> </xpath> </text> </template> </partial> """.format( # noqa: #501 key1_varname=key1_varname, key2_varname=key2_varname, key3_varname=key3_varname, key4_varname=key4_varname, ) # check correct suite is generated self.assertXmlPartialEqual( icon_mapping_spec, app.create_suite(), './detail[@id="m0_case_short"]/field/template' ) # check app strings mapped correctly app_strings = commcare_translations.loads(app.create_app_strings('en')) self.assertEqual( app_strings['m0.case_short.case_gender_1.enum.h{key1_varname}'.format(key1_varname=key1_varname, )], 'Boy' ) self.assertEqual( app_strings['m0.case_short.case_gender_1.enum.h{key2_varname}'.format(key2_varname=key2_varname, )], 'Girl' ) self.assertEqual( app_strings['m0.case_short.case_gender_1.enum.h{key3_varname}'.format(key3_varname=key3_varname, )], 'Man' ) self.assertEqual( app_strings['m0.case_short.case_gender_1.enum.h{key4_varname}'.format(key4_varname=key4_varname, )], 'Woman' ) def test_case_detail_calculated_conditional_enum(self, *args): app = Application.new_app('domain', 'Untitled Application') module = app.add_module(Module.new_module('Unititled Module', None)) module.case_type = 'patient' module.case_details.short.columns = [ DetailColumn( header={'en': 'Gender'}, model='case', field="if(gender = 'male', 'boy', 'girl')", format='enum', enum=[ MappingItem(key="boy", value={'en': 'Boy'}), MappingItem(key="girl", value={'en': 'Girl'}), ], ), ] icon_mapping_spec = """ <partial> <template> <text> <xpath function="replace(join(' ', if(selected(if(gender = 'male', 'boy', 'girl'), 'boy'), $kboy, ''), if(selected(if(gender = 'male', 'boy', 'girl'), 'girl'), $kgirl, '')), '\\s+', ' ')"> <variable name="kboy"> <locale id="m0.case_short.case_if(gender 'male', 'boy', 'girl')_1.enum.kboy"/> </variable> <variable name="kgirl"> <locale id="m0.case_short.case_if(gender 'male', 'boy', 'girl')_1.enum.kgirl"/> </variable> </xpath> </text> </template> </partial> """ # noqa: #501 # check correct suite is generated self.assertXmlPartialEqual( icon_mapping_spec, app.create_suite(), './detail[@id="m0_case_short"]/field/template' ) # check app strings mapped correctly app_strings = commcare_translations.loads(app.create_app_strings('en')) self.assertEqual( app_strings["m0.case_short.case_if(gender 'male', 'boy', 'girl')_1.enum.kboy"], 'Boy' ) self.assertEqual( app_strings["m0.case_short.case_if(gender 'male', 'boy', 'girl')_1.enum.kgirl"], 'Girl' ) def test_case_detail_icon_mapping(self, *args): app = Application.new_app('domain', 'Untitled Application') module = app.add_module(Module.new_module('Untitled Module', None)) module.case_type = 'patient' module.case_details.short.columns = [ DetailColumn( header={'en': 'Age range'}, model='case', field='age', format='enum-image', enum=[ MappingItem(key='10', value={'en': 'jr://icons/10-year-old.png'}), MappingItem(key='age > 50', value={'en': 'jr://icons/old-icon.png'}), MappingItem(key='15%', value={'en': 'jr://icons/percent-icon.png'}), ], ), ] key1_varname = '10' key2_varname = hashlib.md5('age > 50'.encode('utf-8')).hexdigest()[:8] key3_varname = hashlib.md5('15%'.encode('utf-8')).hexdigest()[:8] icon_mapping_spec = """ <partial> <template form="image" width="13%"> <text> <xpath function="if(age = '10', $k{key1_varname}, if(age > 50, $h{key2_varname}, if(age = '15%', $h{key3_varname}, '')))"> <variable name="h{key2_varname}"> <locale id="m0.case_short.case_age_1.enum.h{key2_varname}"/> </variable> <variable name="h{key3_varname}"> <locale id="m0.case_short.case_age_1.enum.h{key3_varname}"/> </variable> <variable name="k{key1_varname}"> <locale id="m0.case_short.case_age_1.enum.k{key1_varname}"/> </variable> </xpath> </text> </template> </partial> """.format( # noqa: #501 key1_varname=key1_varname, key2_varname=key2_varname, key3_varname=key3_varname, ) # check correct suite is generated self.assertXmlPartialEqual( icon_mapping_spec, app.create_suite(), './detail/field/template[@form="image"]' ) # check icons map correctly app_strings = commcare_translations.loads(app.create_app_strings('en')) self.assertEqual( app_strings['m0.case_short.case_age_1.enum.h{key3_varname}'.format(key3_varname=key3_varname,)], 'jr://icons/percent-icon.png' ) self.assertEqual( app_strings['m0.case_short.case_age_1.enum.h{key2_varname}'.format(key2_varname=key2_varname,)], 'jr://icons/old-icon.png' ) self.assertEqual( app_strings['m0.case_short.case_age_1.enum.k{key1_varname}'.format(key1_varname=key1_varname,)], 'jr://icons/10-year-old.png' )
bsd-3-clause
0c0302a758c6ab2bc5b20456dfcc755b
39.487705
261
0.520599
3.657534
false
true
false
false
onepercentclub/bluebottle
bluebottle/notifications/migrations/0001_initial.py
1
1278
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2019-04-15 12:19 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('contenttypes', '0002_remove_content_type_name'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sent', models.DateTimeField(blank=True, null=True)), ('adapter', models.CharField(default=b'email', max_length=30)), ('template', models.CharField(max_length=100)), ('subject', models.CharField(max_length=200)), ('object_id', models.PositiveIntegerField()), ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), ('recipient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
bsd-3-clause
1e3e0934c0e4a5732dbeec34380c7f5f
37.727273
128
0.621283
4.245847
false
false
false
false
onepercentclub/bluebottle
bluebottle/funding/migrations/0049_auto_20200124_1032.py
1
2772
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2020-01-24 09:32 from __future__ import unicode_literals import bluebottle.utils.fields from decimal import Decimal from django.db import migrations, models import django.db.models.deletion import djmoney.models.fields class Migration(migrations.Migration): dependencies = [ ('funding', '0048_add_permissions'), ] operations = [ migrations.AlterModelOptions( name='payout', options={'verbose_name': 'payout', 'verbose_name_plural': 'payouts'}, ), migrations.AlterModelOptions( name='plainpayoutaccount', options={'verbose_name': 'Without payment account', 'verbose_name_plural': 'Without payment accounts'}, ), migrations.AddField( model_name='donation', name='payout_amount', field=bluebottle.utils.fields.MoneyField(currency_choices=[(b'EUR', b'Euro')], decimal_places=2, default=Decimal('0.0'), default_currency=b'EUR', max_digits=12), ), migrations.AddField( model_name='donation', name='payout_amount_currency', field=djmoney.models.fields.CurrencyField(choices=[(b'EUR', b'Euro')], default=b'EUR', editable=False, max_length=50), ), migrations.AlterField( model_name='donation', name='fundraiser', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='donations', to='funding.Fundraiser'), ), migrations.AlterField( model_name='donation', name='name', field=models.CharField(blank=True, help_text='Override donor name / Name for guest donation', max_length=200, null=True, verbose_name='Fake name'), ), migrations.AlterField( model_name='donation', name='reward', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='donations', to='funding.Reward'), ), migrations.AlterField( model_name='funding', name='deadline', field=models.DateTimeField(blank=True, help_text='If you enter a deadline, leave the duration field empty.', null=True, verbose_name='deadline'), ), migrations.AlterField( model_name='funding', name='duration', field=models.PositiveIntegerField(blank=True, help_text='If you enter a duration, leave the deadline field empty.', null=True, verbose_name='duration'), ), migrations.AlterField( model_name='payment', name='updated', field=models.DateTimeField(), ), ]
bsd-3-clause
1a59d6b3c0356a3a1c6b811f91a1ac2d
40.373134
173
0.615079
4.137313
false
false
false
false
dimagi/commcare-hq
corehq/apps/app_manager/suite_xml/contributors.py
1
1085
from abc import ABCMeta, abstractmethod, abstractproperty class BaseSuiteContributor(metaclass=ABCMeta): def __init__(self, suite, app, modules, build_profile_id=None): from corehq.apps.app_manager.suite_xml.sections.entries import EntriesHelper self.suite = suite self.app = app self.modules = modules self.build_profile_id = build_profile_id self.entries_helper = EntriesHelper(app, modules, build_profile_id=self.build_profile_id) @property def timing_context(self): return self.app.timing_context class SectionContributor(BaseSuiteContributor, metaclass=ABCMeta): @abstractproperty def section_name(self): pass @abstractmethod def get_section_elements(self): return [] class SuiteContributorByModule(BaseSuiteContributor, metaclass=ABCMeta): section = None @abstractmethod def get_module_contributions(self, module): return [] class PostProcessor(BaseSuiteContributor, metaclass=ABCMeta): @abstractmethod def update_suite(self): pass
bsd-3-clause
f5bc7254f750ad8c86d3e5190aaef6c2
26.820513
97
0.704147
4.048507
false
false
false
false
dimagi/commcare-hq
corehq/util/metrics/load_counters.py
1
2796
from functools import partial def load_counter(load_type, source, domain_name, extra_tags=None): """Make a function to track load by counting touched items :param load_type: Load type (`"case"`, `"form"`, `"sms"`). Use one of the convenience functions below (e.g., `case_load_counter`) rather than passing a string literal. :param source: Load source string. Example: `"form_submission"`. :param domain_name: Domain name string. :param extra_tags: Optional dict of extra metric tags. :returns: Function that adds load when called: `add_load(value=1)`. """ from corehq.util.metrics import metrics_counter tags = extra_tags or {} tags['src'] = source tags['domain'] = domain_name metric = "commcare.load.%s" % load_type def track_load(value=1): metrics_counter(metric, value, tags=tags) return track_load def case_load_counter(*args, **kw): # grep: commcare.load.case return load_counter("case", *args, **kw) def form_load_counter(*args, **kw): # grep: commcare.load.form return load_counter("form", *args, **kw) def ledger_load_counter(*args, **kw): """Make a ledger transaction load counter function Each item counted is a ledger transaction (not a ledger value). """ # grep: commcare.load.ledger return load_counter("ledger", *args, **kw) def sms_load_counter(*args, **kw): """Make a messaging load counter function This is used to count all kinds of messaging load, including email (not strictly SMS). """ # grep: commcare.load.sms return load_counter("sms", *args, **kw) def ucr_load_counter(engine_id, *args, **kw): """Make a UCR load counter function This is used to count all kinds of UCR load """ # grep: commcare.load.ucr return load_counter("ucr.{}".format(engine_id), *args, **kw) def schedule_load_counter(*args, **kw): """Make a schedule load counter function This is used to count load from ScheduleInstances """ # grep: commcare.load.schedule return load_counter("schedule", *args, **kw) def load_counter_for_model(model): from corehq.form_processor.models import CommCareCase, XFormInstance from corehq.messaging.scheduling.scheduling_partitioned.models import ( AlertScheduleInstance, TimedScheduleInstance, CaseTimedScheduleInstance, CaseAlertScheduleInstance ) return { CommCareCase: case_load_counter, XFormInstance: form_load_counter, AlertScheduleInstance: schedule_load_counter, TimedScheduleInstance: schedule_load_counter, CaseTimedScheduleInstance: schedule_load_counter, CaseAlertScheduleInstance: schedule_load_counter, }.get(model, partial(load_counter, 'unknown')) # grep: commcare.load.unknown
bsd-3-clause
7fdb952a72cb2b21d170fcfdcf8377b8
31.511628
106
0.681688
3.723036
false
false
false
false
dimagi/commcare-hq
corehq/apps/smsbillables/management/commands/bootstrap_yo_gateway.py
1
1466
from decimal import Decimal from django.core.management.base import BaseCommand from corehq.apps.accounting.models import Currency from corehq.apps.sms.models import INCOMING, OUTGOING from corehq.apps.smsbillables.models import ( SmsGatewayFee, SmsGatewayFeeCriteria, ) from corehq.apps.smsbillables.utils import log_smsbillables_info from corehq.messaging.smsbackends.yo.models import SQLYoBackend def bootstrap_yo_gateway(apps): ugx, _ = (apps.get_model('accounting', 'Currency') if apps else Currency).objects.get_or_create(code='UGX') sms_gateway_fee_class = apps.get_model('smsbillables', 'SmsGatewayFee') if apps else SmsGatewayFee sms_gateway_fee_criteria_class = apps.get_model('smsbillables', 'SmsGatewayFeeCriteria') if apps else SmsGatewayFeeCriteria SmsGatewayFee.create_new( SQLYoBackend.get_api_id(), INCOMING, Decimal('110.0'), currency=ugx, fee_class=sms_gateway_fee_class, criteria_class=sms_gateway_fee_criteria_class, ) SmsGatewayFee.create_new( SQLYoBackend.get_api_id(), OUTGOING, Decimal('55.0'), currency=ugx, fee_class=sms_gateway_fee_class, criteria_class=sms_gateway_fee_criteria_class, ) log_smsbillables_info("Updated Yo gateway fees.") class Command(BaseCommand): help = "bootstrap Yo global SMS backend gateway fees" def handle(self, **options): bootstrap_yo_gateway(None)
bsd-3-clause
bf7dd6f0e870ed48dad1e18380cf2ed5
31.577778
127
0.710778
3.393519
false
false
false
false
dimagi/commcare-hq
corehq/util/context_managers.py
1
1676
from contextlib import contextmanager from django.core.cache import cache from corehq.const import DEFAULT_PARALLEL_EXECUTION_TIMEOUT from corehq.util.exceptions import ParallelExecutionError from corehq.util.soft_assert import soft_assert @contextmanager def drop_connected_signals(signal): """ Use as a context manager to temporarily drop signals. Useful in tests. with drop_connected_signals(sql_case_post_save): case.save() # signals won't be called case.save() # signals will be called again """ connected_signals = signal.receivers signal.receivers = [] try: yield finally: signal.receivers = connected_signals @contextmanager def notify_someone(email, success_message, error_message='Sorry, your HQ task failed!', send=True): def send_message_if_needed(message, exception=None): if email and send: soft_assert(to=email, notify_admins=False, send_to_ops=False)(False, message, exception) try: yield send_message_if_needed(success_message) except BaseException as e: send_message_if_needed(error_message, e) raise @contextmanager def catch_signal(signal): """Catch django signal and return the mocked call.""" from unittest.mock import Mock handler = Mock() signal.connect(handler) yield handler signal.disconnect(handler) @contextmanager def prevent_parallel_execution(cache_key, timeout=DEFAULT_PARALLEL_EXECUTION_TIMEOUT): if cache.get(cache_key, False): raise ParallelExecutionError cache.set(cache_key, True, timeout) try: yield finally: cache.set(cache_key, False)
bsd-3-clause
c22c2db09f66219a8d99a24b5bf73d9a
27.896552
100
0.702864
4.019185
false
false
false
false
dimagi/commcare-hq
corehq/apps/users/middleware.py
1
1106
from django.utils.deprecation import MiddlewareMixin from corehq.apps.users.models import CouchUser, InvalidUser from corehq.apps.users.util import username_to_user_id SESSION_USER_KEY_PREFIX = "session_user_doc_%s" class UsersMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): request.analytics_enabled = True if 'domain' in view_kwargs: request.domain = view_kwargs['domain'] if 'org' in view_kwargs: request.org = view_kwargs['org'] if request.user and request.user.is_authenticated: user_id = username_to_user_id(request.user.username) couch_user = CouchUser.get_by_user_id(user_id) if not couch_user: couch_user = InvalidUser() request.couch_user = couch_user if not request.couch_user.analytics_enabled: request.analytics_enabled = False if 'domain' in view_kwargs: domain = request.domain request.couch_user.current_domain = domain return None
bsd-3-clause
c38804344db3b4105d4fb46296aa0dc2
38.5
71
0.638336
3.935943
false
false
false
false
dimagi/commcare-hq
corehq/apps/api/resources/auth.py
1
7323
import json from functools import wraps from django.core.exceptions import PermissionDenied from django.http import Http404, HttpResponse, HttpResponseForbidden from attrs import define, field from tastypie.authentication import Authentication from corehq.apps.api.odata.views import odata_permissions_check from corehq.apps.domain.auth import BASIC, determine_authtype_from_header from corehq.apps.domain.decorators import ( api_key_auth, basic_auth_or_try_api_key_auth, get_auth_decorator_map, ) from corehq.apps.users.decorators import ( require_api_permission, require_permission_raw, ) from corehq.toggles import API_THROTTLE_WHITELIST, IS_CONTRACTOR def wrap_4xx_errors_for_apis(view_func): @wraps(view_func) def _inner(req, *args, **kwargs): try: return view_func(req, *args, **kwargs) except Http404 as e: if str(e): return HttpResponse(json.dumps({"error": str(e)}), content_type="application/json", status=404) return HttpResponse(json.dumps({"error": "not authorized"}), content_type="application/json", status=401) return _inner @define class ApiIdentifier: username = field() domain = field() def get_rate_limit_identifier(request): couch_user = getattr(request, 'couch_user', None) if couch_user is not None: username = couch_user.username else: username = '' domain = getattr(request, 'domain', '') return ApiIdentifier(username=username, domain=domain) class HQAuthenticationMixin: decorator_map = {} # should be set by subclasses def _get_auth_decorator(self, request): return self.decorator_map[determine_authtype_from_header(request)] def get_identifier(self, request): return get_rate_limit_identifier(request) class SSOAuthentication(HQAuthenticationMixin, Authentication): pass class LoginAuthentication(HQAuthenticationMixin, Authentication): """ Just checks you are able to login. Does not check against any permissions/domains, etc. """ def __init__(self, allow_session_auth=False): super().__init__() self.decorator_map = get_auth_decorator_map(require_domain=False, allow_sessions=allow_session_auth) def is_authenticated(self, request, **kwargs): return self._auth_test(request, wrappers=[ self._get_auth_decorator(request), wrap_4xx_errors_for_apis, ], **kwargs) def _auth_test(self, request, wrappers, **kwargs): PASSED_AUTH = object() def dummy(request, **kwargs): return PASSED_AUTH wrapped_dummy = dummy for wrapper in wrappers: wrapped_dummy = wrapper(wrapped_dummy) try: response = wrapped_dummy(request, **kwargs) return response is PASSED_AUTH except PermissionDenied: return False class LoginAndDomainAuthentication(HQAuthenticationMixin, Authentication): def __init__(self, allow_session_auth=False, *args, **kwargs): """ allow_session_auth: set this to True to allow session based access to this resource """ super(LoginAndDomainAuthentication, self).__init__(*args, **kwargs) self.decorator_map = get_auth_decorator_map(require_domain=True, allow_sessions=allow_session_auth) def is_authenticated(self, request, **kwargs): return self._auth_test(request, wrappers=[ require_api_permission('access_api', login_decorator=self._get_auth_decorator(request)), wrap_4xx_errors_for_apis, ], **kwargs) def _auth_test(self, request, wrappers, **kwargs): PASSED_AUTH = 'is_authenticated' def dummy(request, domain, **kwargs): return PASSED_AUTH wrapped_dummy = dummy for wrapper in wrappers: wrapped_dummy = wrapper(wrapped_dummy) if 'domain' not in kwargs: kwargs['domain'] = request.domain try: response = wrapped_dummy(request, **kwargs) except PermissionDenied: response = HttpResponseForbidden() if response == PASSED_AUTH: return True else: return response class NoAPIPermissionsAuthentication(LoginAndDomainAuthentication): """ Checks for domain and login and does not check for access api permissions """ def __init__(self, *args, **kwargs): super(NoAPIPermissionsAuthentication, self).__init__(*args, **kwargs) def is_authenticated(self, request, **kwargs): return self._auth_test(request, wrappers=[ self._get_auth_decorator(request), wrap_4xx_errors_for_apis, ], **kwargs) class RequirePermissionAuthentication(LoginAndDomainAuthentication): def __init__(self, permission, *args, **kwargs): super(RequirePermissionAuthentication, self).__init__(*args, **kwargs) self.permission = permission def is_authenticated(self, request, **kwargs): wrappers = [ require_api_permission(self.permission, login_decorator=self._get_auth_decorator(request)), wrap_4xx_errors_for_apis, ] return self._auth_test(request, wrappers=wrappers, **kwargs) class ODataAuthentication(LoginAndDomainAuthentication): def __init__(self, *args, **kwargs): super(ODataAuthentication, self).__init__(*args, **kwargs) self.decorator_map = { 'basic': basic_auth_or_try_api_key_auth, 'api_key': api_key_auth, } def is_authenticated(self, request, **kwargs): wrappers = [ require_permission_raw( odata_permissions_check, self._get_auth_decorator(request) ), wrap_4xx_errors_for_apis, ] return self._auth_test(request, wrappers=wrappers, **kwargs) def _get_auth_decorator(self, request): return self.decorator_map[determine_authtype_from_header(request, default=BASIC)] class DomainAdminAuthentication(LoginAndDomainAuthentication): def is_authenticated(self, request, **kwargs): permission_check = lambda couch_user, domain: couch_user.is_domain_admin(domain) wrappers = [ require_permission_raw(permission_check, login_decorator=self._get_auth_decorator(request)), wrap_4xx_errors_for_apis, ] return self._auth_test(request, wrappers=wrappers, **kwargs) class AdminAuthentication(LoginAndDomainAuthentication): @staticmethod def _permission_check(couch_user, domain): return ( couch_user.is_superuser or IS_CONTRACTOR.enabled(couch_user.username) ) def is_authenticated(self, request, **kwargs): decorator = require_permission_raw( self._permission_check, login_decorator=self._get_auth_decorator(request) ) wrappers = [decorator, wrap_4xx_errors_for_apis] # passing the domain is a hack to work around non-domain-specific requests # failing on auth return self._auth_test(request, wrappers=wrappers, domain='dimagi', **kwargs)
bsd-3-clause
174b69a91c919756278b4640ff0af9a6
32.286364
108
0.639492
4.194158
false
false
false
false
dimagi/commcare-hq
corehq/apps/enterprise/forms.py
1
12977
from django import forms from django.core.exceptions import ValidationError from django.urls import reverse from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy from crispy_forms import layout as crispy from crispy_forms.bootstrap import PrependedText, StrictButton from crispy_forms.helper import FormHelper from corehq.apps.accounting.utils import domain_has_privilege from corehq.apps.hqwebapp import crispy as hqcrispy from corehq.apps.hqwebapp.widgets import BootstrapCheckboxInput from corehq.apps.export.models.export_settings import ExportFileType from corehq.privileges import DEFAULT_EXPORT_SETTINGS class EnterpriseSettingsForm(forms.Form): restrict_domain_creation = forms.BooleanField( label=gettext_lazy("Restrict Project Space Creation"), required=False, help_text=gettext_lazy("Do not allow current web users, other than enterprise admins, " "to create new project spaces."), ) restrict_signup = forms.BooleanField( label=gettext_lazy("Restrict User Signups"), required=False, help_text=gettext_lazy("<span data-bind='html: restrictSignupHelp'></span>"), ) restrict_signup_message = forms.CharField( label="Signup Restriction Message", required=False, help_text=gettext_lazy("Message to display to users who attempt to sign up for an account"), widget=forms.Textarea(attrs={'rows': 2, 'maxlength': 512, "class": "vertical-resize"}), ) forms_filetype = forms.ChoiceField( label=gettext_lazy("Default File Type"), required=False, initial=ExportFileType.EXCEL_2007_PLUS, choices=ExportFileType.CHOICES, ) forms_auto_convert = forms.BooleanField( label=gettext_lazy("Excel Date & Multimedia Format"), widget=BootstrapCheckboxInput( inline_label=gettext_lazy( "Automatically convert dates and multimedia links for Excel" ), ), required=False, help_text=gettext_lazy("Leaving this checked will ensure dates appear in excel format. " "Otherwise they will appear as a normal text format. This also allows " "for hyperlinks to the multimedia captured by your form submission.") ) forms_auto_format_cells = forms.BooleanField( label=gettext_lazy("Excel Cell Format"), widget=BootstrapCheckboxInput( inline_label=gettext_lazy( "Automatically format cells for Excel 2007+" ), ), required=False, help_text=gettext_lazy("If this setting is not selected, your export will be in Excel's generic format. " "If you enable this setting, Excel will format dates, integers, decimals, " "boolean values (True/False), and currencies.") ) forms_expand_checkbox = forms.BooleanField( label=gettext_lazy("Checkbox Format"), widget=BootstrapCheckboxInput( inline_label=gettext_lazy( "Expand checkbox questions" ), ), required=False, ) cases_filetype = forms.ChoiceField( label=gettext_lazy("Default File Type"), required=False, initial=ExportFileType.EXCEL_2007_PLUS, choices=ExportFileType.CHOICES, ) cases_auto_convert = forms.BooleanField( label=gettext_lazy("Excel Date & Multimedia Format"), widget=BootstrapCheckboxInput( inline_label=gettext_lazy( "Automatically convert dates and multimedia links for Excel" ), ), required=False, help_text=gettext_lazy("Leaving this checked will ensure dates appear in excel format. " "Otherwise they will appear as a normal text format. This also allows " "for hyperlinks to the multimedia captured by your form submission.") ) odata_expand_checkbox = forms.BooleanField( label=gettext_lazy("Checkbox Format"), widget=BootstrapCheckboxInput( inline_label=gettext_lazy( "Expand checkbox questions" ), ), help_text=gettext_lazy("Only applies to form exports."), required=False, ) def __init__(self, *args, **kwargs): self.domain = kwargs.pop('domain', None) self.account = kwargs.pop('account', None) self.username = kwargs.pop('username', None) self.export_settings = kwargs.pop('export_settings', None) kwargs['initial'] = { "restrict_domain_creation": self.account.restrict_domain_creation, "restrict_signup": self.account.restrict_signup, "restrict_signup_message": self.account.restrict_signup_message, } if self.export_settings and domain_has_privilege(self.domain, DEFAULT_EXPORT_SETTINGS): kwargs['initial'].update(self.export_settings.as_dict()) super(EnterpriseSettingsForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'enterprise-settings-form' self.helper.form_class = 'form-horizontal' self.helper.form_action = reverse("edit_enterprise_settings", args=[self.domain]) self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( _("Edit Enterprise Settings"), PrependedText('restrict_domain_creation', ''), crispy.Div( PrependedText('restrict_signup', '', data_bind='checked: restrictSignup'), ), crispy.Div( crispy.Field('restrict_signup_message'), data_bind='visible: restrictSignup', ), ) ) if domain_has_privilege(self.domain, DEFAULT_EXPORT_SETTINGS): self.helper.layout.append( crispy.Div( crispy.Fieldset( _("Edit Default Form Export Settings"), crispy.Div( crispy.Field('forms_filetype'), ), PrependedText('forms_auto_convert', ''), PrependedText('forms_auto_format_cells', ''), PrependedText('forms_expand_checkbox', ''), ), crispy.Fieldset( _("Edit Default Case Export Settings"), crispy.Div( crispy.Field('cases_filetype') ), PrependedText('cases_auto_convert', ''), ), crispy.Fieldset( _("Edit Default OData Export Settings"), PrependedText('odata_expand_checkbox', ''), ), ) ) self.helper.layout.append( hqcrispy.FormActions( StrictButton( _("Update Enterprise Settings"), type="submit", css_class='btn-primary', ) ) ) def clean_restrict_signup_message(self): message = self.cleaned_data['restrict_signup_message'] if self.cleaned_data['restrict_signup'] and not message: raise ValidationError(_("If restricting signups, a message is required.")) return message def save(self, account): account.restrict_domain_creation = self.cleaned_data.get('restrict_domain_creation', False) account.restrict_signup = self.cleaned_data.get('restrict_signup', False) account.restrict_signup_message = self.cleaned_data.get('restrict_signup_message', '') account.save() if self.export_settings and domain_has_privilege(self.domain, DEFAULT_EXPORT_SETTINGS): # forms self.export_settings.forms_filetype = self.cleaned_data.get( 'forms_filetype', self.export_settings.forms_filetype ) self.export_settings.forms_auto_convert = self.cleaned_data.get( 'forms_auto_convert', self.export_settings.forms_auto_convert ) self.export_settings.forms_auto_format_cells = self.cleaned_data.get( 'forms_auto_format_cells', self.export_settings.forms_auto_format_cells ) self.export_settings.forms_expand_checkbox = self.cleaned_data.get( 'forms_expand_checkbox', self.export_settings.forms_expand_checkbox ) # cases self.export_settings.cases_filetype = self.cleaned_data.get( 'cases_filetype', self.export_settings.cases_filetype ) self.export_settings.cases_auto_convert = self.cleaned_data.get( 'cases_auto_convert', self.export_settings.cases_auto_convert ) # odata self.export_settings.odata_expand_checkbox = self.cleaned_data.get( 'odata_expand_checkbox', self.export_settings.odata_expand_checkbox ) self.export_settings.save() return True class EnterpriseManageMobileWorkersForm(forms.Form): enable_auto_deactivation = forms.BooleanField( label=gettext_lazy("Auto-Deactivation by Inactivity"), widget=BootstrapCheckboxInput( inline_label=gettext_lazy( "Automatically deactivate Mobile Workers who have not " "submitted a form within the Inactivity Period below." ), ), required=False, ) inactivity_period = forms.ChoiceField( label=gettext_lazy("Inactivity Period"), required=False, initial=90, choices=( (30, gettext_lazy("30 days")), (60, gettext_lazy("60 days")), (90, gettext_lazy("90 days")), (120, gettext_lazy("120 days")), (150, gettext_lazy("150 days")), (180, gettext_lazy("180 days")), ), help_text=gettext_lazy( "Mobile workers who have not submitted a form after these many " "days will be considered inactive." ), ) allow_custom_deactivation = forms.BooleanField( label=gettext_lazy("Auto-Deactivation by Month"), required=False, widget=BootstrapCheckboxInput( inline_label=gettext_lazy( "Allow auto-deactivation of Mobile Workers after " "a specific month." ), ), help_text=gettext_lazy( "When this is enabled, an option to select a month and " "year for deactivating a Mobile Worker will be present when " "creating that Mobile Worker." ), ) def __init__(self, *args, **kwargs): self.emw_settings = kwargs.pop('emw_settings', None) self.domain = kwargs.pop('domain', None) kwargs['initial'] = { "enable_auto_deactivation": self.emw_settings.enable_auto_deactivation, "inactivity_period": self.emw_settings.inactivity_period, "allow_custom_deactivation": self.emw_settings.allow_custom_deactivation, } super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_id = 'emw-settings-form' self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-sm-3 col-md-2' self.helper.field_class = 'col-sm-9 col-md-8 col-lg-6' self.helper.layout = crispy.Layout( crispy.Fieldset( _("Manage Mobile Workers"), PrependedText('enable_auto_deactivation', ''), crispy.Div( crispy.Field('inactivity_period'), ), PrependedText('allow_custom_deactivation', ''), ), hqcrispy.FormActions( StrictButton( _("Update Settings"), type="submit", css_class='btn-primary', ) ) ) def update_settings(self): self.emw_settings.enable_auto_deactivation = self.cleaned_data['enable_auto_deactivation'] self.emw_settings.inactivity_period = self.cleaned_data['inactivity_period'] self.emw_settings.allow_custom_deactivation = self.cleaned_data['allow_custom_deactivation'] self.emw_settings.save() for domain in self.emw_settings.account.get_domains(): self.emw_settings.clear_domain_caches(domain)
bsd-3-clause
aa0c70408eff1a2c4ac7f37a73a810ca
40.460064
113
0.579795
4.451801
false
false
false
false
dimagi/commcare-hq
corehq/form_processor/management/commands/check_forms_have_xml.py
1
1826
import csv from django.core.management.base import BaseCommand from corehq.blobs import get_blob_db from corehq.form_processor.models import XFormInstance from corehq.util.log import with_progress_bar from couchforms.const import ATTACHMENT_NAME class Command(BaseCommand): help = "Check if there is form.xml in all forms for a domain." def add_arguments(self, parser): parser.add_argument('domains', nargs="*", help='Domains to check.') parser.add_argument('file_name', help='Location to put the output.') def handle(self, domains, file_name, **options): blob_db = get_blob_db() with open(file_name, 'w', encoding='utf-8') as csv_file: field_names = ['domain', 'archived', 'form_id', 'received_on'] csv_writer = csv.DictWriter(csv_file, field_names) csv_writer.writeheader() for domain in domains: self.stdout.write("Handling domain %s" % domain) form_ids = XFormInstance.objects.get_form_ids_in_domain(domain) form_ids.extend(XFormInstance.objects.get_form_ids_in_domain(domain, 'XFormArchived')) forms = XFormInstance.objects.iter_forms(form_ids, domain) for form in with_progress_bar(forms, len(form_ids)): meta = form.get_attachment_meta(ATTACHMENT_NAME) if not meta or not blob_db.exists(key=meta.key): self.write_row(csv_writer, domain, form.is_archived, form.received_on, form.form_id) @staticmethod def write_row(writer, domain, archived, received_on, form_id): properties = { 'domain': domain, 'archived': archived, 'received_on': received_on, 'form_id': form_id, } writer.writerow(properties)
bsd-3-clause
2ab9f49c36380609a50ba5b914643eb6
43.536585
108
0.624863
3.757202
false
false
false
false
dimagi/commcare-hq
corehq/apps/case_importer/tracking/views.py
1
5365
from django.db import transaction from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, StreamingHttpResponse, ) from dimagi.utils.web import json_response from django.views.decorators.http import require_GET from corehq.apps.case_importer.base import location_safe_case_imports_enabled from corehq.apps.case_importer.tracking.dbaccessors import ( get_case_ids_for_case_upload, get_case_upload_records, get_form_ids_for_case_upload, ) from corehq.apps.case_importer.tracking.jsmodels import ( case_upload_to_user_json, ) from corehq.apps.case_importer.tracking.models import ( MAX_COMMENT_LENGTH, CaseUploadRecord, ) from corehq.apps.case_importer.tracking.permissions import ( user_may_update_comment, user_may_view_file_upload, ) from corehq.apps.case_importer.views import require_can_edit_data from corehq.apps.domain.decorators import api_auth from corehq.apps.locations.permissions import conditionally_location_safe from corehq.util.view_utils import set_file_download @require_can_edit_data @conditionally_location_safe(location_safe_case_imports_enabled) def case_uploads(request, domain): try: limit = int(request.GET.get('limit')) except (TypeError, ValueError): limit = 10 try: page = int(request.GET.get('page')) except (TypeError, ValueError): page = 1 query = request.GET.get('query', '') case_upload_records = get_case_upload_records(domain, request.couch_user, limit, skip=limit * (page - 1), query=query) with transaction.atomic(): for case_upload_record in case_upload_records: case_upload_record.save_task_status_json_if_failed() case_uploads_json = [case_upload_to_user_json(case_upload_record, request) for case_upload_record in case_upload_records] return json_response(case_uploads_json) @api_auth @require_GET @require_can_edit_data @conditionally_location_safe(location_safe_case_imports_enabled) def case_upload_status(request, domain, upload_id): try: case_upload = _get_case_upload_record(domain, upload_id, request.couch_user) except CaseUploadRecord.DoesNotExist: return HttpResponseNotFound() return json_response(case_upload.get_task_status_json()) @require_can_edit_data @conditionally_location_safe(location_safe_case_imports_enabled) def update_case_upload_comment(request, domain, upload_id): try: case_upload = _get_case_upload_record(domain, upload_id, request.couch_user) except CaseUploadRecord.DoesNotExist: return HttpResponseNotFound() if not user_may_update_comment(request.couch_user, case_upload): return HttpResponseForbidden() comment = request.POST.get('comment') if comment is None: return HttpResponseBadRequest("POST body must contain non-null comment property") elif len(comment) > MAX_COMMENT_LENGTH: return HttpResponseBadRequest("comment must be shorter than {} characters" .format(MAX_COMMENT_LENGTH)) case_upload.comment = comment case_upload.save() return json_response({}) @require_can_edit_data @conditionally_location_safe(location_safe_case_imports_enabled) def case_upload_file(request, domain, upload_id): try: case_upload = _get_case_upload_record(domain, upload_id, request.couch_user) except CaseUploadRecord.DoesNotExist: return HttpResponseNotFound() if not user_may_view_file_upload(domain, request.couch_user, case_upload): return HttpResponseForbidden() response = StreamingHttpResponse(open(case_upload.get_tempfile_ref_for_upload_ref(), 'rb')) set_file_download(response, case_upload.upload_file_meta.filename) return response @require_can_edit_data @conditionally_location_safe(location_safe_case_imports_enabled) def case_upload_form_ids(request, domain, upload_id): try: case_upload = _get_case_upload_record(domain, upload_id, request.couch_user) except CaseUploadRecord.DoesNotExist: return HttpResponseNotFound() ids_stream = ('{}\n'.format(form_id) for form_id in get_form_ids_for_case_upload(case_upload)) response = StreamingHttpResponse(ids_stream, content_type='text/plain') set_file_download(response, f"{domain}-case_upload-form_ids.txt") return response @require_can_edit_data @conditionally_location_safe(location_safe_case_imports_enabled) def case_upload_case_ids(request, domain, upload_id): try: case_upload = _get_case_upload_record(domain, upload_id, request.couch_user) except CaseUploadRecord.DoesNotExist: return HttpResponseNotFound() ids_stream = ('{}\n'.format(case_id) for case_id in get_case_ids_for_case_upload(case_upload)) response = StreamingHttpResponse(ids_stream, content_type='text/plain') set_file_download(response, f"{domain}-case_upload-case_ids.txt") return response def _get_case_upload_record(domain, upload_id, user): kwargs = { 'domain': domain, 'upload_id': upload_id, } if not user.has_permission(domain, 'access_all_locations'): kwargs['couch_user_id'] = user._id return CaseUploadRecord.objects.get(**kwargs)
bsd-3-clause
24d80b91d0dfa747e834cab074875d87
33.837662
95
0.705871
3.694904
false
false
false
false
dimagi/commcare-hq
corehq/apps/cachehq/mixins.py
1
2872
import logging from django.conf import settings from couchdbkit import ResourceNotFound from dimagi.utils.couch.cache import cache_core from corehq.apps.cachehq.invalidate import invalidate_document from corehq.util.quickcache import quickcache class _InvalidateCacheMixin(object): def clear_caches(self): invalidate_document(self) def save(self, **params): try: super(_InvalidateCacheMixin, self).save(**params) finally: self.clear_caches() @classmethod def save_docs(cls, docs, use_uuids=True): super(_InvalidateCacheMixin, cls).save_docs(docs, use_uuids) for doc in docs: doc.clear_caches() bulk_save = save_docs def delete(self, *args, **kw): id = self._id try: super(_InvalidateCacheMixin, self).delete(*args, **kw) except ResourceNotFound: # it was already deleted. this isn't a problem, but might be a caching bug logging.exception('Tried to delete cached doc %s but it was already deleted', id) self._doc['_id'] = id self.clear_caches() invalidate_document(self, deleted=True) @classmethod def delete_docs(cls, docs, empty_on_delete=False): super(_InvalidateCacheMixin, cls).bulk_delete( docs, empty_on_delete=empty_on_delete) for doc in docs: doc.clear_caches() invalidate_document(doc, deleted=True) bulk_delete = delete_docs def dont_cache_docs(*args, **kwargs): if kwargs.get(dont_cache_docs.__name__): return True if settings.UNIT_TESTING: return False return not getattr(settings, 'COUCH_CACHE_DOCS', True) class QuickCachedDocumentMixin(_InvalidateCacheMixin): def clear_caches(self): super(QuickCachedDocumentMixin, self).clear_caches() if getattr(self, '_id', False): self.get.clear(self.__class__, self._id) @classmethod @quickcache(['cls.__name__', 'doc_id'], skip_arg=dont_cache_docs) def get(cls, doc_id, *args, dont_cache_docs=False, **kwargs): return super(QuickCachedDocumentMixin, cls).get(doc_id, *args, **kwargs) class CachedCouchDocumentMixin(QuickCachedDocumentMixin): """ A mixin for Documents that's meant to be used to enable generationally cached access in front of couch. """ @classmethod def view(cls, view_name, wrapper=None, dynamic_properties=None, wrap_doc=True, classes=None, **params): wrapper = wrapper or cls.wrap if dynamic_properties is None and wrap_doc and classes is None: return cache_core.cached_view(cls.get_db(), view_name, wrapper, **params) else: return super(CachedCouchDocumentMixin, cls).view( view_name, wrapper, dynamic_properties, wrap_doc, classes, **params )
bsd-3-clause
a0ace071170a8354b047018022cd50f4
30.911111
107
0.647632
3.881081
false
false
false
false
dimagi/commcare-hq
corehq/apps/translations/integrations/transifex/parser.py
1
7080
import re from datetime import datetime from tempfile import NamedTemporaryFile from memoized import memoized from openpyxl import Workbook from corehq.apps.dump_reload.const import DATETIME_FORMAT from corehq.apps.translations.const import MODULES_AND_FORMS_SHEET_NAME CONTEXT_REGEXS = { # Module or Form: sheet name for module/form: unique id 'module_and_forms_sheet': r'^(Module|Form):(\w+):(\w+)$', # maintain legacy module usage instead of menu # case property: list/detail 'module_sheet': r'^(.+):(list|detail)$', } TRANSIFEX_MODULE_RESOURCE_NAME = re.compile(r'^module_(\w+)(_v\d+)?$') # module_moduleUniqueID_v123 TRANSIFEX_FORM_RESOURCE_NAME = re.compile(r'^form_(\w+)(_v\d+)?$') # form_formUniqueID_v123 class TranslationsParser(object): def __init__(self, transifex): self.transifex = transifex self.key_lang_str = '{}{}'.format(self.transifex.lang_prefix, self.transifex.key_lang) self.source_lang_str = '{}{}'.format(self.transifex.lang_prefix, self.transifex.source_lang) @property @memoized def get_app(self): from corehq.apps.app_manager.dbaccessors import get_current_app app_build_id = self.transifex.build_id return get_current_app(self.transifex.domain, app_build_id) def _add_sheet(self, ws, po_entries): """ :param ws: workbook sheet object :param po_entries: list of POEntry Objects to read translations from """ sheet_name = ws.title if sheet_name == MODULES_AND_FORMS_SHEET_NAME: self._add_module_and_form_sheet(ws, po_entries) elif 'menu' in sheet_name and 'form' not in sheet_name: self._add_module_sheet(ws, po_entries) elif 'menu' in sheet_name and 'form' in sheet_name: self._add_form_sheet(ws, po_entries) else: raise Exception("Got unexpected sheet name %s" % sheet_name) def _add_module_and_form_sheet(self, ws, po_entries): context_regex = CONTEXT_REGEXS['module_and_forms_sheet'] # add header ws.append(["Type", "menu_or_form", self.key_lang_str, self.source_lang_str, 'unique_id']) # add rows for po_entry in po_entries: context = po_entry.msgctxt _type, _sheet_name, _unique_id = re.match(context_regex, context).groups() # replace the legacy module notation with new menu notation ws.append([_type.replace('Module', 'Menu'), _sheet_name.replace('module', 'menu'), po_entry.msgid, po_entry.msgstr, _unique_id]) @staticmethod def _get_rows_for_module_sheet(consolidated_po_entries): """ get po_entries listed according to their expected order in the final set by using occurrences """ rows = {} # align entries in a dict with their index as the key for po_entry in consolidated_po_entries: occurrences = po_entry.occurrences for occurrence in occurrences: index = int(occurrence[1]) rows[index] = po_entry # ensure the number of final translations is same as the highest index # if rows: # ToDo: Add this message # if len(rows) != int(max(rows.keys())): # add a message for the user # sort by index to have the expected order return [po_entry for i, po_entry in sorted(rows.items())] def _add_module_sheet(self, ws, po_entries): context_regex = CONTEXT_REGEXS['module_sheet'] # add header ws.append(["case_property", "list_or_detail", self.key_lang_str, self.source_lang_str]) for po_entry in self._get_rows_for_module_sheet(po_entries): context = po_entry.msgctxt _case_property, _list_or_detail = re.match(context_regex, context).groups() ws.append([_case_property, _list_or_detail, po_entry.msgid, po_entry.msgstr]) def _add_form_sheet(self, ws, po_entries): # add header ws.append(["label", self.key_lang_str, self.source_lang_str]) # add rows for po_entry in po_entries: _label = po_entry.msgctxt ws.append([_label, po_entry.msgid, po_entry.msgstr]) @memoized def _result_file_name(self): return ("TransifexTranslations {}-{}:v{} {}.xlsx".format( self.transifex.key_lang, self.transifex.source_lang, self.transifex.version, datetime.utcnow().strftime(DATETIME_FORMAT)) ) def _generate_form_sheet_name(self, form_unique_id): """ receive a form unique id and convert into name with module and form index as expected by HQ :param form_unique_id: :return: """ form = self.get_app.get_form(form_unique_id) _module = form.get_module() module_index = self.get_app.get_module_index(_module.unique_id) + 1 form_index = _module.get_form_index(form_unique_id) + 1 return "menu%s_form%s" % (module_index, form_index) def _get_sheet_name_with_indexes(self, resource_slug): """ receives resource slug from transifex trimmed of version postfix and update to sheet name with module/form indexes as expected by HQ :param resource_slug: name like module_moduleUniqueID or form_formUniqueID :return: name like module1 or module1_form1 """ if resource_slug == MODULES_AND_FORMS_SHEET_NAME: return resource_slug module_sheet_name_match = TRANSIFEX_MODULE_RESOURCE_NAME.match(resource_slug) if module_sheet_name_match: module_unique_id = module_sheet_name_match.groups()[0] module_index = self.get_app.get_module_index(module_unique_id) + 1 return "menu%s" % module_index form_sheet_name_match = TRANSIFEX_FORM_RESOURCE_NAME.match(resource_slug) if form_sheet_name_match: form_unique_id = form_sheet_name_match.groups()[0] return self._generate_form_sheet_name(form_unique_id) raise Exception("Got unexpected sheet name %s" % resource_slug) def _get_sheet_name(self, resource_slug): """ receives resource slug and converts to excel sheet name as expected by HQ :param resource_slug: like module_moduleUniqueID_v15 or form_formUniqueID :return: name like menu1 or menu1_form1 """ resource_slug = resource_slug.split("_v%s" % self.transifex.version)[0] return self._get_sheet_name_with_indexes(resource_slug) def _generate_sheets(self, wb): for resource_name, po_entries in self.transifex.get_translations().items(): ws = wb.create_sheet(title=self._get_sheet_name(resource_name)) self._add_sheet(ws, po_entries) def generate_excel_file(self): wb = Workbook(write_only=True) self._generate_sheets(wb) with NamedTemporaryFile(delete=False) as tempfile: wb.save(tempfile) return tempfile, self._result_file_name()
bsd-3-clause
3ac3505a37fd1a94e27234efcafc5afd
42.170732
109
0.627684
3.588444
false
false
false
false
onepercentclub/bluebottle
bluebottle/payouts_dorado/tests/test_adapter.py
1
1743
from datetime import timedelta import requests from django.test.utils import override_settings from django.utils.timezone import now from moneyed.classes import Money from bluebottle.funding.tests.factories import FundingFactory, DonorFactory from bluebottle.funding_pledge.tests.factories import PledgePaymentFactory from bluebottle.payouts_dorado.adapters import DoradoPayoutAdapter from bluebottle.test.utils import BluebottleTestCase class TestPayoutAdapter(BluebottleTestCase): """ Test Payout Adapter """ def setUp(self): super(TestPayoutAdapter, self).setUp() self.funding = FundingFactory.create(target=Money(500, 'EUR'), status='open') donations = DonorFactory.create_batch( 7, activity=self.funding, amount=Money(100, 'EUR')) for donation in donations: PledgePaymentFactory.create(donation=donation) yesterday = now() - timedelta(days=1) self.funding.deadline = yesterday self.funding.save() self.mock_response = requests.Response() self.mock_response.status_code = 200 self.adapter = DoradoPayoutAdapter(self.funding) @override_settings(PAYOUT_SERVICE={'url': 'http://example.com'}) def test_payouts_created_trigger_called(self): """ Check trigger to service is been called. """ pass # with patch('requests.post', return_value=self.mock_response) as request_mock: # self.funding.transitions.succeed() # FIXME ! # Test that the adapater will trigger a call to Payout app when Funding is succeeded. # request_mock.assert_called_once_with('test', {'project_id': self.funding.id, 'tenant': u'test'})
bsd-3-clause
713ee1e45f1b4b1125da795168d94de1
35.3125
106
0.687321
3.847682
false
true
false
false
dimagi/commcare-hq
scripts/purge-platform-pkgs.py
1
2040
#!/usr/bin/env python """Strip unwanted packages out of pip-compiled requirements txt files. TODO: - support packages with multiple via's - accept purge package details via --package argument instead of global dict """ import argparse import sys from collections import deque PACKAGES_TO_PURGE = { # package, via "appnope": "ipython", } def main(files, packages=PACKAGES_TO_PURGE): for file in files: # Ideally these things are less than GiB's in size, because we're gonna # have a few copies in memory :) lines = list(file) purged = list(purge_packages(lines, packages)) if file.fileno() == 0: # stdin # always write these lines to stdout, regardless of purge rewrite_lines(sys.stdout, purged) elif lines != purged: file.close() with open(file.name, "w") as outfile: rewrite_lines(outfile, purged) def purge_packages(lines, packages): """Iterates over a collection of requirements `lines`, yielding all lines except those matching `packages`. :param lines: iterable of requirement file lines :param packages: dictionary of packages to purge """ stack = deque(lines) while stack: line = stack.popleft() name, delim, tail = line.partition("=") if delim and name in packages and stack: next_line = stack.popleft() # pop the "via" line if next_line.strip() == f"# via {packages[name]}": continue # skip both lines stack.insert(0, next_line) # nope, put it back yield line def rewrite_lines(file, lines): sys.stderr.write(f"re-writing {file.name!r}\n") file.writelines(lines) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("files", metavar="FILE", nargs="+", type=argparse.FileType("r"), help="purge packages from compiled python requirements %(metavar)s(s), " "use - to read from STDIN") main(parser.parse_args().files)
bsd-3-clause
34f2a9cc2a5fb72cce5de26c298c2256
31.380952
88
0.632353
3.953488
false
false
false
false
onepercentclub/bluebottle
bluebottle/projects/migrations/0038_auto_20170915_1358.py
1
1363
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2017-09-15 11:58 from __future__ import unicode_literals import bluebottle.utils.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('projects', '0037_auto_20170915_1350'), ] operations = [ migrations.AlterModelOptions( name='projectimage', options={'permissions': (('api_read_projectimage', 'Can view project images through the API'), ('api_add_projectimage', 'Can add project images through the API'), ('api_change_projectimage', 'Can change project images through the API'), ('api_delete_projectimage', 'Can delete project images through the API'), ('api_read_own_projectimage', 'Can view own project images through the API'), ('api_add_own_projectimage', 'Can add own project images through the API'), ('api_change_own_projectimage', 'Can change own project images through the API'), ('api_delete_own_projectimage', 'Can delete own project images through the API')), 'verbose_name': 'project image', 'verbose_name_plural': 'project images'}, ), migrations.AlterField( model_name='projectdocument', name='file', field=bluebottle.utils.fields.PrivateFileField(max_length=110, upload_to=b'private/private/private/projects/documents'), ), ]
bsd-3-clause
a16904915fa1604b896e8e4dc91f375f
53.52
716
0.684519
3.883191
false
false
false
false
onepercentclub/bluebottle
bluebottle/impact/tests/test_api.py
1
9883
# coding=utf-8 from builtins import str import json from django.contrib.auth.models import Group, Permission from django.urls import reverse from rest_framework import status from bluebottle.impact.models import ImpactGoal from bluebottle.impact.tests.factories import ( ImpactTypeFactory, ImpactGoalFactory ) from bluebottle.time_based.tests.factories import DateActivityFactory from bluebottle.members.models import MemberPlatformSettings from bluebottle.test.factory_models.accounts import BlueBottleUserFactory from bluebottle.test.utils import BluebottleTestCase, JSONAPITestClient class ImpactTypeListAPITestCase(BluebottleTestCase): def setUp(self): super(ImpactTypeListAPITestCase, self).setUp() self.client = JSONAPITestClient() self.types = ImpactTypeFactory.create_batch(10) self.url = reverse('impact-type-list') self.user = BlueBottleUserFactory() def test_get(self): response = self.client.get(self.url, user=self.user) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.json()['data']), len(self.types)) resource = response.json()['data'][0]['attributes'] self.assertTrue('slug' in resource) self.assertTrue('name' in resource) self.assertTrue('unit' in resource) self.assertTrue('text' in resource) self.assertTrue('text-with-target' in resource) self.assertTrue('text-passed' in resource) resource_type = response.json()['data'][0]['type'] self.assertEqual(resource_type, 'activities/impact-types') def test_get_anonymous(self): response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.json()['data']), len(self.types)) def test_get_only_active(self): self.types[0].active = False self.types[0].save() response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.json()['data']), len(self.types) - 1) def test_get_closed(self): MemberPlatformSettings.objects.update(closed=True) response = self.client.get(self.url, user=self.user) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_closed_anonymous(self): MemberPlatformSettings.objects.update(closed=True) response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_post(self): response = self.client.post(self.url, user=self.user) self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) class ImpactGoalListAPITestCase(BluebottleTestCase): def setUp(self): super(ImpactGoalListAPITestCase, self).setUp() self.client = JSONAPITestClient() self.activity = DateActivityFactory.create() self.type = ImpactTypeFactory.create() self.url = reverse('impact-goal-list') self.data = { 'data': { 'type': 'activities/impact-goals', 'attributes': { 'target': 1.5 }, 'relationships': { 'activity': { 'data': { 'type': 'activities/time-based/dates', 'id': self.activity.pk }, }, 'type': { 'data': { 'type': 'activities/impact-types', 'id': self.type.pk }, } } } } def test_create(self): response = self.client.post( self.url, json.dumps(self.data), user=self.activity.owner ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) resource_type = response.json()['data']['type'] self.assertEqual(resource_type, 'activities/impact-goals') goal = ImpactGoal.objects.get(pk=response.json()['data']['id']) self.assertEqual( goal.target, self.data['data']['attributes']['target'] ) self.assertEqual(goal.type, self.type) self.assertEqual(goal.activity, self.activity) def test_create_no_target(self): del self.data['data']['attributes']['target'] response = self.client.post( self.url, json.dumps(self.data), user=self.activity.owner ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) resource_type = response.json()['data']['type'] self.assertEqual(resource_type, 'activities/impact-goals') goal = ImpactGoal.objects.get(pk=response.json()['data']['id']) self.assertEqual( goal.target, None ) self.assertEqual(goal.type, self.type) self.assertEqual(goal.activity, self.activity) def test_create_non_owner(self): response = self.client.post( self.url, json.dumps(self.data), user=BlueBottleUserFactory.create() ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_create_anonymous(self): response = self.client.post( self.url, json.dumps(self.data), ) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) class ImpactGoalDetailsAPITestCase(BluebottleTestCase): def setUp(self): super(ImpactGoalDetailsAPITestCase, self).setUp() self.client = JSONAPITestClient() self.activity = DateActivityFactory.create() self.type = ImpactTypeFactory.create() self.goal = ImpactGoalFactory(type=self.type, activity=self.activity) self.url = reverse('impact-goal-details', args=(self.goal.pk, )) self.data = { 'data': { 'type': 'activities/impact-goals', 'id': self.goal.pk, 'attributes': { 'target': 1.5 }, } } def test_get(self): response = self.client.get( self.url, user=self.activity.owner ) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json()['data'] self.assertEqual(data['type'], 'activities/impact-goals') self.assertEqual( data['attributes']['target'], self.goal.target ) self.assertEqual( data['relationships']['type']['data']['id'], str(self.goal.type.pk) ) self.assertEqual( data['relationships']['activity']['data']['id'], str(self.goal.activity.pk) ) def test_get_incomplete(self): self.goal.target = None self.goal.save() response = self.client.get( self.url, user=self.activity.owner ) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json()['data'] self.assertEqual(data['meta']['required'], []) def test_get_non_owner(self): response = self.client.get( self.url, user=BlueBottleUserFactory.create() ) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_anonymous(self): response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_get_closed_anonymous(self): anonymous = Group.objects.get(name='Anonymous') anonymous.permissions.remove( Permission.objects.get(codename='api_read_dateactivity') ) MemberPlatformSettings.objects.update(closed=True) response = self.client.get(self.url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_update(self): response = self.client.patch( self.url, data=json.dumps(self.data), user=self.activity.owner ) self.assertEqual(response.status_code, status.HTTP_200_OK) data = response.json()['data'] self.assertEqual(data['type'], 'activities/impact-goals') self.assertEqual( data['attributes']['target'], self.data['data']['attributes']['target'] ) self.goal.refresh_from_db() self.assertEqual( self.goal.target, self.data['data']['attributes']['target'] ) def test_update_other_user(self): response = self.client.patch( self.url, data=json.dumps(self.data), user=BlueBottleUserFactory.create() ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_update_anonymous(self): response = self.client.patch( self.url, data=json.dumps(self.data) ) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) def test_delete(self): response = self.client.delete( self.url, user=self.activity.owner ) self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) with self.assertRaises(ImpactGoal.DoesNotExist): ImpactGoal.objects.get(pk=self.goal.pk) def test_delete_other_user(self): response = self.client.delete( self.url, user=BlueBottleUserFactory.create() ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_delete_anonymous(self): response = self.client.delete(self.url) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
bsd-3-clause
3d7b071bb96b80f6c6828c1e96145b83
32.276094
82
0.598199
4.083884
false
true
false
false
onepercentclub/bluebottle
bluebottle/activities/migrations/0015_auto_20200128_1045.py
1
1320
# -*- coding: utf-8 -*- # Generated by Django 1.11.15 on 2020-01-28 09:45 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('activities', '0014_add_permissions'), ] operations = [ migrations.AddField( model_name='contribution', name='contribution_date', field=models.DateTimeField(default=django.utils.timezone.now), preserve_default=False, ), migrations.AlterField( model_name='activity', name='transition_date', field=models.DateTimeField(blank=True, help_text='Date the contribution took place.', null=True, verbose_name='contribution date'), ), migrations.AlterField( model_name='contribution', name='transition_date', field=models.DateTimeField(blank=True, null=True), ), migrations.AlterField( model_name='contribution', name='user', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='user'), ), ]
bsd-3-clause
ac40a895dc10077b6907a56f333c14f1
32.846154
154
0.627273
4.313725
false
false
false
false
dimagi/commcare-hq
corehq/messaging/smsbackends/turn/views.py
1
1197
import json from corehq.apps.sms.api import incoming as incoming_sms from corehq.apps.sms.views import IncomingBackendView from corehq.messaging.smsbackends.turn.models import SQLTurnWhatsAppBackend from django.http import HttpResponse class TurnIncomingSMSView(IncomingBackendView): urlname = 'turn_sms' @property def backend_class(self): return SQLTurnWhatsAppBackend def post(self, request, api_key, *args, **kwargs): request_body = json.loads(request.body) for message in request_body.get('messages', []): message_id = message.get('id') from_ = message.get('from') if message.get('type') == 'text': body = message.get('text', {}).get('body') elif message.get('type') == 'image': body = message.get('image', {}).get('caption') # this doesn't seem to work yet incoming_sms( from_, body, SQLTurnWhatsAppBackend.get_api_id(), backend_message_id=message_id, domain_scope=self.domain, backend_id=self.backend_couch_id ) return HttpResponse("")
bsd-3-clause
1676d4a4f4201946d5d3353dd267c79e
34.205882
95
0.596491
4.071429
false
false
false
false
dimagi/commcare-hq
corehq/apps/reports/filters/devicelog.py
1
3212
from django.urls import reverse from django.utils.translation import gettext_lazy from phonelog.models import DeviceReportEntry from corehq.apps.reports.filters.base import ( BaseMultipleOptionFilter, BaseReportFilter, BaseSingleOptionFilter, BaseTagsFilter, ) from corehq.util.queries import fast_distinct, fast_distinct_in_domain from corehq.util.quickcache import quickcache class DeviceLogTagFilter(BaseReportFilter): slug = "logtag" label = gettext_lazy("Filter Logs by Tag") errors_only_slug = "errors_only" template = "reports/filters/devicelog_tags.html" @quickcache(['self.domain'], timeout=10 * 60) def _all_values(self): return fast_distinct_in_domain(DeviceReportEntry, 'type', self.domain) @property def filter_context(self): errors_only = bool(self.request.GET.get(self.errors_only_slug, False)) selected_tags = self.request.GET.getlist(self.slug) show_all = bool(not selected_tags) values = self._all_values() tags = [{ 'name': value, 'show': bool(show_all or value in selected_tags) } for value in values] context = { 'errors_only_slug': self.errors_only_slug, 'default_on': show_all, 'logtags': tags, 'errors_css_id': 'device-log-errors-only-checkbox', self.errors_only_slug: errors_only, } return context class DeviceLogDomainFilter(BaseSingleOptionFilter): slug = "domain" label = gettext_lazy("Filter Logs by Domain") @property @quickcache([], timeout=60 * 60) def options(self): return [(d, d) for d in fast_distinct(DeviceReportEntry, 'domain')] class DeviceLogCommCareVersionFilter(BaseTagsFilter): slug = "commcare_version" label = gettext_lazy("Filter Logs by CommCareVersion") placeholder = gettext_lazy("Enter the CommCare Version you want e.g '2.28.1'") class BaseDeviceLogFilter(BaseMultipleOptionFilter): slug = "logfilter" field = None label = gettext_lazy("Filter Logs By") url_param_map = {'Unknown': None} endpoint = None @property def filter_context(self): selected = self.get_selected(self.request) url = reverse(self.endpoint, args=[self.domain]) return { 'default_on': bool(not selected), 'endpoint': url, } @classmethod def get_selected(cls, request): return [cls.param_to_value(param) for param in request.GET.getlist(cls.slug)] @classmethod def param_to_value(cls, param): return cls.url_param_map.get(param, param) @classmethod def value_to_param(cls, value): for param, value_ in cls.url_param_map.items(): if value_ == value: return param return value class DeviceLogUsersFilter(BaseDeviceLogFilter): slug = "loguser" label = gettext_lazy("Filter Logs by Username") field = 'username' endpoint = 'device_log_users' class DeviceLogDevicesFilter(BaseDeviceLogFilter): slug = "logdevice" label = gettext_lazy("Filter Logs by Device") field = 'device_id' endpoint = 'device_log_ids'
bsd-3-clause
59902eefae9edceba54e49cce447bf3f
29.301887
82
0.650374
3.769953
false
false
false
false
onepercentclub/bluebottle
bluebottle/projects/migrations/0046_auto_20171023_2047.py
1
1344
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2017-10-23 18:47 from __future__ import unicode_literals import bluebottle.utils.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0045_auto_20171023_2013'), ] operations = [ migrations.RenameField( model_name='projectplatformsettings', old_name='project_contact_method', new_name='contact_method', ), migrations.RenameField( model_name='projectplatformsettings', old_name='project_create_flow', new_name='create_flow', ), migrations.RenameField( model_name='projectplatformsettings', old_name='project_create_types', new_name='create_types', ), migrations.RenameField( model_name='projectplatformsettings', old_name='project_suggestions', new_name='suggestions', ), migrations.AlterField( model_name='projectsearchfilter', name='project_settings', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='filters', to='projects.ProjectPlatformSettings'), ), ]
bsd-3-clause
e928cc8596d615529adba77357e2f365
31
155
0.608631
4.37785
false
false
false
false
onepercentclub/bluebottle
bluebottle/funding/base_serializers.py
1
1473
from builtins import object from rest_framework.serializers import ModelSerializer from rest_framework_json_api.relations import ResourceRelatedField from bluebottle.funding.models import Donor, Payment, BankAccount, PayoutAccount from bluebottle.transitions.serializers import AvailableTransitionsField from bluebottle.utils.fields import FSMField class PaymentSerializer(ModelSerializer): status = FSMField(read_only=True) donation = ResourceRelatedField(queryset=Donor.objects.all()) transitions = AvailableTransitionsField() included_serializers = { 'donation': 'bluebottle.funding.serializers.DonorSerializer', } class Meta(object): model = Payment fields = ('donation', 'status', ) meta_fields = ('transitions', 'created', 'updated', ) class JSONAPIMeta(object): included_resources = [ 'donation', ] resource_name = 'payments' class BaseBankAccountSerializer(ModelSerializer): status = FSMField(read_only=True) connect_account = ResourceRelatedField(queryset=PayoutAccount.objects.all()) class Meta(object): model = BankAccount fields = ( 'id', 'connect_account', 'status' ) included_serializers = { 'connect_account': 'bluebottle.funding.serializers.PayoutAccountSerializer', } class JSONAPIMeta(object): resource_name = 'payout-accounts/external-accounts'
bsd-3-clause
a2eed87a7da1985114f76ef2954f4edb
28.46
84
0.691785
4.307018
false
false
false
false
dimagi/commcare-hq
corehq/form_processor/interfaces/dbaccessors.py
1
3360
from abc import ABCMeta, abstractmethod from memoized import memoized class AbstractLedgerAccessor(metaclass=ABCMeta): @staticmethod @abstractmethod def get_transactions_for_consumption(domain, case_id, product_id, section_id, window_start, window_end): raise NotImplementedError @staticmethod @abstractmethod def get_ledger_value(case_id, section_id, entry_id): raise NotImplementedError @staticmethod @abstractmethod def get_ledger_transactions_for_case(case_id, section_id=None, entry_id=None): """ :return: List of transactions orderd by date ascending """ raise NotImplementedError @staticmethod @abstractmethod def get_latest_transaction(case_id, section_id, entry_id): raise NotImplementedError @staticmethod @abstractmethod def get_current_ledger_state(case_ids, ensure_form_id=False): """ Given a list of case IDs return a dict of all current ledger data of the following format: { case_id: { section_id: { product_id: <LedgerValue>, product_id: <LedgerValue>, ... }, ... }, ... } """ raise NotImplementedError @staticmethod @abstractmethod def get_ledger_values_for_cases(case_ids, section_ids=None, entry_ids=None, date_start=None, date_end=None): raise NotImplementedError class LedgerAccessors(object): """ Facade for Ledger DB access that proxies method calls to SQL or Couch version """ def __init__(self, domain=None): self.domain = domain @property @memoized def db_accessor(self): from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL return LedgerAccessorSQL def get_transactions_for_consumption(self, case_id, product_id, section_id, window_start, window_end): return self.db_accessor.get_transactions_for_consumption( self.domain, case_id, product_id, section_id, window_start, window_end ) def get_ledger_value(self, case_id, section_id, entry_id): return self.db_accessor.get_ledger_value(case_id, section_id, entry_id) def get_ledger_transactions_for_case(self, case_id, section_id=None, entry_id=None): return self.db_accessor.get_ledger_transactions_for_case(case_id, section_id, entry_id) def get_latest_transaction(self, case_id, section_id, entry_id): return self.db_accessor.get_latest_transaction(case_id, section_id, entry_id) def get_ledger_values_for_case(self, case_id): return self.db_accessor.get_ledger_values_for_case(case_id) def get_current_ledger_state(self, case_ids): if not case_ids: return {} return self.db_accessor.get_current_ledger_state(case_ids) def get_case_ledger_state(self, case_id, ensure_form_id=False): return self.db_accessor.get_current_ledger_state([case_id], ensure_form_id=ensure_form_id)[case_id] def get_ledger_values_for_cases(self, case_ids, section_ids=None, entry_ids=None, date_start=None, date_end=None): return self.db_accessor.get_ledger_values_for_cases(case_ids, section_ids, entry_ids, date_start, date_end)
bsd-3-clause
7ad7bd5d7f3a2ed33b06e41e45910600
33.639175
115
0.652381
3.779528
false
false
false
false
dimagi/commcare-hq
corehq/apps/enterprise/views.py
1
17321
import json from django.conf import settings from django.contrib import messages from django.core.files.base import ContentFile from django.core.paginator import Paginator from django.db.models import Sum from django.http import ( HttpResponse, HttpResponseNotFound, HttpResponseRedirect, JsonResponse, ) from django.shortcuts import render from django.urls import reverse from django.utils.decorators import method_decorator from django.utils.translation import gettext as _, gettext_lazy from django.views.decorators.http import require_POST from django_prbac.utils import has_privilege from memoized import memoized from corehq.apps.accounting.decorators import always_allow_project_access from corehq.apps.enterprise.decorators import require_enterprise_admin from corehq.apps.enterprise.mixins import ManageMobileWorkersMixin from corehq.apps.enterprise.models import ( EnterprisePermissions, EnterpriseMobileWorkerSettings, ) from corehq.apps.enterprise.tasks import clear_enterprise_permissions_cache_for_all_users from couchexport.export import Format from dimagi.utils.couch.cache.cache_core import get_redis_client from corehq import privileges from corehq.apps.accounting.models import ( CustomerInvoice, CustomerBillingRecord, BillingAccount, ) from corehq.apps.accounting.utils import get_customer_cards, quantize_accounting_decimal, log_accounting_error from corehq.apps.domain.decorators import ( login_and_domain_required, require_superuser, ) from corehq.apps.domain.views import DomainAccountingSettings, BaseDomainView from corehq.apps.domain.views.accounting import PAYMENT_ERROR_MESSAGES, InvoiceStripePaymentView, \ BulkStripePaymentView, WireInvoiceView, BillingStatementPdfView from corehq.apps.enterprise.enterprise import EnterpriseReport from corehq.apps.enterprise.forms import ( EnterpriseSettingsForm, EnterpriseManageMobileWorkersForm, ) from corehq.apps.enterprise.tasks import email_enterprise_report from corehq.apps.export.utils import get_default_export_settings_if_available from corehq.apps.hqwebapp.views import CRUDPaginatedViewMixin from corehq.apps.users.decorators import require_can_edit_or_view_web_users from corehq.const import USER_DATE_FORMAT @always_allow_project_access @require_enterprise_admin @login_and_domain_required def enterprise_dashboard(request, domain): if not has_privilege(request, privileges.PROJECT_ACCESS): return HttpResponseRedirect(reverse(EnterpriseBillingStatementsView.urlname, args=(domain,))) context = { 'account': request.account, 'domain': domain, 'reports': [EnterpriseReport.create(slug, request.account.id, request.couch_user) for slug in ( EnterpriseReport.DOMAINS, EnterpriseReport.WEB_USERS, EnterpriseReport.MOBILE_USERS, EnterpriseReport.FORM_SUBMISSIONS, EnterpriseReport.ODATA_FEEDS, )], 'current_page': { 'page_name': _('Enterprise Dashboard'), 'title': _('Enterprise Dashboard'), } } return render(request, "enterprise/enterprise_dashboard.html", context) @require_enterprise_admin @login_and_domain_required def enterprise_dashboard_total(request, domain, slug): report = EnterpriseReport.create(slug, request.account.id, request.couch_user) return JsonResponse({'total': report.total}) @require_enterprise_admin @login_and_domain_required def enterprise_dashboard_download(request, domain, slug, export_hash): report = EnterpriseReport.create(slug, request.account.id, request.couch_user) redis = get_redis_client() content = redis.get(export_hash) if content: file = ContentFile(content) response = HttpResponse(file, Format.FORMAT_DICT[Format.UNZIPPED_CSV]) response['Content-Length'] = file.size response['Content-Disposition'] = 'attachment; filename="{}"'.format(report.filename) return response return HttpResponseNotFound(_("That report was not found. Please remember that " "download links expire after 24 hours.")) @require_enterprise_admin @login_and_domain_required def enterprise_dashboard_email(request, domain, slug): report = EnterpriseReport.create(slug, request.account.id, request.couch_user) email_enterprise_report.delay(domain, slug, request.couch_user) message = _("Generating {title} report, will email to {email} when complete.").format(**{ 'title': report.title, 'email': request.couch_user.username, }) return JsonResponse({'message': message}) @require_enterprise_admin @login_and_domain_required def enterprise_settings(request, domain): export_settings = get_default_export_settings_if_available(domain) if request.method == 'POST': form = EnterpriseSettingsForm(request.POST, domain=domain, account=request.account, username=request.user.username, export_settings=export_settings) else: form = EnterpriseSettingsForm(domain=domain, account=request.account, username=request.user.username, export_settings=export_settings) context = { 'account': request.account, 'accounts_email': settings.ACCOUNTS_EMAIL, 'domain': domain, 'restrict_signup': request.POST.get('restrict_signup', request.account.restrict_signup), 'current_page': { 'title': _('Enterprise Settings'), 'page_name': _('Enterprise Settings'), }, 'settings_form': form, } return render(request, "enterprise/enterprise_settings.html", context) @require_enterprise_admin @login_and_domain_required @require_POST def edit_enterprise_settings(request, domain): export_settings = get_default_export_settings_if_available(domain) form = EnterpriseSettingsForm(request.POST, username=request.user.username, domain=domain, account=request.account, export_settings=export_settings) if form.is_valid(): form.save(request.account) messages.success(request, "Account successfully updated.") else: return enterprise_settings(request, domain) return HttpResponseRedirect(reverse('enterprise_settings', args=[domain])) @method_decorator(require_enterprise_admin, name='dispatch') class BaseEnterpriseAdminView(BaseDomainView): section_name = gettext_lazy("Enterprise Console") @property def section_url(self): return reverse('enterprise_dashboard', args=(self.domain,)) @property def page_url(self): return reverse(self.urlname, args=(self.domain,)) @method_decorator(require_enterprise_admin, name='dispatch') class EnterpriseBillingStatementsView(DomainAccountingSettings, CRUDPaginatedViewMixin): template_name = 'domain/billing_statements.html' urlname = 'enterprise_billing_statements' page_title = gettext_lazy("Billing Statements") limit_text = gettext_lazy("statements per page") empty_notification = gettext_lazy("No Billing Statements match the current criteria.") loading_message = gettext_lazy("Loading statements...") @property def stripe_cards(self): return get_customer_cards(self.request.user.username, self.domain) @property def show_hidden(self): if not self.request.user.is_superuser: return False return bool(self.request.POST.get('additionalData[show_hidden]')) @property def show_unpaid(self): try: return json.loads(self.request.POST.get('additionalData[show_unpaid]')) except TypeError: return False @property def invoices(self): invoices = CustomerInvoice.objects.filter(account=self.request.account) if not self.show_hidden: invoices = invoices.filter(is_hidden=False) if self.show_unpaid: invoices = invoices.filter(date_paid__exact=None) return invoices.order_by('-date_start', '-date_end') @property def total(self): return self.paginated_invoices.count @property @memoized def paginated_invoices(self): return Paginator(self.invoices, self.limit) @property def total_balance(self): """ Returns the total balance of unpaid, unhidden invoices. Doesn't take into account the view settings on the page. """ invoices = (CustomerInvoice.objects .filter(account=self.request.account) .filter(date_paid__exact=None) .filter(is_hidden=False)) return invoices.aggregate( total_balance=Sum('balance') ).get('total_balance') or 0.00 @property def column_names(self): return [ _("Statement No."), _("Billing Period"), _("Date Due"), _("Payment Status"), _("PDF"), ] @property def page_context(self): pagination_context = self.pagination_context pagination_context.update({ 'stripe_options': { 'stripe_public_key': settings.STRIPE_PUBLIC_KEY, 'stripe_cards': self.stripe_cards, }, 'payment_error_messages': PAYMENT_ERROR_MESSAGES, 'payment_urls': { 'process_invoice_payment_url': reverse( InvoiceStripePaymentView.urlname, args=[self.domain], ), 'process_bulk_payment_url': reverse( BulkStripePaymentView.urlname, args=[self.domain], ), 'process_wire_invoice_url': reverse( WireInvoiceView.urlname, args=[self.domain], ), }, 'total_balance': self.total_balance, 'show_plan': False }) return pagination_context @property def can_pay_invoices(self): return self.request.couch_user.is_domain_admin(self.domain) @property def paginated_list(self): for invoice in self.paginated_invoices.page(self.page).object_list: try: last_billing_record = CustomerBillingRecord.objects.filter( invoice=invoice ).latest('date_created') if invoice.is_paid: payment_status = (_("Paid on %s.") % invoice.date_paid.strftime(USER_DATE_FORMAT)) payment_class = "label label-default" else: payment_status = _("Not Paid") payment_class = "label label-danger" date_due = ( (invoice.date_due.strftime(USER_DATE_FORMAT) if not invoice.is_paid else _("Already Paid")) if invoice.date_due else _("None") ) yield { 'itemData': { 'id': invoice.id, 'invoice_number': invoice.invoice_number, 'start': invoice.date_start.strftime(USER_DATE_FORMAT), 'end': invoice.date_end.strftime(USER_DATE_FORMAT), 'plan': None, 'payment_status': payment_status, 'payment_class': payment_class, 'date_due': date_due, 'pdfUrl': reverse( BillingStatementPdfView.urlname, args=[self.domain, last_billing_record.pdf_data_id] ), 'canMakePayment': (not invoice.is_paid and self.can_pay_invoices), 'balance': "%s" % quantize_accounting_decimal(invoice.balance), }, 'template': 'statement-row-template', } except CustomerBillingRecord.DoesNotExist: log_accounting_error( "An invoice was generated for %(invoice_id)d " "(domain: %(domain)s), but no billing record!" % { 'invoice_id': invoice.id, 'domain': self.domain, }, show_stack_trace=True ) def refresh_item(self, item_id): pass def post(self, *args, **kwargs): return self.paginate_crud_response # This view, and related views, require enterprise admin permissions to be consistent # with other views in this area. They also require superuser access because these views # used to be in another part of HQ, where they were limited to superusers, and we don't # want them to be visible to any external users until we're ready to GA this feature. @require_can_edit_or_view_web_users @require_superuser @require_enterprise_admin def enterprise_permissions(request, domain): config = EnterprisePermissions.get_by_domain(domain) if not config.id: config.save() all_domains = set(config.account.get_domains()) ignored_domains = all_domains - set(config.domains) - {config.source_domain} context = { 'domain': domain, 'all_domains': sorted(all_domains), 'is_enabled': config.is_enabled, 'source_domain': config.source_domain, 'ignored_domains': sorted(list(ignored_domains)), 'controlled_domains': sorted(config.domains), 'current_page': { 'page_name': _('Enterprise Permissions'), 'title': _('Enterprise Permissions'), } } return render(request, "enterprise/enterprise_permissions.html", context) @require_superuser @require_enterprise_admin @require_POST def disable_enterprise_permissions(request, domain): config = EnterprisePermissions.get_by_domain(domain) config.is_enabled = False config.source_domain = None config.save() clear_enterprise_permissions_cache_for_all_users.delay(config.id) redirect = reverse("enterprise_permissions", args=[domain]) messages.success(request, _('Enterprise permissions have been disabled.')) return HttpResponseRedirect(redirect) @require_superuser @require_enterprise_admin @require_POST def add_enterprise_permissions_domain(request, domain, target_domain): config = EnterprisePermissions.get_by_domain(domain) redirect = reverse("enterprise_permissions", args=[domain]) if target_domain not in config.account.get_domains(): messages.error(request, _("Could not add {}.").format(target_domain)) return HttpResponseRedirect(redirect) if target_domain not in config.domains: config.domains.append(target_domain) config.save() if config.source_domain: clear_enterprise_permissions_cache_for_all_users.delay(config.id, config.source_domain) messages.success(request, _('{} is now included in enterprise permissions.').format(target_domain)) return HttpResponseRedirect(redirect) @require_superuser @require_enterprise_admin @require_POST def remove_enterprise_permissions_domain(request, domain, target_domain): config = EnterprisePermissions.get_by_domain(domain) redirect = reverse("enterprise_permissions", args=[domain]) if target_domain not in config.account.get_domains() or target_domain not in config.domains: messages.error(request, _("Could not remove {}.").format(target_domain)) return HttpResponseRedirect(redirect) if target_domain in config.domains: config.domains.remove(target_domain) config.save() if config.source_domain: clear_enterprise_permissions_cache_for_all_users.delay(config.id, config.source_domain) messages.success(request, _('{} is now excluded from enterprise permissions.').format(target_domain)) return HttpResponseRedirect(redirect) @require_superuser @require_enterprise_admin @require_POST def update_enterprise_permissions_source_domain(request, domain): source_domain = request.POST.get('source_domain') redirect = reverse("enterprise_permissions", args=[domain]) config = EnterprisePermissions.get_by_domain(domain) if source_domain not in config.account.get_domains(): messages.error(request, _("Please select a project.")) return HttpResponseRedirect(redirect) config.is_enabled = True old_domain = config.source_domain config.source_domain = source_domain if source_domain in config.domains: config.domains.remove(source_domain) config.save() clear_enterprise_permissions_cache_for_all_users.delay(config.id, config.source_domain) clear_enterprise_permissions_cache_for_all_users.delay(config.id, old_domain) messages.success(request, _('Controlling domain set to {}.').format(source_domain)) return HttpResponseRedirect(redirect) class ManageEnterpriseMobileWorkersView(ManageMobileWorkersMixin, BaseEnterpriseAdminView): page_title = gettext_lazy("Manage Mobile Workers") template_name = 'enterprise/manage_mobile_workers.html' urlname = 'enterprise_manage_mobile_workers'
bsd-3-clause
3a04c9c0a4e2631ccee7d838ededa059
37.068132
110
0.656024
4.287376
false
true
false
false
dimagi/commcare-hq
corehq/motech/openmrs/const.py
1
3921
import logging from itertools import chain LOG_LEVEL_CHOICES = ( (99, 'Disable logging'), (logging.ERROR, 'Error'), (logging.INFO, 'Info'), ) # device_id for cases added/updated by an OpenmrsImporter. # OpenmrsImporter ID is appended to this. OPENMRS_IMPORTER_DEVICE_ID_PREFIX = 'openmrs-importer-' # XMLNS to indicate that a form was imported from OpenMRS XMLNS_OPENMRS = 'http://commcarehq.org/openmrs-integration' OPENMRS_ATOM_FEED_POLL_INTERVAL = {'minute': '*/10'} # device_id for cases added/updated from OpenMRS Atom feed. # OpenmrsRepeater ID is appended to this. OPENMRS_ATOM_FEED_DEVICE_ID = 'openmrs-atomfeed-' ATOM_FEED_NAME_PATIENT = 'patient' ATOM_FEED_NAME_ENCOUNTER = 'encounter' ATOM_FEED_NAMES = ( ATOM_FEED_NAME_PATIENT, ATOM_FEED_NAME_ENCOUNTER, ) # The Location property to store the OpenMRS location UUID in LOCATION_OPENMRS_UUID = 'openmrs_uuid' # To match cases against their OpenMRS Person UUID, in case config # (Project Settings > Data Forwarding > Forward to OpenMRS > Configure > # Patient config) "patient_identifiers", set the identifier's key to the # value of PERSON_UUID_IDENTIFIER_TYPE_ID. e.g.:: # # "patient_identifiers": { # /* ... */ # "uuid": { # "case_property": "openmrs_uuid" # } # } # # To match against any other OpenMRS identifier, set the key to the UUID # of the OpenMRS Identifier Type. e.g.:: # # "patient_identifiers": { # /* ... */ # "e2b966d0-1d5f-11e0-b929-000c29ad1d07": { # "case_property": "nid" # } # } # PERSON_UUID_IDENTIFIER_TYPE_ID = 'uuid' # A subset of OpenMRS concept data types. Omitted data types ("Coded", # "N/A", "Document", "Rule", "Structured Numeric", "Complex") are not # currently relevant to CommCare integration OPENMRS_DATA_TYPE_NUMERIC = 'omrs_numeric' OPENMRS_DATA_TYPE_TEXT = 'omrs_text' OPENMRS_DATA_TYPE_DATE = 'omrs_date' OPENMRS_DATA_TYPE_TIME = 'omrs_time' OPENMRS_DATA_TYPE_DATETIME = 'omrs_datetime' OPENMRS_DATA_TYPE_BOOLEAN = 'omrs_boolean' OPENMRS_DATA_TYPE_MILLISECONDS = 'posix_milliseconds' OPENMRS_DATA_TYPES = ( OPENMRS_DATA_TYPE_NUMERIC, OPENMRS_DATA_TYPE_TEXT, OPENMRS_DATA_TYPE_DATE, OPENMRS_DATA_TYPE_TIME, OPENMRS_DATA_TYPE_DATETIME, OPENMRS_DATA_TYPE_BOOLEAN, OPENMRS_DATA_TYPE_MILLISECONDS, ) # Standard OpenMRS property names and their data types PERSON_PROPERTIES = { 'gender': OPENMRS_DATA_TYPE_TEXT, 'age': OPENMRS_DATA_TYPE_NUMERIC, 'birthdate': OPENMRS_DATA_TYPE_DATETIME, 'birthdateEstimated': OPENMRS_DATA_TYPE_BOOLEAN, 'dead': OPENMRS_DATA_TYPE_BOOLEAN, 'deathDate': OPENMRS_DATA_TYPE_DATETIME, 'deathdateEstimated': OPENMRS_DATA_TYPE_BOOLEAN, 'causeOfDeath': OPENMRS_DATA_TYPE_TEXT, } NAME_PROPERTIES = { 'givenName': OPENMRS_DATA_TYPE_TEXT, 'familyName': OPENMRS_DATA_TYPE_TEXT, 'middleName': OPENMRS_DATA_TYPE_TEXT, 'familyName2': OPENMRS_DATA_TYPE_TEXT, 'prefix': OPENMRS_DATA_TYPE_TEXT, 'familyNamePrefix': OPENMRS_DATA_TYPE_TEXT, 'familyNameSuffix': OPENMRS_DATA_TYPE_TEXT, 'degree': OPENMRS_DATA_TYPE_TEXT, } ADDRESS_PROPERTIES = { 'address1': OPENMRS_DATA_TYPE_TEXT, 'address2': OPENMRS_DATA_TYPE_TEXT, 'cityVillage': OPENMRS_DATA_TYPE_TEXT, 'stateProvince': OPENMRS_DATA_TYPE_TEXT, 'country': OPENMRS_DATA_TYPE_TEXT, 'postalCode': OPENMRS_DATA_TYPE_TEXT, 'latitude': OPENMRS_DATA_TYPE_NUMERIC, 'longitude': OPENMRS_DATA_TYPE_NUMERIC, 'countyDistrict': OPENMRS_DATA_TYPE_TEXT, 'address3': OPENMRS_DATA_TYPE_TEXT, 'address4': OPENMRS_DATA_TYPE_TEXT, 'address5': OPENMRS_DATA_TYPE_TEXT, 'address6': OPENMRS_DATA_TYPE_TEXT, 'startDate': OPENMRS_DATA_TYPE_DATETIME, 'endDate': OPENMRS_DATA_TYPE_DATETIME, } OPENMRS_PROPERTIES = dict(chain( PERSON_PROPERTIES.items(), NAME_PROPERTIES.items(), ADDRESS_PROPERTIES.items(), ))
bsd-3-clause
e6087ac82134636d9753d64ca847fe40
31.94958
72
0.69166
2.893727
false
false
false
false
dimagi/commcare-hq
corehq/apps/change_feed/topics.py
1
4684
from kafka.common import OffsetRequestPayload from corehq.apps.app_manager.util import app_doc_types from corehq.apps.change_feed.connection import get_simple_kafka_client from corehq.apps.change_feed.exceptions import UnavailableKafkaOffset from corehq.form_processor.models import XFormInstance DOMAIN = 'domain' META = 'meta' APP = 'app' CASE_SQL = 'case-sql' FORM_SQL = 'form-sql' SMS = 'sms' LEDGER = 'ledger' COMMCARE_USER = 'commcare-user' GROUP = 'group' WEB_USER = 'web-user' LOCATION = 'location' SYNCLOG_SQL = 'synclog-sql' CASE_TOPICS = (CASE_SQL, ) FORM_TOPICS = (FORM_SQL, ) USER_TOPICS = (COMMCARE_USER, WEB_USER) ALL = ( CASE_SQL, COMMCARE_USER, DOMAIN, FORM_SQL, GROUP, LEDGER, META, SMS, WEB_USER, APP, LOCATION, SYNCLOG_SQL, ) def get_topic_for_doc_type(doc_type, data_source_type=None, default_topic=None): from corehq.apps.change_feed import document_types from corehq.apps.locations.document_store import LOCATION_DOC_TYPE if doc_type in document_types.CASE_DOC_TYPES: return CASE_SQL elif doc_type in XFormInstance.ALL_DOC_TYPES: return FORM_SQL elif doc_type in document_types.DOMAIN_DOC_TYPES: return DOMAIN elif doc_type in document_types.MOBILE_USER_DOC_TYPES: return COMMCARE_USER elif doc_type in document_types.WEB_USER_DOC_TYPES: return WEB_USER elif doc_type in document_types.GROUP_DOC_TYPES: return GROUP elif doc_type in document_types.SYNCLOG_DOC_TYPES: return SYNCLOG_SQL elif doc_type in app_doc_types(): return APP elif doc_type == LOCATION_DOC_TYPE: return LOCATION elif doc_type in ALL: # for docs that don't have a doc_type we use the Kafka topic return doc_type elif default_topic: return default_topic else: # at some point we may want to make this more granular return META # note this does not map to the 'meta' Couch database def get_topic_offset(topic): """ :returns: The kafka offset dict for the topic.""" return get_multi_topic_offset([topic]) def get_multi_topic_offset(topics): """ :returns: A dict of offsets keyed by topic and partition""" return _get_topic_offsets(topics, latest=True) def get_multi_topic_first_available_offsets(topics): """ :returns: A dict of offsets keyed by topic and partition""" return _get_topic_offsets(topics, latest=False) def _get_topic_offsets(topics, latest): """ :param topics: list of topics :param latest: True to fetch latest offsets, False to fetch earliest available :return: dict: { (topic, partition): offset, ... } """ # https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-OffsetRequest # https://cfchou.github.io/blog/2015/04/23/a-closer-look-at-kafka-offsetrequest/ assert set(topics) <= set(ALL) with get_simple_kafka_client() as client: partition_meta = client.topic_partitions # only return the offset of the latest message in the partition num_offsets = 1 time_value = -1 if latest else -2 offsets = {} offset_requests = [] for topic in topics: partitions = list(partition_meta.get(topic, {})) for partition in partitions: offsets[(topic, partition)] = None offset_requests.append(OffsetRequestPayload(topic, partition, time_value, num_offsets)) responses = client.send_offset_request(offset_requests) for r in responses: offsets[(r.topic, r.partition)] = r.offsets[0] return offsets def validate_offsets(expected_offsets): """ Takes in a dictionary of offsets (topics to checkpoint numbers) and ensures they are all available in the current kafka feed """ if expected_offsets: topics = {x[0] for x in expected_offsets.keys()} available_offsets = get_multi_topic_first_available_offsets(topics) for topic_partition, offset in expected_offsets.items(): topic, partition = topic_partition if topic_partition not in available_offsets: raise UnavailableKafkaOffset("Invalid partition '{}' for topic '{}'".format(partition, topic)) if expected_offsets[topic_partition] < available_offsets[topic_partition]: message = ( 'First available topic offset for {}:{} is {} but needed {}.' ).format(topic, partition, available_offsets[topic_partition], expected_offsets[topic_partition]) raise UnavailableKafkaOffset(message)
bsd-3-clause
54dd73ab8f01abcfe7dbbd2bcce54f6c
32.697842
124
0.66567
3.688189
false
true
false
false
dimagi/commcare-hq
corehq/sql_proxy_standby_accessors/migrations/0001_initial.py
1
1391
from django.conf import settings from django.db import migrations from corehq.sql_db.config import plproxy_standby_config from corehq.sql_db.management.commands.configure_pl_proxy_cluster import ( get_drop_server_sql, get_sql_to_create_pl_proxy_cluster, ) from corehq.sql_db.operations import RawSQLMigration from corehq.util.django_migrations import noop_migration migrator = RawSQLMigration(('corehq', 'sql_proxy_standby_accessors', 'sql_templates'), { 'PL_PROXY_CLUSTER_NAME': settings.PL_PROXY_CLUSTER_NAME }) def create_update_pl_proxy_config(): if not plproxy_standby_config or not (settings.UNIT_TESTING and settings.USE_PARTITIONED_DATABASE): return noop_migration() sql_statements = get_sql_to_create_pl_proxy_cluster(plproxy_standby_config) drop_server_sql = get_drop_server_sql(plproxy_standby_config.cluster_name) return migrations.RunSQL('\n'.join(sql_statements), drop_server_sql) class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.RunSQL( 'CREATE EXTENSION IF NOT EXISTS plproxy', 'DROP EXTENSION plproxy' ), migrations.RunSQL( 'CREATE EXTENSION IF NOT EXISTS hashlib', 'DROP EXTENSION hashlib' ), create_update_pl_proxy_config(), migrator.get_migration('get_replication_delay.sql'), ]
bsd-3-clause
503e6d55a3956441333860de6f837576
32.119048
103
0.701653
3.650919
false
true
false
false
dimagi/commcare-hq
corehq/apps/reports/management/commands/rollout_ecd_preview.py
1
4170
from django.core.management import BaseCommand from django.db.models import Q from corehq.apps.accounting.models import SoftwarePlanEdition, Subscription from corehq.feature_previews import EXPLORE_CASE_DATA_PREVIEW from corehq.toggles import ( ECD_MIGRATED_DOMAINS, ECD_PREVIEW_ENTERPRISE_DOMAINS, NAMESPACE_DOMAIN, ) class Command(BaseCommand): help = 'Enables the Case Search Index for Explore Case Data Report' def add_arguments(self, parser): parser.add_argument( '--domain', action='store', dest='domain', default=None, help='A single domain to rollout ECD preview to.', ) parser.add_argument( '--deativate-domain', action='store', dest='deactivate_domain', default=None, help='A single domain to deactivate ECD preview to' ) parser.add_argument( '--deativate', action='store_true', dest='deactivate', default=False, help='Deactivate all ineligible domains.' ) def _domains_in_beta(self): relevant_subs = Subscription.visible_objects.filter( is_active=True, is_trial=False, ).filter( Q(plan_version__plan__edition=SoftwarePlanEdition.ADVANCED) | Q(plan_version__plan__edition=SoftwarePlanEdition.PRO) ).all() domains = set([sub.subscriber.domain for sub in relevant_subs]) enterprise_domains = set(ECD_PREVIEW_ENTERPRISE_DOMAINS.get_enabled_domains()) domains = domains.union(enterprise_domains) migrated_domains = set(ECD_MIGRATED_DOMAINS.get_enabled_domains()) return domains.intersection(migrated_domains) def _domains_needing_activation(self): domains_in_beta = self._domains_in_beta() preview_domains = set(EXPLORE_CASE_DATA_PREVIEW.get_enabled_domains()) return domains_in_beta.difference(preview_domains) def _domains_needing_deactivation(self): preview_domains = set(EXPLORE_CASE_DATA_PREVIEW.get_enabled_domains()) return preview_domains.difference(self._domains_in_beta()) def handle(self, **options): domain = options.pop('domain') deactivate_domain = options.pop('deactivate_domain') deactivate = options.pop('deactivate') if deactivate: self.update_domains( self._domains_needing_deactivation(), 'deactivation', False ) return if deactivate_domain: EXPLORE_CASE_DATA_PREVIEW.set(deactivate_domain, False, NAMESPACE_DOMAIN) self.stdout.write('\n\nDomain {} deactivated.\n\n'.format( deactivate_domain)) return if domain: if domain not in ECD_MIGRATED_DOMAINS.get_enabled_domains(): self.stdout.write('\n\nDomain {} not migrated yet. ' 'Activation not possible.\n\n'.format(domain)) return EXPLORE_CASE_DATA_PREVIEW.set(domain, True, NAMESPACE_DOMAIN) self.stdout.write('\n\nDomain {} activated.\n\n'.format(domain)) return self.update_domains( self._domains_needing_activation(), 'activation', True ) def update_domains(self, domains, action_name, action_state): if not domains: self.stdout.write('\n\nNo domains need {}.'.format(action_name)) return self.stdout.write('\n\nDomains needing {}\n'.format(action_name)) self.stdout.write('\n'.join(domains)) confirm = input('\n\nContinue with {}? [y/n] '.format(action_name)) if not confirm == 'y': self.stdout.write('\nAborting {}\n\n'.format(action_name)) return self.stdout.write('\n') for domain in domains: self.stdout.write('.') EXPLORE_CASE_DATA_PREVIEW.set(domain, action_state, NAMESPACE_DOMAIN) self.stdout.write('\n\nDone.\n\n')
bsd-3-clause
39a5e374fd3cc8b9b839f6588ebaa6d8
35.26087
86
0.590887
4.080235
false
false
false
false
onepercentclub/bluebottle
bluebottle/members/migrations/0058_auto_20220607_0934.py
1
1163
# Generated by Django 2.2.24 on 2022-06-07 07:34 import bluebottle.bb_accounts.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('members', '0057_auto_20220516_1412'), ] operations = [ migrations.AddField( model_name='memberplatformsettings', name='require_address', field=models.BooleanField(default=False, help_text='Require members to enter their address once after logging in.', verbose_name='Address'), ), migrations.AddField( model_name='memberplatformsettings', name='require_birthdate', field=models.BooleanField(default=False, help_text='Require members to enter their date of birth once after logging in.', verbose_name='Birthdate'), ), migrations.AddField( model_name='memberplatformsettings', name='require_phone_number', field=models.BooleanField(default=False, help_text='Require members to enter their phone number once after logging in.', verbose_name='Phone number'), ), ]
bsd-3-clause
429955b811e87e887c53e4b169793ba1
37.766667
162
0.660361
4.473077
false
false
false
false
dimagi/commcare-hq
corehq/form_processor/utils/xform.py
1
9152
from datetime import datetime from lxml import etree import re import iso8601 import pytz import xml2json from corehq.form_processor.interfaces.processor import XFormQuestionValueIterator from corehq.form_processor.models import Attachment, XFormInstance from corehq.form_processor.exceptions import XFormQuestionValueNotFound from dimagi.ext import jsonobject from dimagi.utils.parsing import json_format_datetime # The functionality below to create a simple wrapped XForm is used in production code (repeaters) and so is # not in the test utils SIMPLE_FORM = """<?xml version='1.0' ?> <data uiVersion="1" version="17" name="{form_name}" xmlns:jrm="http://dev.commcarehq.org/jr/xforms" xmlns="{xmlns}"> {form_properties} <n1:meta xmlns:n1="http://openrosa.org/jr/xforms"> <n1:deviceID>{device_id}</n1:deviceID> <n1:timeStart>{time_start}</n1:timeStart> <n1:timeEnd>{time_end}</n1:timeEnd> <n1:username>{username}</n1:username> <n1:userID>{user_id}</n1:userID> <n1:instanceID>{uuid}</n1:instanceID> <n2:appVersion xmlns:n2="http://commcarehq.org/xforms"></n2:appVersion> </n1:meta> {case_block} </data>""" # this is like jsonobject.api.re_datetime, # but without the "time" parts being optional # i.e. I just removed (...)? surrounding the second two lines # This is used to in our form processor so we detect what strings are datetimes. RE_DATETIME_MATCH = re.compile(r""" ^ (\d{4}) # year \D? (0[1-9]|1[0-2]) # month \D? ([12]\d|0[1-9]|3[01]) # day [ T] ([01]\d|2[0-3]) # hour \D? ([0-5]\d) # minute \D? ([0-5]\d)? # second \D? (\d{3,6})? # millisecond ([zZ]|([\+-])([01]\d|2[0-3])\D?([0-5]\d)?)? # timezone $ """, re.VERBOSE) class TestFormMetadata(jsonobject.JsonObject): domain = jsonobject.StringProperty(required=False) xmlns = jsonobject.StringProperty(default='http://openrosa.org/formdesigner/form-processor') app_id = jsonobject.StringProperty(default='123') form_name = jsonobject.StringProperty(default='New Form') device_id = jsonobject.StringProperty(default='DEV IL') user_id = jsonobject.StringProperty(default='cruella_deville') username = jsonobject.StringProperty(default='eve') time_end = jsonobject.DateTimeProperty(default=datetime(2013, 4, 19, 16, 52, 2)) time_start = jsonobject.DateTimeProperty(default=datetime(2013, 4, 19, 16, 53, 2)) # Set this property to fake the submission time received_on = jsonobject.DateTimeProperty(default=datetime.utcnow) class FormSubmissionBuilder(object): """ Utility/helper object for building a form submission """ def __init__(self, form_id, metadata=None, case_blocks=None, form_properties=None, form_template=SIMPLE_FORM): self.form_id = form_id self.metadata = metadata or TestFormMetadata() self.case_blocks = case_blocks or [] self.form_template = form_template self.form_properties = form_properties or {} def as_xml_string(self): case_block_xml = ''.join(cb.as_text() for cb in self.case_blocks) form_properties_xml = build_form_xml_from_property_dict(self.form_properties) form_xml = self.form_template.format( uuid=self.form_id, form_properties=form_properties_xml, case_block=case_block_xml, **self.metadata.to_json() ) if not self.metadata.user_id: form_xml = form_xml.replace('<n1:userID>{}</n1:userID>'.format(self.metadata.user_id), '') return form_xml def _build_node_list_from_dict(form_properties, separator=''): elements = [] for key, values in form_properties.items(): if not isinstance(values, list): values = [values] for value in values: node = etree.Element(key) if isinstance(value, dict): children = _build_node_list_from_dict(value, separator=separator) for child in children: node.append(child) else: node.text = value elements.append(node) return elements def build_form_xml_from_property_dict(form_properties, separator=''): return separator.join( etree.tostring(e, encoding='utf-8').decode('utf-8') for e in _build_node_list_from_dict(form_properties, separator) ) def get_simple_form_xml(form_id, case_id=None, metadata=None, simple_form=SIMPLE_FORM): from casexml.apps.case.mock import CaseBlock case_blocks = [CaseBlock(create=True, case_id=case_id)] if case_id else [] return FormSubmissionBuilder( form_id=form_id, metadata=metadata, case_blocks=case_blocks, form_template=simple_form, ).as_xml_string() def get_simple_wrapped_form(form_id, metadata=None, save=True, simple_form=SIMPLE_FORM): from corehq.form_processor.interfaces.processor import FormProcessorInterface metadata = metadata or TestFormMetadata() xml = get_simple_form_xml(form_id=form_id, metadata=metadata, simple_form=simple_form) form_json = convert_xform_to_json(xml) interface = FormProcessorInterface(domain=metadata.domain) wrapped_form = interface.new_xform(form_json) wrapped_form.domain = metadata.domain wrapped_form.received_on = metadata.received_on interface.store_attachments(wrapped_form, [Attachment('form.xml', xml, 'text/xml')]) if save: interface.save_processed_models([wrapped_form]) wrapped_form = XFormInstance.objects.get_form(wrapped_form.form_id, metadata.domain) return wrapped_form def extract_meta_instance_id(form): """Takes form json (as returned by xml2json)""" if form.get('Meta'): # bhoma, 0.9 commcare meta = form['Meta'] elif form.get('meta'): # commcare 1.0 meta = form['meta'] else: return None if meta.get('uid'): # bhoma return meta['uid'] elif meta.get('instanceID'): # commcare 0.9, commcare 1.0 return meta['instanceID'] else: return None def extract_meta_user_id(form): user_id = None if form.get('meta'): user_id = form.get('meta').get('userID', None) elif form.get('Meta'): user_id = form.get('Meta').get('user_id', None) return user_id def convert_xform_to_json(xml_string): """ takes xform payload as xml_string and returns the equivalent json i.e. the json that will show up as xform.form """ try: name, json_form = xml2json.xml2json(xml_string) except xml2json.XMLSyntaxError as e: from couchforms import XMLSyntaxError raise XMLSyntaxError('Invalid XML: %s' % e) json_form['#type'] = name return json_form def adjust_text_to_datetime(text): matching_datetime = iso8601.parse_date(text) return matching_datetime.astimezone(pytz.utc).replace(tzinfo=None) def adjust_datetimes(data, parent=None, key=None): """ find all datetime-like strings within data (deserialized json) and format them uniformly, in place. """ # this strips the timezone like we've always done # todo: in the future this will convert to UTC if isinstance(data, str) and RE_DATETIME_MATCH.match(data): try: parent[key] = str(json_format_datetime( adjust_text_to_datetime(data) )) except (iso8601.ParseError, ValueError): pass elif isinstance(data, dict): for key, value in data.items(): adjust_datetimes(value, parent=data, key=key) elif isinstance(data, list): for i, value in enumerate(data): adjust_datetimes(value, parent=data, key=i) # return data, just for convenience in testing # this is the original input, modified, not a new data structure return data def resave_form(domain, form): from corehq.form_processor.change_publishers import publish_form_saved publish_form_saved(form) def get_node(root, question, xmlns=''): ''' Given an xml element, find the node corresponding to a question path. See XFormQuestionValueIterator for question path format. Throws XFormQuestionValueNotFound if question is not present. ''' def _next_node(node, xmlns, id, index=None): try: return node.findall("{{{}}}{}".format(xmlns, id))[index or 0] except (IndexError, KeyError): raise XFormQuestionValueNotFound() node = root i = XFormQuestionValueIterator(question) for (qid, index) in i: node = _next_node(node, xmlns, qid, index) node = _next_node(node, xmlns, i.last()) if node is None: raise XFormQuestionValueNotFound() return node def update_response(root, question, response, xmlns=None): ''' Given a form submission's xml root, updates the response for an individual question. Question and response are both strings; see XFormQuestionValueIterator for question format. ''' node = get_node(root, question, xmlns) if node.text != response: node.text = response return True return False
bsd-3-clause
18b53f149792276b6b57d3704cb209a7
33.406015
114
0.655594
3.580595
false
false
false
false
onepercentclub/bluebottle
bluebottle/payments_docdata/migrations/0001_initial.py
2
8230
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-05-23 13:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('payments', '0001_initial'), ] operations = [ migrations.CreateModel( name='DocdataDirectdebitPayment', fields=[ ('payment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='payments.Payment')), ('merchant_order_id', models.CharField(default=b'', max_length=100, verbose_name='Order ID')), ('payment_cluster_id', models.CharField(default=b'', max_length=200, unique=True, verbose_name='Payment cluster id')), ('payment_cluster_key', models.CharField(default=b'', max_length=200, unique=True, verbose_name='Payment cluster key')), ('language', models.CharField(blank=True, default=b'en', max_length=5, verbose_name='Language')), ('ideal_issuer_id', models.CharField(default=b'', max_length=100, verbose_name='Ideal Issuer ID')), ('default_pm', models.CharField(max_length=100, verbose_name='Default Payment Method')), ('total_gross_amount', models.IntegerField(verbose_name='Total gross amount')), ('currency', models.CharField(max_length=10, verbose_name='Currency')), ('country', models.CharField(blank=True, max_length=2, null=True, verbose_name='Country_code')), ('total_registered', models.IntegerField(default=0, verbose_name='Total registered')), ('total_shopper_pending', models.IntegerField(default=0, verbose_name='Total shopper pending')), ('total_acquirer_pending', models.IntegerField(default=0, verbose_name='Total acquirer pending')), ('total_acquirer_approved', models.IntegerField(default=0, verbose_name='Total acquirer approved')), ('total_captured', models.IntegerField(default=0, verbose_name='Total captured')), ('total_refunded', models.IntegerField(default=0, verbose_name='Total refunded')), ('total_charged_back', models.IntegerField(default=0, verbose_name='Total charged back')), ('customer_id', models.PositiveIntegerField(default=0)), ('email', models.EmailField(default=b'', max_length=254)), ('first_name', models.CharField(default=b'', max_length=200)), ('last_name', models.CharField(default=b'', max_length=200)), ('address', models.CharField(default=b'', max_length=200)), ('postal_code', models.CharField(default=b'', max_length=20)), ('city', models.CharField(default=b'', max_length=200)), ('ip_address', models.CharField(default=b'', max_length=200)), ('account_name', models.CharField(max_length=35)), ('account_city', models.CharField(max_length=35)), ('iban', models.CharField(max_length=35)), ('bic', models.CharField(max_length=35)), ('agree', models.BooleanField(default=False)), ], options={ 'ordering': ('-created', '-updated'), 'abstract': False, 'verbose_name': 'Docdata Direct Debit Payment', 'verbose_name_plural': 'Docdata Direct Debit Payments', }, bases=('payments.payment',), ), migrations.CreateModel( name='DocdataPayment', fields=[ ('payment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='payments.Payment')), ('merchant_order_id', models.CharField(default=b'', max_length=100, verbose_name='Order ID')), ('payment_cluster_id', models.CharField(default=b'', max_length=200, unique=True, verbose_name='Payment cluster id')), ('payment_cluster_key', models.CharField(default=b'', max_length=200, unique=True, verbose_name='Payment cluster key')), ('language', models.CharField(blank=True, default=b'en', max_length=5, verbose_name='Language')), ('ideal_issuer_id', models.CharField(default=b'', max_length=100, verbose_name='Ideal Issuer ID')), ('default_pm', models.CharField(max_length=100, verbose_name='Default Payment Method')), ('total_gross_amount', models.IntegerField(verbose_name='Total gross amount')), ('currency', models.CharField(max_length=10, verbose_name='Currency')), ('country', models.CharField(blank=True, max_length=2, null=True, verbose_name='Country_code')), ('total_registered', models.IntegerField(default=0, verbose_name='Total registered')), ('total_shopper_pending', models.IntegerField(default=0, verbose_name='Total shopper pending')), ('total_acquirer_pending', models.IntegerField(default=0, verbose_name='Total acquirer pending')), ('total_acquirer_approved', models.IntegerField(default=0, verbose_name='Total acquirer approved')), ('total_captured', models.IntegerField(default=0, verbose_name='Total captured')), ('total_refunded', models.IntegerField(default=0, verbose_name='Total refunded')), ('total_charged_back', models.IntegerField(default=0, verbose_name='Total charged back')), ('customer_id', models.PositiveIntegerField(default=0)), ('email', models.EmailField(default=b'', max_length=254)), ('first_name', models.CharField(default=b'', max_length=200)), ('last_name', models.CharField(default=b'', max_length=200)), ('address', models.CharField(default=b'', max_length=200)), ('postal_code', models.CharField(default=b'', max_length=20)), ('city', models.CharField(default=b'', max_length=200)), ('ip_address', models.CharField(default=b'', max_length=200)), ], options={ 'ordering': ('-created', '-updated'), 'abstract': False, 'verbose_name': 'Docdata Payment', 'verbose_name_plural': 'Docdata Payments', }, bases=('payments.payment',), ), migrations.CreateModel( name='DocdataTransaction', fields=[ ('transaction_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='payments.Transaction')), ('status', models.CharField(default=b'NEW', max_length=30, verbose_name='status')), ('docdata_id', models.CharField(max_length=100, verbose_name='Docdata ID')), ('payment_method', models.CharField(blank=True, default=b'', max_length=60)), ('authorization_status', models.CharField(blank=True, default=b'', max_length=60)), ('authorization_amount', models.IntegerField(null=True, verbose_name='Amount in cents')), ('authorization_currency', models.CharField(blank=True, default=b'', max_length=10)), ('capture_status', models.CharField(blank=True, default=b'', max_length=60)), ('capture_amount', models.IntegerField(null=True, verbose_name='Amount in cents')), ('chargeback_amount', models.IntegerField(null=True, verbose_name='Charge back amount in cents')), ('refund_amount', models.IntegerField(null=True, verbose_name='Refund amount in cents')), ('capture_currency', models.CharField(default=b'', max_length=10, null=True)), ('raw_response', models.TextField(blank=True)), ], options={ 'abstract': False, }, bases=('payments.transaction',), ), ]
bsd-3-clause
c63ae5b73fd60d5a47e26f84de68e1e7
68.159664
202
0.600729
4.257631
false
false
false
false
dimagi/commcare-hq
corehq/apps/domain/project_access/middleware.py
1
1526
from datetime import datetime, timedelta from django.utils.deprecation import MiddlewareMixin from corehq.apps.domain.project_access.models import ( ENTRY_RECORD_FREQUENCY, SuperuserProjectEntryRecord, ) from corehq.apps.users.tasks import update_domain_date from corehq.util.quickcache import quickcache class ProjectAccessMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): if getattr(request, 'couch_user', None) and request.couch_user.is_superuser \ and hasattr(request, 'domain'): self.record_superuser_entry(request.domain, request.couch_user.username) if getattr(request, 'couch_user', None) and request.couch_user.is_web_user() \ and hasattr(request, 'domain'): self.record_web_user_entry(request.couch_user, request.domain) @quickcache(['domain', 'username'], timeout=ENTRY_RECORD_FREQUENCY.seconds) def record_superuser_entry(self, domain, username): if not SuperuserProjectEntryRecord.entry_recently_recorded(username, domain): SuperuserProjectEntryRecord.record_entry(username, domain) return None @staticmethod def record_web_user_entry(user, domain): membership = user.get_domain_membership(domain) yesterday = (datetime.today() - timedelta(hours=24)).date() if membership and (not membership.last_accessed or membership.last_accessed <= yesterday): update_domain_date.delay(user.user_id, domain)
bsd-3-clause
c546917d2c4d39680dca440d4476b961
45.242424
98
0.714286
3.882952
false
false
false
false
dimagi/commcare-hq
corehq/pillows/ledger.py
1
4277
from collections import namedtuple from functools import lru_cache from pillowtop.checkpoints.manager import ( get_checkpoint_for_elasticsearch_pillow, ) from pillowtop.pillow.interface import ConstructedPillow from pillowtop.processors import PillowProcessor from corehq.apps.change_feed import topics from corehq.apps.change_feed.consumer.feed import ( KafkaChangeFeed, KafkaCheckpointEventHandler, ) from corehq.apps.export.models.new import LedgerSectionEntry from corehq.apps.locations.models import SQLLocation from corehq.util.quickcache import quickcache @quickcache(['case_id']) def _location_id_for_case(case_id): try: return SQLLocation.objects.get(supply_point_id=case_id).location_id except SQLLocation.DoesNotExist: return None def _get_daily_consumption_for_ledger(ledger): from corehq.apps.commtrack.consumption import get_consumption_for_ledger_json daily_consumption = get_consumption_for_ledger_json(ledger) from corehq.form_processor.backends.sql.dbaccessors import LedgerAccessorSQL ledger_value = LedgerAccessorSQL.get_ledger_value( ledger['case_id'], ledger['section_id'], ledger['entry_id'] ) ledger_value.daily_consumption = daily_consumption LedgerAccessorSQL.save_ledger_values([ledger_value]) return daily_consumption def _update_ledger_section_entry_combinations(ledger): current_combos = _get_ledger_section_combinations(ledger['domain']) if (ledger['section_id'], ledger['entry_id']) in current_combos: return # use get_or_create because this may be created by another parallel process LedgerSectionEntry.objects.get_or_create( domain=ledger['domain'], section_id=ledger['section_id'], entry_id=ledger['entry_id'], ) # clear the lru_cache so that next time a ledger is saved, we get the combinations _get_ledger_section_combinations.cache_clear() @lru_cache() def _get_ledger_section_combinations(domain): return list(LedgerSectionEntry.objects.filter(domain=domain).values_list('section_id', 'entry_id').all()) class LedgerProcessor(PillowProcessor): """Updates ledger section and entry combinations (exports), daily consumption and case location ids Reads from: - Kafka topics: ledger - Ledger data source Writes to: - LedgerSectionEntry postgres table - Ledger data source """ def process_change(self, change): if change.deleted: return ledger = change.get_document() from corehq.apps.commtrack.models import CommtrackConfig commtrack_config = CommtrackConfig.for_domain(ledger['domain']) if commtrack_config and commtrack_config.use_auto_consumption: daily_consumption = _get_daily_consumption_for_ledger(ledger) ledger['daily_consumption'] = daily_consumption if not ledger.get('location_id') and ledger.get('case_id'): ledger['location_id'] = _location_id_for_case(ledger['case_id']) _update_ledger_section_entry_combinations(ledger) def get_ledger_to_elasticsearch_pillow(pillow_id='LedgerToElasticsearchPillow', num_processes=1, process_num=0, **kwargs): """Ledger pillow Note that this pillow's id references Elasticsearch, but it no longer saves to ES. It has been kept to keep the checkpoint consistent, and can be changed at any time. Processors: - :py:class:`corehq.pillows.ledger.LedgerProcessor` """ assert pillow_id == 'LedgerToElasticsearchPillow', 'Pillow ID is not allowed to change' IndexInfo = namedtuple('IndexInfo', ['index']) checkpoint = get_checkpoint_for_elasticsearch_pillow( pillow_id, IndexInfo("ledgers_2016-03-15"), [topics.LEDGER] ) change_feed = KafkaChangeFeed( topics=[topics.LEDGER], client_id='ledgers-to-es', num_processes=num_processes, process_num=process_num ) return ConstructedPillow( name=pillow_id, checkpoint=checkpoint, change_feed=change_feed, processor=LedgerProcessor(), change_processed_event_handler=KafkaCheckpointEventHandler( checkpoint=checkpoint, checkpoint_frequency=100, change_feed=change_feed ), )
bsd-3-clause
56d15dd01f4d8958fa46c420769ba108
35.555556
111
0.708908
3.664953
false
false
false
false
dimagi/commcare-hq
corehq/apps/case_search/views.py
1
3244
import json import re from django.http import Http404 from django.urls import reverse from django.utils.translation import gettext_lazy from dimagi.utils.web import json_response from corehq.apps.case_search.models import case_search_enabled_for_domain from corehq.apps.domain.decorators import cls_require_superuser_or_contractor from corehq.apps.domain.views.base import BaseDomainView from corehq.util.view_utils import BadRequest, json_error class CaseSearchView(BaseDomainView): section_name = gettext_lazy("Data") template_name = 'case_search/case_search.html' urlname = 'case_search' page_title = gettext_lazy("Case Search") @property def section_url(self): return reverse("data_interfaces_default", args=[self.domain]) @property def page_url(self): return reverse(self.urlname, args=[self.domain]) @property def page_context(self): context = super().page_context context.update({ 'settings_url': reverse("case_search_config", args=[self.domain]), }) return context @cls_require_superuser_or_contractor def get(self, request, *args, **kwargs): if not case_search_enabled_for_domain(self.domain): raise Http404("Domain does not have case search enabled") return self.render_to_response(self.get_context_data()) @json_error @cls_require_superuser_or_contractor def post(self, request, *args, **kwargs): from corehq.apps.es.case_search import CaseSearchES if not case_search_enabled_for_domain(self.domain): raise BadRequest("Domain does not have case search enabled") query = json.loads(request.POST.get('q')) case_type = query.get('type') owner_id = query.get('owner_id') search_params = query.get('parameters', []) xpath = query.get("xpath") search = CaseSearchES() search = search.domain(self.domain).size(10) if case_type: search = search.case_type(case_type) if owner_id: search = search.owner(owner_id) for param in search_params: value = re.sub(param.get('regex', ''), '', param.get('value')) if '/' in param.get('key'): query = '{} = "{}"'.format(param.get('key'), value) search = search.xpath_query(self.domain, query, fuzzy=param.get('fuzzy')) else: search = search.case_property_query( param.get('key'), value, clause=param.get('clause'), fuzzy=param.get('fuzzy'), ) if xpath: search = search.xpath_query(self.domain, xpath) include_profile = request.POST.get("include_profile", False) if include_profile: search = search.enable_profiling() search_results = search.run() return json_response({ 'values': search_results.raw_hits, 'count': search_results.total, 'took': search_results.raw['took'], 'query': search_results.query.dumps(pretty=True), 'profile': json.dumps(search_results.raw.get('profile', {}), indent=2), })
bsd-3-clause
170f30dba2801c00682c838d84c584d3
35.044444
89
0.611591
3.951279
false
false
false
false
dimagi/commcare-hq
corehq/motech/generic_inbound/utils.py
1
1296
import json import uuid from base64 import urlsafe_b64encode from django.utils.translation import gettext as _ from casexml.apps.phone.xml import get_registration_element_data from corehq.apps.userreports.specs import EvaluationContext from corehq.motech.generic_inbound.exceptions import GenericInboundUserError def make_url_key(): raw_key = urlsafe_b64encode(uuid.uuid4().bytes).decode() return raw_key.removesuffix("==") def get_context_from_request(request): try: body = json.loads(request.body.decode('utf-8')) except (UnicodeDecodeError, json.JSONDecodeError): raise GenericInboundUserError(_("Payload must be valid JSON")) couch_user = request.couch_user restore_user = couch_user.to_ota_restore_user(request.domain, request_user=couch_user) query = dict(request.GET.lists()) return get_evaluation_context( restore_user, request.method, query, dict(request.headers), body ) def get_evaluation_context(restore_user, method, query, headers, body): return EvaluationContext({ 'request': { 'method': method, 'query': query, 'headers': headers }, 'body': body, 'user': get_registration_element_data(restore_user) })
bsd-3-clause
9a4a543e0fafd9a40ed0da20f11fed41
27.8
90
0.675926
3.800587
false
false
false
false
dimagi/commcare-hq
corehq/apps/products/migrations/0001_initial.py
1
1498
from django.db import migrations, models import jsonfield.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='SQLProduct', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('domain', models.CharField(max_length=255, db_index=True)), ('product_id', models.CharField(unique=True, max_length=100, db_index=True)), ('name', models.CharField(max_length=100, null=True)), ('is_archived', models.BooleanField(default=False)), ('code', models.CharField(default='', max_length=100, null=True)), ('description', models.TextField(default='', null=True)), ('category', models.CharField(default='', max_length=100, null=True)), ('program_id', models.CharField(default='', max_length=100, null=True)), ('cost', models.DecimalField(null=True, max_digits=20, decimal_places=5)), ('units', models.CharField(default='', max_length=100, null=True)), ('product_data', jsonfield.fields.JSONField(default=dict)), ('created_at', models.DateTimeField(auto_now_add=True)), ('last_modified', models.DateTimeField(auto_now=True)), ], options={ }, bases=(models.Model,), ), ]
bsd-3-clause
398cfe7c5e88f224a1ff663f350dd554
43.058824
114
0.565421
4.317003
false
false
false
false
dimagi/commcare-hq
corehq/apps/userreports/migrations/0018_ucrexpression.py
1
1026
# Generated by Django 3.2.12 on 2022-04-12 15:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('userreports', '0017_index_cleanup'), ] operations = [ migrations.CreateModel( name='UCRExpression', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('domain', models.CharField(db_index=True, max_length=255)), ('description', models.TextField(blank=True, null=True)), ('expression_type', models.CharField(choices=[('named_expression', 'named_expression'), ('named_filter', 'named_filter')], db_index=True, default='named_expression', max_length=20)), ('definition', models.JSONField(null=True)), ], options={ 'unique_together': {('name', 'domain')}, }, ), ]
bsd-3-clause
a073716e59369ab0d86c28e1b0d27894
37
198
0.567251
4.239669
false
false
false
false
onepercentclub/bluebottle
bluebottle/cms/migrations/0035_auto_20171017_1611.py
1
1079
# -*- coding: utf-8 -*- # Generated by Django 1.10.8 on 2017-10-17 14:11 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.manager class Migration(migrations.Migration): dependencies = [ ('cms', '0034_auto_20171017_1549'), ] operations = [ migrations.AlterUniqueTogether( name='steptranslation', unique_together=set([]), ), migrations.RemoveField( model_name='steptranslation', name='master', ), migrations.AddField( model_name='step', name='header', field=models.CharField(default='', max_length=100, verbose_name='Header'), preserve_default=False, ), migrations.AddField( model_name='step', name='text', field=models.CharField(default='', max_length=400, verbose_name='Text'), preserve_default=False, ), migrations.DeleteModel( name='StepTranslation', ), ]
bsd-3-clause
86a39c2fd781382a9d4ad22c9166b84f
26.666667
86
0.560704
4.386179
false
false
false
false