forked from dimagi/commcare-hq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.py
278 lines (229 loc) · 8.07 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
from xml.etree import ElementTree
from casexml.apps.case.models import CommCareCase
from corehq import toggles, feature_previews
from corehq.apps.commtrack import const
from corehq.apps.commtrack.const import RequisitionActions
from corehq.apps.commtrack.models import CommtrackConfig, SupplyPointCase, CommtrackActionConfig, \
CommtrackRequisitionConfig
from corehq.apps.products.models import Product
from corehq.apps.programs.models import Program
from corehq.apps.locations.models import Location
import itertools
from datetime import date, timedelta
from calendar import monthrange
from corehq.apps.hqcase.utils import submit_case_blocks
from casexml.apps.case.mock import CaseBlock
from casexml.apps.case.xml import V2
from django.utils.text import slugify
from unidecode import unidecode
from django.utils.translation import ugettext as _
import re
def all_sms_codes(domain):
config = CommtrackConfig.for_domain(domain)
actions = dict((action.keyword, action) for action in config.actions)
products = dict((p.code, p) for p in Product.by_domain(domain))
commands = {
config.multiaction_keyword: {'type': 'stock_report_generic', 'caption': 'Stock Report'},
}
sms_codes = zip(('action', 'product', 'command'), (actions, products, commands))
return dict(itertools.chain(*([(k.lower(), (type, v)) for k, v in codes.iteritems()] for type, codes in sms_codes)))
def get_supply_point(domain, site_code=None, loc=None):
if loc is None:
loc = Location.view('commtrack/locations_by_code',
key=[domain, site_code.lower()],
include_docs=True).first()
if loc:
case = SupplyPointCase.get_by_location(loc)
else:
case = None
return {
'case': case,
'location': loc,
}
def make_program(domain, name, code, default=False):
p = Program()
p.domain = domain
p.name = name
p.code = code.lower()
p.default = default
p.save()
return p
def get_or_create_default_program(domain):
program = Program.default_for_domain(domain)
if program:
return program
else:
return make_program(
domain,
_('Uncategorized'),
_('uncategorized'),
default=True
)
def _create_commtrack_config_if_needed(domain):
if CommtrackConfig.for_domain(domain):
return
CommtrackConfig(
domain=domain,
multiaction_enabled=True,
multiaction_keyword='report',
actions=[
CommtrackActionConfig(
action='receipts',
keyword='r',
caption='Received',
),
CommtrackActionConfig(
action='consumption',
keyword='c',
caption='Consumed',
),
CommtrackActionConfig(
action='consumption',
subaction='loss',
keyword='l',
caption='Losses',
),
CommtrackActionConfig(
action='stockonhand',
keyword='soh',
caption='Stock on hand',
),
CommtrackActionConfig(
action='stockout',
keyword='so',
caption='Stock-out',
),
],
).save()
def _enable_commtrack_previews(domain):
for toggle_class in (
toggles.COMMTRACK,
feature_previews.LOCATIONS,
toggles.VELLUM_TRANSACTION_QUESTION_TYPES,
toggles.VELLUM_ADVANCED_ITEMSETS,
):
toggle_class.set(domain, True, toggles.NAMESPACE_DOMAIN)
def make_domain_commtrack(domain_object):
domain_object.commtrack_enabled = True
domain_object.locations_enabled = True
domain_object.save()
_create_commtrack_config_if_needed(domain_object.name)
get_or_create_default_program(domain_object.name)
_enable_commtrack_previews(domain_object.name)
def get_default_requisition_config():
return CommtrackRequisitionConfig(
enabled=True,
actions=[
CommtrackActionConfig(
action=RequisitionActions.REQUEST,
keyword='req',
caption='Request',
),
# TODO not tested yet, so not included
# CommtrackActionConfig(
# action=RequisitionActions.APPROVAL,
# keyword='approve',
# caption='Approved',
# ),
CommtrackActionConfig(
action=RequisitionActions.FULFILL,
keyword='fulfill',
caption='Fulfilled',
),
CommtrackActionConfig(
action=RequisitionActions.RECEIPTS,
keyword='rec',
caption='Requisition Receipts',
),
],
)
def due_date_weekly(dow, past_period=0): # 0 == sunday
"""compute the next due date on a weekly schedule, where reports are
due on 'dow' day of the week (0:sunday, 6:saturday). 'next' due date
is the first due date that occurs today or in the future. if past_period
is non-zero, return the due date that occured N before the next due date
"""
cur_weekday = date.today().isoweekday()
days_till_due = (dow - cur_weekday) % 7
return date.today() + timedelta(days=days_till_due - 7 * past_period)
def due_date_monthly(day, from_end=False, past_period=0):
"""compute the next due date on a monthly schedule, where reports are
due on 'day' day of the month. (if from_end is true, due date is 'day' days
before the end of the month, where 0 is the last day of the month). 'next' due date
is the first due date that occurs today or in the future. if past_period
is non-zero, return the due date that occured N before the next due date
"""
if from_end:
assert False, 'not supported yet'
month_diff = -past_period
if date.today().day > day:
month_diff += 1
month_seq = date.today().year * 12 + (date.today().month - 1)
month_seq += month_diff
y = month_seq // 12
m = month_seq % 12 + 1
return date(y, m, min(day, monthrange(y, m)[1]))
def submit_mapping_case_block(user, index):
mapping = user.get_location_map_case()
if mapping:
caseblock = CaseBlock(
create=False,
case_id=mapping._id,
version=V2,
index=index
)
else:
caseblock = CaseBlock(
create=True,
case_type=const.USER_LOCATION_OWNER_MAP_TYPE,
case_id=location_map_case_id(user),
version=V2,
owner_id=user._id,
index=index,
case_name=const.USER_LOCATION_OWNER_MAP_TYPE.replace('-', ' '),
user_id=const.COMMTRACK_USERNAME,
)
submit_case_blocks(
ElementTree.tostring(
caseblock.as_xml()
),
user.domain,
)
def location_map_case_id(user):
return 'user-owner-mapping-' + user._id
def get_commtrack_location_id(user, domain):
if (
user and
user.get_domain_membership(domain.name) and
user.get_domain_membership(domain.name).location_id and
domain.commtrack_enabled
):
return user.get_domain_membership(domain.name).location_id
else:
return None
def get_case_wrapper(data):
return {
const.SUPPLY_POINT_CASE_TYPE: SupplyPointCase,
}.get(data.get('type'), CommCareCase)
def unicode_slug(text):
return slugify(unicode(unidecode(text)))
def encode_if_needed(val):
return val.encode("utf8") if isinstance(val, unicode) else val
def _fetch_ending_numbers(s):
matcher = re.compile("\d*$")
return matcher.search(s).group()
def generate_code(object_name, existing_codes):
if not object_name:
object_name = 'no name'
matcher = re.compile("[\W\d]+")
name_slug = matcher.sub(
'_',
unicode_slug(object_name.lower())
).strip('_')
postfix = _fetch_ending_numbers(object_name)
while name_slug + postfix in existing_codes:
if postfix:
postfix = str(int(postfix) + 1)
else:
postfix = '1'
return name_slug + postfix