Repository: hydroshare/hydroshare

Issue:
Management command for published resources
**Describe the feature you'd like and what it will do**
We should have a management command to report on resources published within a timeframe.
Consider also adding to our metrics system

**Additional context**
HS 2.9.2



Discussion:

Resolving patch:
diff --git a/hs_core/management/commands/list_published_by_year.py b/hs_core/management/commands/list_published_by_year.py
new file mode 100644
--- /dev/null
+++ b/hs_core/management/commands/list_published_by_year.py
@@ -0,0 +1,102 @@
+"""Lists all the resources published in a given year.
+"""
+
+from django.core.management.base import BaseCommand
+from django.contrib.auth.models import User
+from hs_core.models import BaseResource
+from hs_access_control.models import PrivilegeCodes
+from hs_core import hydroshare
+from django.db.models import F
+from datetime import timedelta
+from django.utils import timezone
+from django.core.exceptions import ObjectDoesNotExist
+
+
+class Command(BaseCommand):
+    help = "Print resource information"
+
+    def add_arguments(self, parser):
+        # Named (optional) arguments
+        parser.add_argument(
+            '--year',
+            dest='year',
+            help='limit to resources published in a given year'
+        )
+
+        parser.add_argument('--days', type=int, dest='days', help='include resources updated in the last X days')
+
+        parser.add_argument(
+            '--type',
+            dest='type',
+            help='limit to resources of a particular type'
+        )
+
+        parser.add_argument(
+            '--owned_by',
+            dest='owned_by',
+            help='limit to resources owned by specific user'
+        )
+
+    def handle(self, *args, **options):
+        days = options['days']
+        resources = BaseResource.objects.filter(raccess__published=True)
+        owner = options['owned_by']
+        type = options['type']
+
+        if owner is not None:
+            try:
+                owner = User.objects.get(username=owner)
+                resources.filter(r2urp__user=owner,
+                                 r2urp__privilege=PrivilegeCodes.OWNER)
+            except ObjectDoesNotExist:
+                print(f"User matching {owner} not found")
+
+        if type is not None:
+            if type in ["CompositeResource", "CollectionResource"]:
+                resources.filter(resource_type=type)
+            else:
+                print(f"Type {type} is not supported. Must be 'CompositeResource' or 'CollectionResource'")
+
+        resources = resources.order_by(F('updated').asc(nulls_first=True))
+
+        for resource in resources:
+            pub_date = self.get_publication_date(resource)
+            if options['year']:
+                if pub_date.year != int(options['year']):
+                    continue
+            if days:
+                cuttoff_time = timezone.now() - timedelta(days)
+                if not pub_date >= cuttoff_time:
+                    continue
+            self.print_resource(resource, pub_date)
+
+    def get_publication_date(self, resource):
+        published_date = resource.metadata.dates.filter(type="published").first()
+        if not published_date:
+            print(f"Publication date not found for {resource.short_id}")
+        return published_date
+
+    def print_resource(self, res, pub_date):
+        site_url = hydroshare.utils.current_site_url()
+        res_url = site_url + res.absolute_url
+        funding_agencies = res.metadata.funding_agencies.all()
+        print("*" * 100)
+        print(f"{res_url}")
+        print(res.metadata.title.value)
+        print(f"Resource type: {res.resource_type}")
+        if pub_date:
+            print(f"Published on {pub_date}")
+        else:
+            print("Resource has no publication date")
+
+        if funding_agencies:
+            print("Funding agency/agencies:")
+            for f in funding_agencies:
+                print(f.agency_name)
+        else:
+            print("Resource has no funding agency")
+
+        if res.doi:
+            print(res.doi)
+        else:
+            print("Resource has no doi")
diff --git a/hs_tracking/management/commands/stats.py b/hs_tracking/management/commands/stats.py
--- a/hs_tracking/management/commands/stats.py
+++ b/hs_tracking/management/commands/stats.py
@@ -9,7 +9,7 @@
 from django.db.models import Q
 from django.utils import timezone
 import zoneinfo
-from hs_core.models import BaseResource
+from hs_core.models import BaseResource, Date
 from theme.models import UserProfile
 
 from ... import models as hs_tracking
@@ -150,11 +150,17 @@ def resources_details(self):
             'publication status',
             'user type',
             'user id',
-            'resource id'
+            'resource id',
+            'publication date'
         ]
         w.writerow(fields)
         failed_resource_ids = []
         for r in BaseResource.objects.all():
+            try:
+                pub_date = r.metadata.dates.get(type='published')\
+                    .start_date.strftime("%m/%d/%Y %H:%M:%S.%f")
+            except Date.DoesNotExist:
+                pub_date = None
             try:
                 values = [
                     r.metadata.dates.get(type="created").
@@ -165,7 +171,8 @@ def resources_details(self):
                     r.raccess.sharing_status,
                     r.user.userprofile.user_type,
                     r.user_id,
-                    r.short_id
+                    r.short_id,
+                    pub_date
                 ]
                 w.writerow([str(v) for v in values])
 


Test patch: