Coverage for portality/tasks/article_deletion_notifications.py: 89%

89 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-20 13:43 +0000

1"""Weekly notifications to publishers about articles deleted in the last week. 

2Collect article details from ArticleTombstone and send a Notification per owner. 

3""" 

4from typing import Dict, List 

5 

6from portality import models, constants 

7from portality.background import BackgroundTask, BackgroundApi 

8from portality.bll.doaj import DOAJ 

9from portality.core import app 

10from portality.lib import dates 

11from portality.tasks.helpers import background_helper 

12from portality.tasks.redis_huey import scheduled_short_queue as queue 

13from portality.util import url_for 

14 

15 

16class ArticleDeletionNotificationsBackgroundTask(BackgroundTask): 

17 __action__ = "article_deletion_notifications" 

18 

19 def run(self): 

20 job = self.background_job 

21 

22 # note we're using the doaj url_for wrapper, not the flask url_for directly, due to the request context hack required 

23 action_url = url_for("publisher.upload_file") 

24 

25 # Query tombstones created in the last week 

26 # Determine date range: last 7 days 

27 since = dates.before_now(7 * 24 * 60 * 60) 

28 q = models.ArticleTombstoneRecentlyDeletedQuery(since=since) 

29 

30 owner_to_items: Dict[str, List[dict]] = {} 

31 

32 for stone in models.ArticleTombstone.iterate_unstable(q.query(), page_size=1000): 

33 owner = stone.owner 

34 if not owner: 

35 continue 

36 

37 bj = stone.bibjson() 

38 title = bj.title 

39 authors = [] 

40 for a in bj.author or []: 

41 n = a.get('name') if isinstance(a, dict) else None 

42 if n: 

43 authors.append(n) 

44 

45 volume = bj.volume 

46 issue = bj.number 

47 start_page = bj.start_page 

48 end_page = bj.end_page 

49 pages = None 

50 if start_page and end_page: 

51 pages = f"{start_page}-{end_page}" 

52 elif start_page: 

53 pages = str(start_page) 

54 issns = bj.issns() 

55 journal_name = bj.journal_title 

56 

57 item = { 

58 'title': title, 

59 'authors': authors, 

60 'volume': volume, 

61 'issue': issue, 

62 'pages': pages, 

63 'issns': issns, 

64 'journal': journal_name, 

65 } 

66 

67 owner_to_items.setdefault(owner, []).append(item) 

68 

69 if not owner_to_items: 

70 job.add_audit_message("No deleted articles in the last week; no notifications sent.") 

71 return 

72 

73 notify_svc = DOAJ.notificationsService() 

74 

75 total_notes = 0 

76 for owner, items in owner_to_items.items(): 

77 acc = models.Account.pull(owner) 

78 if acc is None: 

79 job.add_audit_message(f"Owner account {owner} not found; skipping {len(items)} items") 

80 continue 

81 

82 source_id = "bg:job:" + self.__action__ + ":publisher" 

83 

84 lines = [] 

85 for it in items: 

86 auth = (", ".join(it['authors'])) if it['authors'] else "Unknown author" 

87 issn_str = ", ".join([i for i in (it.get('issns') or []) if i]) 

88 vol_str = f", vol {it['volume']}" if it.get('volume') else "" 

89 iss_str = f", issue {it['issue']}" if it.get('issue') else "" 

90 pg_str = f", pages {it['pages']}" if it.get('pages') else "" 

91 jn = f" ({it['journal']})" if it.get('journal') else "" 

92 line = f"- {it['title'] or 'Untitled'} by {auth}{vol_str}{iss_str}{pg_str} [{issn_str}]{jn}" 

93 lines.append(line) 

94 

95 note = models.Notification() 

96 note.who = owner 

97 note.classification = constants.NOTIFICATION_CLASSIFICATION_STATUS 

98 note.long = notify_svc.long_notification(source_id).format(list_of_articles="\n".join(lines)) 

99 note.short = notify_svc.short_notification(source_id) 

100 note.action = action_url 

101 

102 notify_svc.notify(note) 

103 total_notes += 1 

104 job.add_audit_message(f"Sending notification for owner {owner} with {len(items)} deleted articles") 

105 

106 job.add_audit_message(f"Sent {total_notes} publisher deletion notifications.") 

107 

108 def cleanup(self): 

109 pass 

110 

111 @classmethod 

112 def prepare(cls, username, **kwargs): 

113 job = background_helper.create_job(username, cls.__action__, 

114 queue_id=huey_helper.queue_id) 

115 return job 

116 

117 @classmethod 

118 def submit(cls, background_job): 

119 background_job.save() 

120 execute_article_deletion_notifications.schedule(args=(background_job.id,), 

121 delay=app.config.get('HUEY_ASYNC_DELAY', 10)) 

122 

123 

124huey_helper = ArticleDeletionNotificationsBackgroundTask.create_huey_helper(queue) 

125 

126 

127@huey_helper.register_schedule 

128def scheduled_article_deletion_notifications(): 

129 background_helper.submit_by_bg_task_type(ArticleDeletionNotificationsBackgroundTask) 

130 

131 

132@huey_helper.register_execute(is_load_config=False) 

133def execute_article_deletion_notifications(job_id): 

134 background_helper.execute_by_job_id(job_id, lambda j: ArticleDeletionNotificationsBackgroundTask(j))