Skip to content

Adding new backfill option#643

Open
BillingServ wants to merge 2 commits into
chiefonboarding:masterfrom
BillingServ:add-backfill-option-for-user-ids
Open

Adding new backfill option#643
BillingServ wants to merge 2 commits into
chiefonboarding:masterfrom
BillingServ:add-backfill-option-for-user-ids

Conversation

@BillingServ
Copy link
Copy Markdown

When importing existing employees into ChiefOnboarding, we need to retrieve each user’s ID from the external service (via the manifest/API). This ensures we can properly reference and delete users during offboarding.

To support this, the manifest will need to be updated. Additionally, a button will be added to the integration to automatically fetch and store this information.

@coveralls
Copy link
Copy Markdown
Collaborator

Coverage Status

coverage: 90.612% (-0.4%) from 90.986% — BillingServ:add-backfill-option-for-user-ids into chiefonboarding:master

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an admin-triggered “Backfill IDs” capability for custom integrations by allowing the manifest’s exists block to declare store_data, persisting extracted identifiers into users’ extra_fields, and providing a UI button that runs the lookup asynchronously.

Changes:

  • Add a “Backfill IDs” button in Settings → Integrations and a corresponding admin POST endpoint that enqueues a Django-Q background job.
  • Extend manifest support so exists can declare store_data, and persist extracted values to user.extra_fields when an exists lookup succeeds.
  • Enhance get_value_from_notation to support bracketed filter tokens (e.g., selecting a list item by field match).

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 7 comments.

Show a summary per file
File Description
back/admin/settings/templates/settings_integrations.html Adds “Backfill IDs” action in the integrations settings UI when supported by the integration manifest.
back/admin/integrations/views.py Adds an admin POST view that enqueues the background backfill task and reports status via messages.
back/admin/integrations/utils.py Implements a tokenizer and adds bracket-filter support to notation traversal.
back/admin/integrations/urls.py Registers the new backfill POST endpoint route.
back/admin/integrations/tasks.py Adds the background job that iterates users and runs the exists lookup to populate IDs.
back/admin/integrations/serializers.py Allows exists.store_data in manifest validation.
back/admin/integrations/models.py Updates user_exists to persist exists.store_data fields into extra_fields on successful matches.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread back/admin/settings/templates/settings_integrations.html
integration.manifest.get("exists", {}).get("store_data", {}).keys()
)

users = get_user_model().objects.exclude(email="").order_by("id")
Comment on lines +42 to +44
try:
result = integration.user_exists(user, save_result=False)
except Exception as e:
Comment on lines +38 to +39
# skip users who already have all backfill keys set
if store_keys and all(k in user.extra_fields for k in store_keys):
Comment on lines +1 to +55
def _tokenize_notation(notation):
# split on '.' but keep [...] groups intact, so values inside a filter
# expression (which may themselves contain '.', e.g. emails) aren't split
tokens = []
buf = ""
depth = 0
for ch in notation:
if ch == "[":
depth += 1
buf += ch
elif ch == "]":
depth -= 1
buf += ch
elif ch == "." and depth == 0:
if buf:
tokens.append(buf)
buf = ""
else:
buf += ch
if buf:
tokens.append(buf)
return tokens


def get_value_from_notation(notation, value):
# if we don't need to go into props, then just return the value
if notation == "":
return value

notations = notation.split(".")
for notation in notations:
for token in _tokenize_notation(notation):
# filter form: optional_key[field=expected] - pick first list entry
# whose `field` equals `expected`. Useful when the upstream API returns
# an unfiltered list (e.g. Bitwarden /public/members).
if "[" in token and token.endswith("]"):
list_key, _, filter_expr = token.partition("[")
filter_expr = filter_expr[:-1]

if list_key:
try:
value = value[list_key]
except (KeyError, TypeError):
raise KeyError

if "=" not in filter_expr or not isinstance(value, list):
raise KeyError

field, _, expected = filter_expr.partition("=")
for item in value:
if isinstance(item, dict) and str(item.get(field, "")) == expected:
value = item
break
else:
raise KeyError
continue

Comment on lines +540 to +561
# If the user was found and the manifest declares store_data on its
# exists block, capture those values into extra_fields. Lets a single
# lookup populate IDs (e.g. ATLASSIAN_USER_ID, bitwarden_id) for users
# that pre-existed in the upstream system.
store_data = self.manifest["exists"].get("store_data", {})
if user_exists and store_data:
try:
json_response = response.json()
except (ValueError, AttributeError):
json_response = {}
for new_hire_prop, notation in store_data.items():
try:
value = get_value_from_notation(
self._replace_vars(notation), json_response
)
except KeyError:
continue
if value is None:
continue
new_hire.extra_fields[new_hire_prop] = value
new_hire.save()

Comment on lines +250 to +269
class IntegrationBackfillIDsView(AdminPermMixin, View):
def post(self, request, pk):
integration = get_object_or_404(Integration, pk=pk)
if not integration.can_backfill_ids:
messages.error(
request,
_("This integration has no store_data declared on its exists block."),
)
return redirect("settings:integrations")
async_task(
"admin.integrations.tasks.backfill_integration_ids",
integration.id,
task_name=f"Backfill IDs: {integration.name}",
)
messages.success(
request,
_("Backfill started for %(name)s. Users' extra fields will populate "
"as the lookup runs in the background.") % {"name": integration.name},
)
return redirect("settings:integrations")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants