-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommcare_post_case_form.py
More file actions
130 lines (96 loc) · 4.17 KB
/
Copy pathcommcare_post_case_form.py
File metadata and controls
130 lines (96 loc) · 4.17 KB
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
import requests
from requests.auth import HTTPDigestAuth
import os
from dotenv import load_dotenv
import uuid
from jinja2 import Template
from datetime import datetime, timezone
import uuid
import itertools
import xmltodict
import json
from dataclasses import dataclass
import pandas as pd
# 1. CommCare Configuration
load_dotenv() # Load environment variables from .env file
DOMAIN = os.getenv("MCDOMAIN")
APP_ID = os.getenv("MCAPP_ID")
USERNAME = os.getenv("MCUSERNAME")
API_KEY = os.getenv("MCAPI_KEY")
MCUSER_ID = os.getenv("MCUSER_ID")
def now_utc() -> str:
"""
Returns a UTC timestamp in ISO-8601 format with the offset as "Z".
e.g. "2020-06-08T18:41:33.207Z"
"""
now = datetime.now(tz=timezone.utc)
now_iso = now.isoformat(timespec='milliseconds')
now_iso_z = now_iso.replace('+00:00', 'Z')
return now_iso_z
form_xmlns = "http://openrosa.org/formdesigner/9098B05D-1C43-4BF7-A4FE-E4A32E2CA2B6"
DEVICE_ID = "device123" # Example device ID, replace as needed
# URL for Form Submission (Replace with your Domain and App ID)
url = f"https://www.commcarehq.org/a/{DOMAIN}/receiver/{APP_ID}/"
submission_id = uuid.uuid4().hex,
OWNER_ID = "41b373b43e484506be6efe90ccf7c065" # Example owner ID, replace as needed
# 2. Define your OpenRosa XML Payload
# Ensure case_id and instanceID are unique UUIDs
def xforms_payload(df, newcid: str) -> str:
print(df.icn_id)
xml_payload = f"""<?xml version="1.0" ?>
<data name="Register ICN"
uiVersion="1"
version="41"
xmlns="{form_xmlns}">
<icn>
<icn_id>{newcid}</icn_id>
<icn_title>updated tile</icn_title>
</icn>
<n0:case case_id="{newcid}"
date_modified="{now_utc()}"
user_id="de8cc5191f9b4e2a846069f0659fa35e"
xmlns:n0="http://commcarehq.org/case/transaction/v2">
<n0:create>
<n0:case_type>icn</n0:case_type>
<n0:owner_id>{OWNER_ID}</n0:owner_id>
<n0:case_name>{df.icn_title}</n0:case_name>
<n0:icn_id>{df.icn_id}</n0:icn_id>
<n0:icn_title>{df.icn_title}</n0:icn_title>
</n0:create>
</n0:case>
<n1:meta xmlns:n1="http://openrosa.org/jr/xforms">
<n1:deviceID>commcare_37478fd5-2730-4a14-a847-84e8848a1ff5</n1:deviceID>
<n1:timeStart>2020-06-08T18:38:13.855Z</n1:timeStart>
<n1:timeEnd>2020-06-08T18:41:33.207Z</n1:timeEnd>
<n1:username>exampleuser</n1:username>
<n1:userID>de8cc5191f9b4e2a846069f0659fa35e</n1:userID>
<n1:instanceID>dca03509-4446-41dc-8352-2bb6f8516c7b</n1:instanceID>
<n2:appVersion xmlns:n2="http://commcarehq.org/xforms">CommCare Version 2.48. Build 461457</n2:appVersion>
</n1:meta>
</data>"""
return xml_payload
# 3. Headers and Payload structure
headers = {'Content-Type': 'application/json'}
# Step 2: Convert the dictionary to a JSON string
#xform = xml_payload #xtract the 'case' part of the JSON for submission
def submit_form():
df = pd.read_csv("icns.csv")
for index, row in df.iterrows():
newcid = uuid.uuid4().hex # Generate a unique case ID
xml_payload = xforms_payload(row, newcid)
print(newcid)
auth = (os.getenv('MCUSERNAME'), os.getenv('MCPASSWORD'))
try:
headers = {'Content-Type': 'text/html; charset=UTF-8'}
response = requests.post(url, xml_payload.encode('utf-8'),
headers=headers, auth=auth)
# 5. Check the result
if response.status_code in [200, 201]:
print("Submission Successful!")
print(f"Response: {response.text}")
else:
print(f"Failed to submit. Status Code: {response.status_code}")
print(f"Error: {response.text}")
except requests.exceptions.RequestException as e:
print(f"HTTP Request failed: {e}")
submit_form()