Skip to content

Commit be26ba9

Browse files
committed
refactor: clean up registrants fetching logic
1 parent c57e1b3 commit be26ba9

1 file changed

Lines changed: 71 additions & 46 deletions

File tree

g2p_social_registry_importer/models/fetch_social_registry_beneficiary.py

Lines changed: 71 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -286,7 +286,16 @@ def build_request_body(self, today_isoformat, message_id, transaction_id, refere
286286
"message": message,
287287
}
288288

289-
def get_graphql_query(self, query_fields, current_limit=None, current_offset=None, **kwargs):
289+
def get_graphql_query(self, query_fields=None, effective_limit=None, effective_offset=None, **kwargs):
290+
"""
291+
Build GraphQL query with pagination and filtering.
292+
293+
Args:
294+
query_fields: GraphQL fields to include in the query
295+
effective_limit: Explicit limit (takes precedence over kwargs['limit'])
296+
effective_offset: Explicit offset (takes precedence over kwargs['offset'])
297+
**kwargs: Additional query parameters (limit/offset here are ignored)
298+
"""
290299
params = []
291300

292301
if self.target_registry:
@@ -297,10 +306,10 @@ def get_graphql_query(self, query_fields, current_limit=None, current_offset=Non
297306
params.append(f'lastSyncDate: "{self.last_sync_date.strftime("%Y-%m-%dT%H:%M:%S.000Z")}"')
298307

299308
# 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}")
309+
if effective_limit is not None:
310+
params.append(f"limit: {effective_limit}")
311+
if effective_offset is not None:
312+
params.append(f"offset: {effective_offset}")
304313

305314
# Handle additional kwargs (skip ones already handled)
306315
for key, value in kwargs.items():
@@ -319,7 +328,10 @@ def get_graphql_query(self, query_fields, current_limit=None, current_offset=Non
319328
params_str = ", ".join(params)
320329

321330
# Construct the final GraphQL query
322-
graphql_query = f"{{ getRegistrants({params_str}) {query_fields} totalRegistrantCount }}"
331+
if query_fields is None:
332+
graphql_query = "{totalRegistrantCount}"
333+
else:
334+
graphql_query = f"{{ getRegistrants({params_str}) {query_fields} totalRegistrantCount }}"
323335

324336
_logger.debug("updated graphql query: %s", graphql_query)
325337
return graphql_query.strip()
@@ -340,12 +352,7 @@ def get_total_registrant_count(self):
340352
transaction_id = str(uuid.uuid4())
341353
reference_id = str(uuid.uuid4())
342354

343-
count_query_fields = "{ totalRegistrantCount }"
344-
query_params = self.get_parsed_query_params() or {}
345-
346-
# Override the query_fields explicitly
347-
graphql_query = self.get_graphql_query(query_fields=count_query_fields, **query_params)
348-
# Create request body for count
355+
graphql_query = self.get_graphql_query()
349356
data = self.build_request_body(
350357
today_isoformat, message_id, transaction_id, reference_id, graphql_query
351358
)
@@ -678,51 +685,62 @@ def fetch_social_registry_beneficiary(self):
678685
query_fields = self.query_fields.strip()
679686
query_params = self.get_parsed_query_params()
680687

681-
max_registrant_per_batch = int(
688+
max_registrants_per_batch = int(
682689
self.env["ir.config_parameter"]
683690
.sudo()
684691
.get_param("g2p_import_social_registry.max_registrants_count_job_queue", 100)
685692
)
686693

687-
total_processed_records = 0 # Initialize variable
694+
total_processed_registrants = 0
688695

689-
# Determine processing parameters based on conditions
690696
if query_params is None:
691-
# fetch all records
697+
# No query parameters provided → fetch all records from the beginning
698+
# Example: query_params = None
699+
# → fetch all records (e.g., 500), starting from index 0
700+
692701
total_count = self.get_total_registrant_count()
693702
if total_count == 0:
694703
message = _("No registrants found in the Social Registry.")
695704
kind = "warning"
696-
raise ValueError("Empty Social Registry")
697-
current_limit = total_count
698-
current_offset = 0
705+
effective_limit = total_count
706+
effective_offset = 0
699707
query_params = {}
700-
701708
else:
709+
# Query parameters provided
702710
limit = query_params.get("limit")
703-
offset = query_params.get("offset")
711+
offset = query_params.get("offset", 0)
712+
713+
if limit is not None:
714+
# 'limit' is provided → use given limit and offset
715+
# Example: query_params = {'limit': 100, 'offset': 200}
716+
# → fetch 100 records starting from the 201st record
704717

705-
if offset is not None:
706-
# limit with offset - paginated fetch from specific offset
707-
current_limit = limit
708-
current_offset = offset
718+
effective_limit = limit
719+
effective_offset = offset
709720
else:
710-
# limit without offset - fetch from beginning
711-
current_limit = limit
712-
current_offset = 0
721+
# 'limit' is not provided → treat as fetch all from 'offset'
722+
# Example: query_params = {'offset': 50}
723+
# → fetch all remaining records starting from the 51st
724+
725+
total_count = self.get_total_registrant_count()
726+
if total_count == 0:
727+
message = _("No registrants found in the Social Registry.")
728+
kind = "warning"
729+
effective_limit = total_count
730+
effective_offset = offset
713731

714732
_logger.info(
715733
"Starting Social Registry fetch - Limit: %s, Offset: %s, Batch size: %s",
716-
current_limit,
717-
current_offset,
718-
max_registrant_per_batch,
734+
effective_limit,
735+
effective_offset,
736+
max_registrants_per_batch,
719737
)
720738

721739
# Process based on batch size threshold
722-
if max_registrant_per_batch >= current_limit:
740+
if max_registrants_per_batch >= effective_limit:
723741
# Synchronous processing
724742
paginated_query = self.get_graphql_query(
725-
query_fields, current_limit, current_offset, **query_params
743+
query_fields, effective_limit, effective_offset, **query_params
726744
)
727745

728746
registrants = self.fetch_registrants_batch(paginated_query)
@@ -732,7 +750,7 @@ def fetch_social_registry_beneficiary(self):
732750
message = _("Successfully processed %s registrants.") % len(registrants)
733751
kind = "success"
734752
self.process_registrants(registrants)
735-
total_processed_records = len(registrants)
753+
total_processed_registrants = len(registrants)
736754
else:
737755
message = _(
738756
"No registrants found. "
@@ -743,9 +761,12 @@ def fetch_social_registry_beneficiary(self):
743761

744762
else:
745763
# Process asynchronously in batches
746-
while total_processed_records < current_limit:
764+
current_offset = effective_offset
765+
766+
while total_processed_registrants < effective_limit:
747767
# Calculate batch size for this iteration
748-
batch_size = min(max_registrant_per_batch, current_limit - total_processed_records)
768+
remaining_records = effective_limit - total_processed_registrants
769+
batch_size = min(max_registrants_per_batch, remaining_records)
749770

750771
# Build and execute paginated query
751772
paginated_query = self.get_graphql_query(
@@ -756,35 +777,39 @@ def fetch_social_registry_beneficiary(self):
756777

757778
if not registrants:
758779
message = (
759-
_("No more registrants to process. Processed %s total.") % total_processed_records
780+
_("No more registrants to process. Processed %s total.")
781+
% total_processed_registrants
760782
)
761-
kind = "warning" if total_processed_records == 0 else "success"
783+
kind = "warning" if total_processed_registrants == 0 else "success"
762784
break
763785

764786
# Process batch asynchronously
765787
sticky = True
766788
self.process_registrants_async(registrants, len(registrants))
767789

768790
# Update counters
769-
total_processed_records += len(registrants)
770-
current_offset += len(registrants)
791+
batch_count = len(registrants)
792+
total_processed_registrants += batch_count
793+
current_offset += batch_count
771794

772795
_logger.info(
773796
"Processed batch: %s registrants (total: %s/%s)",
774-
len(registrants),
775-
total_processed_records,
776-
current_limit,
797+
batch_count,
798+
total_processed_registrants,
799+
effective_limit,
777800
)
778801

779802
# Set final message for successful async processing
780-
if total_processed_records > 0 and kind != "warning":
803+
if total_processed_registrants > 0 and kind != "warning":
781804
message = (
782805
_("Successfully queued %s registrants for asynchronous processing.")
783-
% total_processed_records
806+
% total_processed_registrants
784807
)
785808
kind = "success"
786809

787-
_logger.info("Completed Social Registry fetch. Processed %s registrants", total_processed_records)
810+
_logger.info(
811+
"Completed Social Registry fetch. Processed %s registrants", total_processed_registrants
812+
)
788813

789814
self.last_sync_date = fields.Datetime.now()
790815
end_time = fields.Datetime.now()

0 commit comments

Comments
 (0)