from django.db import transaction from django.db.models.signals import post_save from rest_framework import status from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from utils.cache import defer_cache_invalidation @action(detail=False, methods=["post"], url_path="bulk-delete") def bulk_delete_items(self, request, *args, **kwargs): """ Universal bulk delete action for all ModelViewSets. Expects JSON body: {"ids": [1, 2, 3]} """ ids = request.data.get("ids") or request.data.get("item_ids") or [] if not isinstance(ids, list) or not ids: return Response( {"detail": "A non-empty list of 'ids' is required."}, status=status.HTTP_400_BAD_REQUEST, ) base_qs = self.get_queryset() model = base_qs.model target_qs = model.objects.filter(pk__in=ids) # Track affected playlists if deleting Podcast or Video items affected_playlists = [] if hasattr(model, "playlist_appearances"): try: rel_model = model._meta.get_field("playlist_appearances").related_model playlist_field = rel_model._meta.get_field("playlist").related_model playlist_ids = list( rel_model.objects.filter(**{f"{model._meta.model_name}_id__in": ids}) .values_list("playlist_id", flat=True) .distinct() ) if playlist_ids: affected_playlists = list(playlist_field.objects.filter(id__in=playlist_ids)) except Exception: affected_playlists = [] with defer_cache_invalidation(), transaction.atomic(): if hasattr(model, "soft_delete") and getattr(self.__class__, "perform_destroy", None) is not ModelViewSet.perform_destroy: instances = list(target_qs) for inst in instances: self.perform_destroy(inst) deleted_count = len(instances) else: deleted_count, _ = target_qs.delete() for pl in affected_playlists: if hasattr(pl, "calculate_total_time"): pl.total_time = pl.calculate_total_time() pl.save(update_fields=["total_time"]) if model._meta.app_label == "hadis": try: from apps.hadis.serializers import hadis as hadis_serializers hadis_serializers._EDITION_METADATA_MEM = None except Exception: pass try: from apps.hadis.signals import invalidate_hadis_cache invalidate_hadis_cache() except Exception: pass return Response( {"status": "success", "deleted_count": deleted_count}, status=status.HTTP_200_OK, ) @action(detail=False, methods=["post"], url_path="bulk-status") def bulk_update_status(self, request, *args, **kwargs): """ Universal bulk status update action for all ModelViewSets. Expects JSON body: {"ids": [1, 2, 3], "status": true} """ ids = request.data.get("ids") or request.data.get("item_ids") or [] raw_status = request.data.get("status") if not isinstance(ids, list) or not ids or raw_status is None: return Response( {"detail": "'ids' and 'status' are required."}, status=status.HTTP_400_BAD_REQUEST, ) if isinstance(raw_status, str): new_status = raw_status.lower() in ("true", "1", "yes", "active") else: new_status = bool(raw_status) base_qs = self.get_queryset() model = base_qs.model target_qs = model.objects.filter(pk__in=ids) field_names = {f.name for f in model._meta.get_fields()} update_kwargs = {} if "status" in field_names: update_kwargs["status"] = new_status elif "is_active" in field_names: update_kwargs["is_active"] = new_status else: return Response( {"detail": f"Model {model.__name__} does not have a status/is_active field."}, status=status.HTTP_400_BAD_REQUEST, ) with defer_cache_invalidation(), transaction.atomic(): updated_count = target_qs.update(**update_kwargs) first_obj = target_qs.first() if first_obj: post_save.send(sender=model, instance=first_obj, created=False) return Response( {"status": "success", "updated_count": updated_count}, status=status.HTTP_200_OK, ) def register_modelviewset_bulk_actions(): """ Attaches universal bulk_delete_items ('bulk-delete') and bulk_update_status ('bulk-status') actions to DRF's ModelViewSet so every ModelViewSet router automatically exposes them. """ if not hasattr(ModelViewSet, "bulk_delete_items"): ModelViewSet.bulk_delete_items = bulk_delete_items if not hasattr(ModelViewSet, "bulk_update_status"): ModelViewSet.bulk_update_status = bulk_update_status register_modelviewset_bulk_actions()