Skip to content

Commit 5127794

Browse files
committed
Fix webhook assets
1 parent 89594fd commit 5127794

File tree

3 files changed

+44
-47
lines changed

3 files changed

+44
-47
lines changed

landolfio/inventory/resource_types.py

Lines changed: 31 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -42,73 +42,66 @@ def process_webhook_event(
4242
data: dict,
4343
event: WebhookEvent,
4444
):
45-
logger.info(
46-
f"Processing {event.value} for {cls.entity_type_name} {resource_id}"
47-
)
48-
4945
# If no data, the asset was deleted
5046
if not data:
5147
return cls.delete_from_moneybird(resource_id)
5248

5349
# Check if asset already exists locally
5450
try:
5551
asset = cls.get_queryset().get(moneybird_asset_id=resource_id)
56-
logger.info(
57-
f"Asset {resource_id} already exists locally, refreshing from Moneybird"
58-
)
5952
asset.refresh_from_moneybird()
6053

6154
# If this is a created event and the name doesn't match, update Moneybird
6255
if event.value == "company_assets_asset_created":
6356
moneybird_name = data.get("name", "")
6457
if moneybird_name and moneybird_name != asset.name:
6558
logger.info(
66-
f"Asset name mismatch: Moneybird has '{moneybird_name}', local has '{asset.name}'. Updating Moneybird."
59+
f"Updating Moneybird asset name from '{moneybird_name}' to '{asset.name}'"
6760
)
6861
asset.update_on_moneybird()
6962

7063
return asset
7164
except cls.model.DoesNotExist:
7265
# Asset doesn't exist locally - try to find by name and link
73-
asset_name = data.get("name", "")
74-
if asset_name:
75-
try:
76-
asset = cls.get_queryset().get(
77-
name=asset_name, moneybird_asset_id__isnull=True
78-
)
79-
logger.info(
80-
f"Found existing asset with name '{asset_name}', linking to Moneybird asset {resource_id}"
81-
)
82-
asset.moneybird_asset_id = resource_id
83-
asset.refresh_from_moneybird()
66+
moneybird_name = data.get("name", "")
67+
if not moneybird_name:
68+
logger.warning(f"Asset {resource_id} has no name, cannot match")
69+
return None
8470

85-
# Check if name needs updating on Moneybird
86-
if asset_name != asset.name:
87-
logger.info(
88-
f"Linked asset name differs from Moneybird name. Updating Moneybird from '{asset_name}' to '{asset.name}'."
89-
)
90-
asset.update_on_moneybird()
71+
# Try to find exact match (case-insensitive)
72+
try:
73+
asset = cls.get_queryset().get(
74+
name__iexact=moneybird_name, moneybird_asset_id__isnull=True
75+
)
76+
logger.info(
77+
f"Linking local asset '{asset.name}' to Moneybird asset {resource_id}"
78+
)
79+
asset.moneybird_asset_id = resource_id
80+
asset.save(update_fields=["moneybird_asset_id"])
81+
asset.refresh_from_moneybird()
9182

92-
return asset
93-
except cls.model.DoesNotExist:
83+
# Update Moneybird if names differ in case
84+
if moneybird_name != asset.name:
9485
logger.info(
95-
f"No existing asset found with name '{asset_name}' to link"
96-
)
97-
except cls.model.MultipleObjectsReturned:
98-
logger.warning(
99-
f"Multiple assets found with name '{asset_name}', cannot auto-link"
86+
f"Updating Moneybird asset name from '{moneybird_name}' to '{asset.name}'"
10087
)
101-
else:
102-
logger.warning(f"Asset {resource_id} has no name, cannot match")
103-
return None
88+
asset.update_on_moneybird()
89+
90+
return asset
91+
except cls.model.DoesNotExist:
92+
return None
93+
except cls.model.MultipleObjectsReturned:
94+
logger.warning(
95+
f"Multiple assets found with name '{moneybird_name}', cannot auto-link"
96+
)
97+
return None
10498

10599
@classmethod
106100
def delete_from_moneybird(cls, resource_id: str):
107-
logger.info(f"Asset {resource_id} deleted on Moneybird")
108101
try:
109102
asset = cls.get_queryset().get(moneybird_asset_id=resource_id)
110103
logger.info(
111-
f"Unlinking local asset {asset.id} from Moneybird asset {resource_id}"
104+
f"Unlinking local asset '{asset.name}' from deleted Moneybird asset"
112105
)
113106
asset.moneybird_asset_id = None
114107
asset.moneybird_data = None
@@ -123,4 +116,4 @@ def delete_from_moneybird(cls, resource_id: str):
123116
]
124117
)
125118
except cls.model.DoesNotExist:
126-
logger.info(f"Asset {resource_id} not found locally, nothing to unlink")
119+
pass

landolfio/moneybird/webhooks/processing.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,25 +10,25 @@
1010

1111
def process_webhook_payload(payload: MoneybirdResource) -> None:
1212
if payload["action"] == "test_webhook":
13-
logging.info(f"Received test webhook from Moneybird: {payload}")
13+
logging.info(f"Received test webhook from Moneybird")
1414
return
1515

1616
if payload["webhook_id"] != settings.MONEYBIRD_WEBHOOK_ID:
17-
logging.error("Received webhook with wrong id")
17+
logging.error(f"Received webhook with wrong id")
1818
return
1919

2020
if payload["webhook_token"] != settings.MONEYBIRD_WEBHOOK_TOKEN:
2121
logging.error("Received webhook with wrong token")
2222
return
2323

2424
if int(payload["administration_id"]) != settings.MONEYBIRD_ADMINISTRATION_ID:
25-
logging.error("Received webhook for wrong administration")
25+
logging.error(f"Received webhook for wrong administration")
2626
return
2727

2828
try:
2929
event = WebhookEvent(payload["action"])
3030
except ValueError:
31-
logging.error("Received webhook with invalid event")
31+
logging.error(f"Received webhook with invalid event: {payload['action']}")
3232
return
3333

3434
entity_type = payload["entity_type"]
@@ -42,17 +42,13 @@ def process_webhook_payload(payload: MoneybirdResource) -> None:
4242
if resource_type is None and entity_type.startswith("CompanyAssets::"):
4343
resource_type = get_moneybird_resource_type_for_entity("company_assets_asset")
4444
if resource_type:
45-
logging.info(
46-
f"Routing {entity_type} webhook (event: {event.value}, entity_id: {entity_id}) to AssetResourceType"
47-
)
4845
# For CompanyAssets sub-entities (disposal, source, value_change), extract asset_id from entity_data
4946
if (
5047
entity_type != "CompanyAssets::Asset"
5148
and entity_data
5249
and "asset_id" in entity_data
5350
):
5451
asset_id = entity_data["asset_id"]
55-
logging.info(f"Extracted asset_id {asset_id} from {entity_type} entity")
5652
entity_id = asset_id
5753

5854
if resource_type is None:

landolfio/moneybird/webhooks/views.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,20 @@ def __contains__(self, item):
2929
@require_POST
3030
@non_atomic_requests
3131
def webhook_receive(request):
32+
import logging
33+
34+
logger = logging.getLogger(__name__)
35+
3236
idempotency_key = request.headers.get("Idempotency-Key")
3337
if idempotency_key in webhook_cache:
3438
return HttpResponse("Webhook already processed.", content_type="text/plain")
3539

3640
payload = json.loads(request.body)
37-
process_webhook_payload(payload)
41+
42+
try:
43+
process_webhook_payload(payload)
44+
except Exception as e:
45+
logger.error(f"Error processing webhook: {e}", exc_info=True)
3846

3947
webhook_cache.add(idempotency_key)
4048

0 commit comments

Comments
 (0)