Skip to content

Commit c57e1b3

Browse files
committed
Improve GraphQL query_params handling
1 parent 6fd4928 commit c57e1b3

3 files changed

Lines changed: 87 additions & 95 deletions

File tree

g2p_social_registry_importer/data/search_criteria.xml

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,7 @@
7474
}
7575
</field>
7676

77-
<field name="query">{
78-
getRegistrants(limit:2){
77+
<field name="query_fields">{
7978
name,
8079
isGroup,
8180
givenName,
@@ -125,7 +124,7 @@
125124
expiryDate
126125
}
127126
}
128-
}
127+
129128
</field>
130129
</record>
131130
</odoo>

g2p_social_registry_importer/models/fetch_social_registry_beneficiary.py

Lines changed: 84 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class G2PFetchSocialRegistryBeneficiary(models.Model):
3636
domain=("[('target_type', '=', target_registry)]"),
3737
)
3838
query_params = fields.Text(default="""{}""")
39-
query = fields.Text(required=True, default="""{}""")
39+
query_fields = fields.Text(required=True, default="""{}""")
4040
output_mapping = fields.Text(required=True, default="""{}""")
4141

4242
last_sync_date = fields.Datetime(string="Last synced on", required=False)
@@ -286,72 +286,42 @@ def build_request_body(self, today_isoformat, message_id, transaction_id, refere
286286
"message": message,
287287
}
288288

289-
def get_graphql_query(self, limit=None, offset=None, order=None):
290-
query = self.query.strip()
291-
292-
graphql_query = query[0:-1] + "totalRegistrantCount }"
293-
_logger.debug(query)
289+
def get_graphql_query(self, query_fields, current_limit=None, current_offset=None, **kwargs):
290+
params = []
294291

295292
if self.target_registry:
296-
index = graphql_query.find("(") + 1
297293
is_group = str(self.target_registry == "group").lower()
298-
if not index:
299-
get_registrants_index = graphql_query.find("getRegistrants") + 14
300-
graphql_query = (
301-
graphql_query[:get_registrants_index] + "()" + graphql_query[get_registrants_index:]
302-
)
303-
index = graphql_query.find("(") + 1
304-
305-
graphql_query = graphql_query[:index] + f"isGroup: {is_group}" + graphql_query[index:]
306-
307-
else:
308-
graphql_query = graphql_query[:index] + f"isGroup: {is_group}," + graphql_query[index:]
294+
params.append(f"isGroup: {is_group}")
309295

310296
if self.last_sync_date:
311-
index = graphql_query.find("(") + 1
312-
if not index:
313-
get_registrants_index = graphql_query.find("getRegistrants") + 14
314-
graphql_query = (
315-
graphql_query[:get_registrants_index] + "()" + graphql_query[get_registrants_index:]
316-
)
317-
index = graphql_query.find("(") + 1
318-
graphql_query = (
319-
graphql_query[:index]
320-
+ f'lastSyncDate: "{self.last_sync_date.strftime("%Y-%m-%dT%H:%M:%S.000Z")}"'
321-
+ graphql_query[index:]
322-
)
297+
params.append(f'lastSyncDate: "{self.last_sync_date.strftime("%Y-%m-%dT%H:%M:%S.000Z")}"')
298+
299+
# Add pagination parameters explicitly
300+
if current_limit is not None:
301+
params.append(f"limit: {current_limit}")
302+
if current_offset is not None:
303+
params.append(f"offset: {current_offset}")
304+
305+
# Handle additional kwargs (skip ones already handled)
306+
for key, value in kwargs.items():
307+
if key in ["limit", "offset", "isGroup", "lastSyncDate"]:
308+
continue
309+
310+
if value is not None:
311+
if isinstance(value, str):
312+
params.append(f'{key}: "{value}"')
313+
elif isinstance(value, bool):
314+
params.append(f"{key}: {str(value).lower()}")
315+
else:
316+
params.append(f"{key}: {value}")
323317

324-
else:
325-
graphql_query = (
326-
graphql_query[:index]
327-
+ f'lastSyncDate: "{self.last_sync_date.strftime("%Y-%m-%dT%H:%M:%S.000Z")}",'
328-
+ graphql_query[index:]
329-
)
330-
# Add pagination parameters
331-
if limit is not None or offset is not None:
332-
index = graphql_query.find("(") + 1
333-
pagination_params = []
334-
335-
if limit is not None:
336-
pagination_params.append(f"limit: {limit}")
337-
if offset is not None:
338-
pagination_params.append(f"offset: {offset}")
339-
if order is not None:
340-
pagination_params.append(f'order: "{order}"')
341-
342-
pagination_str = ", ".join(pagination_params)
343-
344-
if index == 0:
345-
get_registrants_index = graphql_query.find("getRegistrants") + 14
346-
graphql_query = (
347-
graphql_query[:get_registrants_index] + "()" + graphql_query[get_registrants_index:]
348-
)
349-
index = graphql_query.find("(") + 1
350-
graphql_query = graphql_query[:index] + pagination_str + graphql_query[index:]
351-
else:
352-
graphql_query = graphql_query[:index] + pagination_str + "," + graphql_query[index:]
318+
# Build the parameters string
319+
params_str = ", ".join(params)
320+
321+
# Construct the final GraphQL query
322+
graphql_query = f"{{ getRegistrants({params_str}) {query_fields} totalRegistrantCount }}"
353323

354-
_logger.debug("updated graphql query", graphql_query)
324+
_logger.debug("updated graphql query: %s", graphql_query)
355325
return graphql_query.strip()
356326

357327
def get_total_registrant_count(self):
@@ -370,12 +340,14 @@ def get_total_registrant_count(self):
370340
transaction_id = str(uuid.uuid4())
371341
reference_id = str(uuid.uuid4())
372342

373-
# Build count-only query
374-
count_query = "{totalRegistrantCount}"
343+
count_query_fields = "{ totalRegistrantCount }"
344+
query_params = self.get_parsed_query_params() or {}
375345

346+
# Override the query_fields explicitly
347+
graphql_query = self.get_graphql_query(query_fields=count_query_fields, **query_params)
376348
# Create request body for count
377349
data = self.build_request_body(
378-
today_isoformat, message_id, transaction_id, reference_id, count_query
350+
today_isoformat, message_id, transaction_id, reference_id, graphql_query
379351
)
380352

381353
# Make request
@@ -702,65 +674,84 @@ def fetch_social_registry_beneficiary(self):
702674

703675
try:
704676
self.write({"job_status": "running", "start_datetime": fields.Datetime.now()})
677+
678+
query_fields = self.query_fields.strip()
705679
query_params = self.get_parsed_query_params()
706-
limit = query_params.get("limit")
707-
offset = query_params.get("offset", 0)
708-
order = query_params.get("order", "id asc")
709680

710-
current_offset = offset or 0
711-
total_processed_records = 0
681+
max_registrant_per_batch = int(
682+
self.env["ir.config_parameter"]
683+
.sudo()
684+
.get_param("g2p_import_social_registry.max_registrants_count_job_queue", 100)
685+
)
712686

713-
# If the limit is not specified in query_params, use the total count as the limit
714-
if not limit:
687+
total_processed_records = 0 # Initialize variable
688+
689+
# Determine processing parameters based on conditions
690+
if query_params is None:
691+
# fetch all records
715692
total_count = self.get_total_registrant_count()
716693
if total_count == 0:
717694
message = _("No registrants found in the Social Registry.")
718695
kind = "warning"
719696
raise ValueError("Empty Social Registry")
720-
limit = total_count
697+
current_limit = total_count
698+
current_offset = 0
699+
query_params = {}
721700

722-
# max_registrant is the batch size for pagination and queue
723-
max_registrant_per_batch = int(
724-
self.env["ir.config_parameter"]
725-
.sudo()
726-
.get_param("g2p_import_social_registry.max_registrants_count_job_queue", 100)
727-
)
701+
else:
702+
limit = query_params.get("limit")
703+
offset = query_params.get("offset")
704+
705+
if offset is not None:
706+
# limit with offset - paginated fetch from specific offset
707+
current_limit = limit
708+
current_offset = offset
709+
else:
710+
# limit without offset - fetch from beginning
711+
current_limit = limit
712+
current_offset = 0
728713

729714
_logger.info(
730715
"Starting Social Registry fetch - Limit: %s, Offset: %s, Batch size: %s",
731-
limit,
716+
current_limit,
732717
current_offset,
733718
max_registrant_per_batch,
734719
)
735720

736-
if max_registrant_per_batch >= limit:
737-
# Fetch Records synchronously
738-
paginated_query = self.get_graphql_query(limit, current_offset, order)
721+
# Process based on batch size threshold
722+
if max_registrant_per_batch >= current_limit:
723+
# Synchronous processing
724+
paginated_query = self.get_graphql_query(
725+
query_fields, current_limit, current_offset, **query_params
726+
)
727+
739728
registrants = self.fetch_registrants_batch(paginated_query)
740729

741730
if registrants:
742731
sticky = True
743-
message = _("Successfully processed %s registrants synchronously.") % len(registrants)
732+
message = _("Successfully processed %s registrants.") % len(registrants)
744733
kind = "success"
745734
self.process_registrants(registrants)
746-
total_processed_records += len(registrants)
735+
total_processed_records = len(registrants)
747736
else:
748737
message = _(
749738
"No registrants found. "
750739
"Verify last sync date or "
751740
"check if Social Registry contains data."
752741
)
753742
kind = "warning"
743+
754744
else:
755745
# Process asynchronously in batches
756-
while total_processed_records < limit:
757-
# Calculate the number of records to fetch in this batch
758-
batch_size = min(max_registrant_per_batch, limit - total_processed_records)
746+
while total_processed_records < current_limit:
747+
# Calculate batch size for this iteration
748+
batch_size = min(max_registrant_per_batch, current_limit - total_processed_records)
759749

760-
# Use batch_size as the limit in the paginated GraphQL query
761-
paginated_query = self.get_graphql_query(batch_size, current_offset, order)
750+
# Build and execute paginated query
751+
paginated_query = self.get_graphql_query(
752+
query_fields, batch_size, current_offset, **query_params
753+
)
762754

763-
# Fetch the registrants from the Social Registry
764755
registrants = self.fetch_registrants_batch(paginated_query)
765756

766757
if not registrants:
@@ -770,20 +761,22 @@ def fetch_social_registry_beneficiary(self):
770761
kind = "warning" if total_processed_records == 0 else "success"
771762
break
772763

773-
# Process Records asynchronously
764+
# Process batch asynchronously
774765
sticky = True
775766
self.process_registrants_async(registrants, len(registrants))
776767

768+
# Update counters
777769
total_processed_records += len(registrants)
778770
current_offset += len(registrants)
779771

780772
_logger.info(
781773
"Processed batch: %s registrants (total: %s/%s)",
782774
len(registrants),
783775
total_processed_records,
784-
limit,
776+
current_limit,
785777
)
786778

779+
# Set final message for successful async processing
787780
if total_processed_records > 0 and kind != "warning":
788781
message = (
789782
_("Successfully queued %s registrants for asynchronous processing.")

g2p_social_registry_importer/views/fetch_social_registry_beneficiary_views.xml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@
110110
<field name="target_registry" />
111111
<field name="target_program" />
112112
<field name="query_params" />
113-
<field name="query" />
113+
<field name="query_fields" />
114114
<field name="output_mapping" />
115115
<field name="last_sync_date" />
116116
<field

0 commit comments

Comments
 (0)