Coverage for portality/forms/application_processors.py: 82%
532 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 13:43 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-20 13:43 +0000
1from flask import url_for, has_request_context
2from flask_login import current_user
3from wtforms import FormField, FieldList
5from portality import models, constants, app_email
6from portality.bll import DOAJ, exceptions
7from portality.core import app
8from portality.crosswalks.application_form import ApplicationFormXWalk
9from portality.crosswalks.journal_form import JournalFormXWalk
10from portality.lib import dates
11from portality.lib.formulaic import FormProcessor
12from portality.ui.messages import Messages
15class ApplicationProcessor(FormProcessor):
17 def pre_validate(self):
18 # to bypass WTForms insistence that choices on a select field match the value, outside of the actual validation
19 # chain
20 super(ApplicationProcessor, self).pre_validate()
22 def patch_target(self):
23 super().patch_target()
25 self._patch_target_note_id()
27 def _carry_fixed_aspects(self):
28 if self.source is None:
29 raise Exception("Cannot carry data from a non-existent source")
31 now = dates.now_str()
33 # copy over any important fields from the previous version of the object
34 created_date = self.source.created_date if self.source.created_date else now
35 self.target.set_created(created_date)
36 if "id" in self.source.data:
37 self.target.data['id'] = self.source.data['id']
39 # date_applied is now a property of both applications and journals
40 if self.source.date_applied is not None:
41 self.target.date_applied = self.source.date_applied
43 try:
44 if self.source.current_application:
45 self.target.set_current_application(self.source.current_application)
46 except AttributeError:
47 # this means that the source doesn't know about current_applications, which is fine
48 pass
50 try:
51 if self.source.current_journal:
52 self.target.set_current_journal(self.source.current_journal)
53 except AttributeError:
54 # this means that the source doesn't know about current_journals, which is fine
55 pass
57 try:
58 if self.source.related_journal:
59 self.target.set_related_journal(self.source.related_journal)
60 except AttributeError:
61 # this means that the source doesn't know about related_journals, which is fine
62 pass
64 try:
65 if self.source.related_applications:
66 related = self.source.related_applications
67 for rel in related:
68 self.target.add_related_application(rel.get("application_id"), rel.get("date_accepted"))
69 except AttributeError:
70 # this means that the source doesn't know about related_applications, which is fine
71 pass
73 try:
74 if self.source.application_type:
75 self.target.application_type = self.source.application_type
76 except AttributeError:
77 # this means that the source doesn't know about related_journals, which is fine
78 pass
80 try:
81 if self.source.last_withdrawn:
82 self.target.last_withdrawn = self.source.last_withdrawn
83 except AttributeError:
84 # this means that the source doesn't know about related_journals, which is fine
85 pass
87 try:
88 if self.source.last_reinstated:
89 self.target.last_reinstated = self.source.last_reinstated
90 except AttributeError:
91 # this means that the source doesn't know about related_journals, which is fine
92 pass
94 try:
95 if self.source.last_owner_transfer:
96 self.target.last_owner_transfer = self.source.last_owner_transfer
97 except AttributeError:
98 # this means that the source doesn't know about related_journals, which is fine
99 pass
101 try:
102 if self.source.date_rejected:
103 self.target.date_rejected = self.source.date_rejected
104 except AttributeError:
105 # this means that the source doesn't know about related_journals, which is fine
106 pass
108 # if the source is a journal, we need to carry the in_doaj flag
109 if isinstance(self.source, models.Journal):
110 self.target.set_in_doaj(self.source.is_in_doaj())
112 def resetDefaults(self, form):
113 # self.form.resettedFields = []
114 def _values_to_reset(f):
115 return (f.data != "") and (f.data != None) and (f.data != f.default)
116 for field in form:
117 if field.errors:
118 if isinstance(field, FormField):
119 self.resetDefaults(field.form)
120 elif isinstance(field, FieldList):
121 for sub in field:
122 if isinstance(sub, FormField):
123 self.resetDefaults(sub)
124 elif _values_to_reset(sub):
125 sub.data = sub.default
126 elif _values_to_reset(field):
127 # self.form.resettedFields.append({"name": field.name, "data": field.data, "default": field.default})
128 field.data = field.default
130 def _merge_notes_forward(self, allow_delete=False):
131 if self.source is None:
132 raise Exception("Cannot carry data from a non-existent source")
133 if self.target is None:
134 raise Exception("Cannot carry data on to a non-existent target - run the xwalk first")
136 # first off, get the notes (by value) in the target and the notes from the source
137 tnotes = self.target.notes
138 snotes = self.source.notes
140 # for each of the target notes we need to get the original dates from the source notes
141 for n in tnotes:
142 for sn in snotes:
143 if n.get("id") == sn.get("id"):
144 n["date"] = sn.get("date")
146 # record the positions of any blank notes except flags
147 i = 0
148 removes = []
149 for n in tnotes:
150 if not n.get("flag", {}).get("assigned_to", "") and n.get("note").strip() == "":
151 removes.append(i)
152 i += 1
154 # actually remove all the notes marked for deletion
155 removes.sort(reverse=True)
156 for r in removes:
157 tnotes.pop(r)
159 # finally, carry forward any notes that aren't already in the target
160 if not allow_delete:
161 for sn in snotes:
162 found = False
163 for tn in tnotes:
164 if sn.get("id") == tn.get("id"):
165 found = True
166 if not found:
167 tnotes.append(sn)
169 self.target.set_notes(tnotes)
171 def _carry_continuations(self):
172 if self.source is None:
173 raise Exception("Cannot carry data from a non-existent source")
175 try:
176 sbj = self.source.bibjson()
177 tbj = self.target.bibjson()
178 if sbj.replaces:
179 tbj.replaces = sbj.replaces
180 if sbj.is_replaced_by:
181 tbj.is_replaced_by = sbj.is_replaced_by
182 if sbj.discontinued_date:
183 tbj.discontinued_date = sbj.discontinued_date
184 except AttributeError:
185 # this means that the source doesn't know about current_applications, which is fine
186 pass
188 def _validate_status_change(self, source_status, target_status):
189 """ Check whether the editorial pipeline permits a change to the target status for a role.
190 Don't run this for admins, since they can change to any role at any time. """
191 from portality.forms.application_forms import application_statuses
192 choices_for_role = [s.get("value") for s in application_statuses(None, self._formulaic)]
193 # choices_for_role = list(sum(application_statuses(None, self._formulaic), ()))
194 # choices_for_role = list(sum(cls.application_status(role), ())) # flattens the list of tuples
196 # Don't allow edits to application when status is beyond this user's permissions in the pipeline
197 if source_status not in choices_for_role:
198 raise Exception(
199 "You don't have permission to edit applications which are in status {0}.".format(source_status))
201 # Don't permit changes to status in reverse of the editorial process
202 if choices_for_role.index(target_status) < choices_for_role.index(source_status):
203 # Except that editors can revert 'completed' to 'in progress'
204 if self._formulaic.name == 'editor' and source_status == constants.APPLICATION_STATUS_COMPLETED and target_status == constants.APPLICATION_STATUS_IN_PROGRESS:
205 pass
206 else:
207 raise Exception(
208 "You are not permitted to revert the application status from {0} to {1}.".format(source_status,
209 target_status))
211 def _patch_target_note_id(self):
212 if self.target.notes:
213 # set author_id on the note if it's a new note
214 for note in self.target.notes:
215 note_date = dates.parse(note['date'])
216 # FIXME: this feels quite bad, I am not going to fix it now, but
217 # we should probably sort this out in the next version of the processors
218 if not note.get('author_id') and note_date > dates.before_now(60):
219 try:
220 note['author_id'] = current_user.id
221 self.target.add_note_by_dict(note) # We have to explicitly re-add the note, as `.notes` is by value not reference now
222 except AttributeError:
223 # Skip if we don't have a current_user
224 pass
226 def _resolve_flags(self, account):
227 import json
228 # handle flag resolution
229 # check that this form knows about flags
230 if getattr(self.form, "flags", None) is None:
231 return
233 flag = self.form.flags.data
234 if flag["flag_resolved"]:
235 acc_id = account.id if account else "unknown user"
236 resolved = json.loads(flag["flag_resolved"])
237 new_note_text = Messages.FORMS__APPLICATION_FLAG__RESOLVED.format(
238 created_date=dates.human_date(resolved["created"]),
239 author=resolved["author"],
240 assignee=resolved["assignee"],
241 deadline=resolved["deadline"],
242 date=dates.today(),
243 username=acc_id,
244 note=resolved["note"]
245 )
246 new_note = self.target.resolve_flag(resolved["id"], new_note_text, dates.now_str(), acc_id)
247 if not new_note:
248 self.target.add_note(new_note_text, dates.now_str(), id=resolved["id"], author_id=acc_id)
251class NewApplication(ApplicationProcessor):
252 """
253 Public Application Form Context. This is also a sort of demonstrator as to how to implement
254 one, so it will do unnecessary things like override methods that don't actually need to be overridden.
256 This should be used in a context where an unauthenticated user is making a request to put a journal into the
257 DOAJ. It does not have any edit capacity (i.e. the form can only be submitted once), and it does not provide
258 any form fields other than the essential journal bibliographic, application bibliographc and contact information
259 for the suggester. On submission, it will set the status to "pending" and the item will be available for review
260 by the editors
262 ~~NewApplication:FormProcessor~~
263 """
265 ############################################################
266 # PublicApplicationForm versions of FormProcessor lifecycle functions
267 ############################################################
269 def draft(self, account, id=None, *args, **kwargs):
270 # check for validity
271 valid = self.validate()
273 # FIXME: if you can only save a valid draft, you cannot save a draft
274 # the draft to be saved needs to be valid
275 #if not valid:
276 # return None
278 # if not valid, then remove all fields which have validation errors
279 if not valid:
280 self.resetDefaults(self.form)
282 self.form2target()
283 # ~~-> DraftApplication:Model~~
284 draft_application = models.DraftApplication(**self.target.data)
285 if id is not None:
286 draft_application.set_id(id)
288 draft_application.set_application_status("draft")
289 draft_application.set_owner(account.id)
290 draft_application.save()
291 return draft_application
293 def finalise(self, account, save_target=True, email_alert=True, id=None):
294 super(NewApplication, self).finalise()
296 # set some administrative data
297 now = dates.now_str()
298 self.target.date_applied = now
299 if app.config.get("AUTOCHECK_INCOMING", False):
300 self.target.set_application_status(constants.APPLICATION_STATUS_POST_SUBMISSION_REVIEW)
301 else:
302 self.target.set_application_status(constants.APPLICATION_STATUS_PENDING)
303 self.target.set_owner(account.id)
304 self.target.set_last_manual_update()
306 if id:
307 # ~~-> Application:Model~~
308 replacing = models.Application.pull(id)
309 if replacing is None:
310 self.target.set_id(id)
311 else:
312 if replacing.application_status == constants.APPLICATION_STATUS_PENDING and replacing.owner == account.id:
313 self.target.set_id(id)
314 self.target.set_created(replacing.created_date)
316 # Finally save the target
317 if save_target:
318 self.target.save()
319 # a draft may have been saved, so also remove that
320 if id:
321 models.DraftApplication.remove_by_id(id)
323 # trigger an application created event
324 eventsSvc = DOAJ.eventsService()
325 eventsSvc.trigger(models.Event(constants.EVENT_APPLICATION_CREATED, account.id, {
326 "application": self.target.data
327 }))
329 # Kick off the post-submission review
330 if app.config.get("AUTOCHECK_INCOMING", False):
331 # FIXME: imports are delayed because of a circular import problem buried in portality.decorators
332 from portality.tasks.application_autochecks import ApplicationAutochecks
333 from portality.tasks.helpers import background_helper
334 background_helper.submit_by_bg_task_type(ApplicationAutochecks,
335 application=self.target.id,
336 status_on_complete=constants.APPLICATION_STATUS_PENDING)
339class AdminApplication(ApplicationProcessor):
340 """
341 Managing Editor's Application Review form. Should be used in a context where the form warrants full
342 admin priviledges. It will permit conversion of applications to journals, and assignment of owner account
343 as well as assignment to editorial group.
345 ~~ManEdApplication:FormProcessor~~
346 """
348 def pre_validate(self):
349 # to bypass WTForms insistence that choices on a select field match the value, outside of the actual validation
350 # chain
351 super(AdminApplication, self).pre_validate()
352 self.form.editor.validate_choice = False
353 # self.form.editor.choices = [(self.form.editor.data, self.form.editor.data)]
355 # TODO: Should quick_reject be set through this form at all?
356 self.form.quick_reject.validate_choice = False
357 # self.form.quick_reject.choices = [(self.form.quick_reject.data, self.form.quick_reject.data)]
359 def patch_target(self):
360 super(AdminApplication, self).patch_target()
362 # This patches the target with things that shouldn't change from the source
363 self._carry_fixed_aspects()
364 self._merge_notes_forward(allow_delete=True)
366 # NOTE: this means you can't unset an owner once it has been set. But you can change it.
367 if (self.target.owner is None or self.target.owner == "") and (self.source.owner is not None):
368 self.target.set_owner(self.source.owner)
370 def finalise(self, account, save_target=True, email_alert=True):
371 """
372 account is the administrator account carrying out the action
373 """
375 if self.source is None:
376 raise Exception(Messages.EXCEPTION_EDITING_NON_EXISTING_APPLICATION)
378 if self.source.application_status == constants.APPLICATION_STATUS_ACCEPTED:
379 raise Exception(Messages.EXCEPTION_EDITING_ACCEPTED_JOURNAL)
381 if self.source.current_journal is not None:
382 j = models.Journal.pull(self.source.current_journal)
383 if j is None:
384 raise Exception(Messages.EXCEPTION_EDITING_DELETED_JOURNAL)
385 elif not j.is_in_doaj():
386 raise Exception(Messages.EXCEPTION_EDITING_WITHDRAWN_JOURNAL)
388 # if we are allowed to finalise, kick this up to the superclass
389 # here I can do something before the crosswalk is called - to do, move the resovled note conversion here
390 super(AdminApplication, self).finalise()
392 # resolve any flags that were resolved in the form
393 # self._resolve_flags(account)
395 # TODO: should these be a BLL feature?
396 # If we have changed the editors assigned to this application, let them know.
397 # ~~-> ApplicationForm:Crosswalk~~
398 is_editor_group_changed = ApplicationFormXWalk.is_new_editor_group(self.form, self.source)
399 is_associate_editor_changed = ApplicationFormXWalk.is_new_editor(self.form, self.source)
401 # record the event in the provenance tracker
402 # ~~-> Provenance:Model~~
403 models.Provenance.make(account, "edit", self.target)
405 # ~~->Application:Service~~
406 applicationService = DOAJ.applicationService()
408 # ~~->Event:Service~~
409 eventsSvc = DOAJ.eventsService()
411 # if the application is already rejected, and we are moving it back into a non-rejected status
412 if self.source.application_status == constants.APPLICATION_STATUS_REJECTED and self.target.application_status != constants.APPLICATION_STATUS_REJECTED:
413 try:
414 applicationService.unreject_application(self.target, current_user._get_current_object(), disallow_status=[])
415 except exceptions.DuplicateUpdateRequest as e:
416 self.add_alert(Messages.FORMS__APPLICATION_PROCESSORS__ADMIN_APPLICATION__FINALISE__COULD_NOT_UNREJECT)
417 return
419 # if this application is being accepted, then do the conversion to a journal
420 if self.target.application_status == constants.APPLICATION_STATUS_ACCEPTED:
421 j = applicationService.accept_application(self.target, account)
423 # Record the current time as last full review, if mark as full review has been selected
424 if (self.target.application_type == constants.APPLICATION_TYPE_UPDATE_REQUEST and
425 self.form.mark_as_full_review.data):
426 now = dates.now_str()
427 # Add last full review note to update request application
428 n = Messages.LAST_FULL_REVIEW_NOTE.format(date=now, username=account.id)
429 self.target.add_note(n, date=now, author_id=account.id)
430 self.target.save()
431 # Add last full review note to journal
432 j.last_full_review = now
433 n = Messages.LAST_FULL_REVIEW_NOTE.format(date=now, username=account.id)
434 j.add_note(n, date=now, author_id=account.id)
435 j.save()
437 # record the url the journal is available at in the admin are and alert the user
438 if has_request_context(): # fixme: if we handle alerts via a notification service we won't have to toggle on request context
439 jurl = url_for("doaj.toc", identifier=j.toc_id)
440 if self.source.current_journal is not None: # todo: are alerts displayed?
441 self.add_alert('<a href="{url}" target="_blank">Existing journal updated</a>.'.format(url=jurl))
442 else:
443 self.add_alert('<a href="{url}" target="_blank">New journal created</a>.'.format(url=jurl))
445 # Add the journal to the account and send the notification email
446 try:
447 # ~~-> Account:Model~~
448 owner = models.Account.pull(j.owner)
449 self.add_alert('Associating the journal with account {username}.'.format(username=owner.id))
450 owner.add_journal(j.id)
451 if not owner.has_role('publisher'):
452 owner.add_role('publisher')
453 owner.save()
455 # for all acceptances, send an email to the owner of the journal
456 if email_alert:
457 if app.config.get("ENABLE_PUBLISHER_EMAIL", False):
458 msg = Messages.SENT_ACCEPTED_APPLICATION_EMAIL.format(user=owner.id)
459 if self.target.application_type == constants.APPLICATION_TYPE_UPDATE_REQUEST:
460 msg = Messages.SENT_ACCEPTED_UPDATE_REQUEST_EMAIL.format(user=owner.id)
461 self.add_alert(msg)
462 else:
463 msg = Messages.NOT_SENT_ACCEPTED_APPLICATION_EMAIL.format(user=owner.id)
464 if self.target.application_type == constants.APPLICATION_TYPE_UPDATE_REQUEST:
465 msg = Messages.NOT_SENT_ACCEPTED_UPDATE_REQUEST_EMAIL.format(user=owner.id)
466 self.add_alert(msg)
467 # self._send_application_approved_email(self.target, j, owner, self.source.current_journal is not None)
468 except AttributeError:
469 raise Exception("Account {owner} does not exist".format(owner=j.owner))
470 except app_email.EmailException:
471 self.add_alert("Problem sending email to suggester - probably address is invalid")
472 app.logger.exception("Acceptance email to owner failed.")
474 # if the application was instead rejected, carry out the rejection actions
475 elif self.source.application_status != constants.APPLICATION_STATUS_REJECTED and self.target.application_status == constants.APPLICATION_STATUS_REJECTED:
476 # FIXME: I'm not really sure what `info` is for - it has been defined but unused in the
477 # base class for ages. This doesn't feel right, though, but since it's unused doesn't
478 # cause any actual problems right now
479 self.info = constants.APP_PROCESSOR_INFO_IS_BEING_REJECTED
480 # reject the application
481 applicationService.reject_application(self.target, current_user._get_current_object())
483 # the application was neither accepted or rejected, so just save it
484 else:
485 self.target.set_last_manual_update()
486 self.target.save()
488 if email_alert:
489 # trigger a status change event
490 if self.source.application_status != self.target.application_status:
491 eventsSvc.trigger(models.Event(constants.EVENT_APPLICATION_STATUS, account.id, {
492 "application": self.target.data,
493 "old_status": self.source.application_status,
494 "new_status": self.target.application_status
495 }))
497 # ~~-> Email:Notifications~~
499 # if we need to email the editor and/or the associate, handle those here
500 if is_editor_group_changed:
501 eventsSvc.trigger(models.Event(
502 constants.EVENT_APPLICATION_EDITOR_GROUP_ASSIGNED,
503 account.id, {
504 "application": self.target.data
505 }
506 ))
507 # try:
508 # emails.send_editor_group_email(self.target)
509 # except app_email.EmailException:
510 # self.add_alert("Problem sending email to editor - probably address is invalid")
511 # app.logger.exception("Email to associate failed.")
512 if is_associate_editor_changed:
513 eventsSvc.trigger(models.Event(constants.EVENT_APPLICATION_ASSED_ASSIGNED, account.id, {
514 "application" : self.target.data,
515 "old_editor": self.source.editor,
516 "new_editor": self.target.editor
517 }))
518 # try:
519 # emails.send_assoc_editor_email(self.target)
520 # except app_email.EmailException:
521 # self.add_alert("Problem sending email to associate editor - probably address is invalid")
522 # app.logger.exception("Email to associate failed.")
524 # Inform editor and associate editor if this application was 'ready' or 'completed', but has been changed to 'in progress'
525 if (self.source.application_status == constants.APPLICATION_STATUS_READY or self.source.application_status == constants.APPLICATION_STATUS_COMPLETED) and self.target.application_status == constants.APPLICATION_STATUS_IN_PROGRESS:
526 # First, the editor
527 self.add_alert('A notification has been sent to alert the editor of the change in status.')
529 # Then the associate
530 if self.target.editor:
531 self.add_alert('The associate editor has been notified of the change in status.')
534 # email other managing editors if this was newly set to 'ready'
535 if self.source.application_status != constants.APPLICATION_STATUS_READY and self.target.application_status == constants.APPLICATION_STATUS_READY:
536 self.add_alert('A notification has been sent to the Managing Editors.')
537 # this template requires who made the change, say it was an Admin
539 def validate(self):
540 _statuses_not_requiring_validation = ['rejected', 'pending', 'in progress', 'on hold']
541 self.pre_validate()
542 # make use of the ability to disable validation, otherwise, let it run
543 valid = super(AdminApplication, self).validate()
545 if self.form is not None:
546 if self.form.application_status.data in _statuses_not_requiring_validation and not valid:
547 self.resetDefaults(self.form)
548 return True
550 return valid
553class EditorApplication(ApplicationProcessor):
554 """
555 Editors Application Review form. This should be used in a context where an editor who owns an editorial group
556 is accessing an application. This prevents re-assignment of Editorial group, but permits assignment of associate
557 editor. It also permits change in application state, except to "accepted"; therefore this form context cannot
558 be used to create journals from applications. Deleting notes is not allowed, but adding is.
560 ~~EditorApplication:FormProcessor~~
561 """
563 def validate(self):
564 _statuses_not_requiring_validation = ['pending', 'in progress']
565 self.pre_validate()
566 # make use of the ability to disable validation, otherwise, let it run
567 valid = super(EditorApplication, self).validate()
569 if self.form is not None:
570 if self.form.application_status.data in _statuses_not_requiring_validation and not valid:
571 self.resetDefaults(self.form)
572 return True
574 return valid
576 def pre_validate(self):
577 # Call to super sets all the basic disabled fields
578 super(EditorApplication, self).pre_validate()
580 # although the editor_group field is handled by the general pre-validator, we still need to set the choices
581 # self.form.editor_group.data = self.source.editor_group
582 self.form.editor.choices = [(self.form.editor.data, self.form.editor.data)]
584 # This is no longer necessary, is handled by the main pre_validate function
585 #if self._formulaic.get('application_status').is_disabled:
586 # self.form.application_status.data = self.source.application_status
587 # but we do still need to add the overwritten status to the choices for validation
588 if self.form.application_status.data not in [c[0] for c in self.form.application_status.choices]:
589 self.form.application_status.choices.append((self.form.application_status.data, self.form.application_status.data))
591 def patch_target(self):
592 super(EditorApplication, self).patch_target()
594 self._carry_fixed_aspects()
595 self._merge_notes_forward()
596 self._carry_continuations()
598 self.target.set_owner(self.source.owner)
599 self.target.set_editor_group(self.source.editor_group)
600 self.target.bibjson().labels = self.source.bibjson().labels
602 def finalise(self):
603 if self.source is None:
604 raise Exception("You cannot edit a not-existent application")
605 if self.source.application_status == constants.APPLICATION_STATUS_ACCEPTED:
606 raise Exception("You cannot edit applications which have been accepted into DOAJ.")
608 # if we are allowed to finalise, kick this up to the superclass
609 super(EditorApplication, self).finalise()
611 # Check the status change is valid
612 self._validate_status_change(self.source.application_status, self.target.application_status)
614 # ~~-> ApplicationForm:Crosswalk~~
615 new_associate_assigned = ApplicationFormXWalk.is_new_editor(self.form, self.source)
617 # Save the target
618 self.target.set_last_manual_update()
619 self.target.save()
621 # record the event in the provenance tracker
622 # ~~-> Procenance:Model~~
623 models.Provenance.make(current_user, "edit", self.target) # FIXME: shouldn't really use current_user here
625 # trigger a status change event
626 eventsSvc = DOAJ.eventsService()
627 if self.source.application_status != self.target.application_status:
628 eventsSvc.trigger(models.Event(constants.EVENT_APPLICATION_STATUS, current_user.id, {
629 "application": self.target.data,
630 "old_status": self.source.application_status,
631 "new_status": self.target.application_status
632 }))
634 # if we need to email the associate because they have just been assigned, handle that here.
635 # ~~-> Email:Notifications~~
636 if new_associate_assigned:
637 eventsSvc.trigger(models.Event(constants.EVENT_APPLICATION_ASSED_ASSIGNED, context={
638 "application": self.target.data,
639 "old_editor": self.source.editor,
640 "new_editor": self.target.editor
641 }))
642 self.add_alert("New editor assigned - notification has been sent")
643 # try:
644 # self.add_alert("New editor assigned - email with confirmation has been sent")
645 # emails.send_assoc_editor_email(self.target)
646 # except app_email.EmailException:
647 # self.add_alert("Problem sending email to associate editor - probably address is invalid")
648 # app.logger.exception('Error sending associate assigned email')
650 # Email the assigned associate if the application was reverted from 'completed' to 'in progress' (failed review)
651 if self.source.application_status == constants.APPLICATION_STATUS_COMPLETED and self.target.application_status == constants.APPLICATION_STATUS_IN_PROGRESS:
652 if self.target.editor:
653 self.add_alert('The associate editor has been notified of the change in status.')
655 # email managing editors if the application was newly set to 'ready'
656 if self.source.application_status != constants.APPLICATION_STATUS_READY and self.target.application_status == constants.APPLICATION_STATUS_READY:
657 # Tell the ManEds who has made the status change - the editor in charge of the group
658 # ~~-> EditorGroup:Model~~
659 editor_group_name = self.target.editor_group
660 editor_group_id = models.EditorGroup.group_exists_by_name(name=editor_group_name)
661 editor_group = models.EditorGroup.pull(editor_group_id)
662 editor_acc = editor_group.get_editor_account()
664 # record the event in the provenance tracker
665 # ~~-> Provenance:Model~~
666 models.Provenance.make(current_user, "status:ready", self.target)
668 self.add_alert('A notification has been sent to the Managing Editors.')
671class AssociateApplication(ApplicationProcessor):
672 """
673 Associate Editors Application Review form. This is to be used in a context where an associate editor (fewest rights)
674 needs to access an application for review. This editor cannot change the editorial group or the assigned editor.
675 They also cannot change the owner of the application. They cannot set an application to "Accepted" so this form can't
676 be used to create a journal from an application. They cannot delete, only add notes.
678 ~~AssEdApplication:FormProcessor~~
679 """
681 def pre_validate(self):
682 # Call to super sets all the basic disabled fields
683 super(AssociateApplication, self).pre_validate()
685 # no longer necessary, handled by superclass pre_validate
686 #if self._formulaic.get('application_status').is_disabled:
687 # self.form.application_status.data = self.source.application_status
688 # but we do still need to add the overwritten status to the choices for validation
689 if self.form.application_status.data not in [c[0] for c in self.form.application_status.choices]:
690 self.form.application_status.choices.append(
691 (self.form.application_status.data, self.form.application_status.data))
693 def patch_target(self):
694 if self.source is None:
695 raise Exception("You cannot patch a target from a non-existent source")
697 super().patch_target()
698 self._carry_fixed_aspects()
699 self._merge_notes_forward()
700 self.target.set_owner(self.source.owner)
701 self.target.set_editor_group(self.source.editor_group)
702 self.target.set_editor(self.source.editor)
703 self.target.bibjson().labels = self.source.bibjson().labels
704 self._carry_continuations()
706 def finalise(self):
707 # if we are allowed to finalise, kick this up to the superclass
708 super(AssociateApplication, self).finalise()
710 # Check the status change is valid
711 self._validate_status_change(self.source.application_status, self.target.application_status)
713 # trigger a status change event
714 eventsSvc = DOAJ.eventsService()
715 if self.source.application_status != self.target.application_status:
716 eventsSvc.trigger(models.Event(constants.EVENT_APPLICATION_STATUS, current_user.id, {
717 "application": self.target.data,
718 "old_status": self.source.application_status,
719 "new_status": self.target.application_status
720 }))
722 # Save the target
723 self.target.set_last_manual_update()
724 self.target.save()
726 # record the event in the provenance tracker
727 # ~~-> Provenance:Model~~
728 models.Provenance.make(current_user, "edit", self.target)
730 # Editor is informed via status change event if this was newly set to 'completed'
731 # fixme: duplicated logic in notification event and here for provenance
732 if self.source.application_status != constants.APPLICATION_STATUS_COMPLETED and self.target.application_status == constants.APPLICATION_STATUS_COMPLETED:
733 # record the event in the provenance tracker
734 # ~~-> Procenance:Model~~
735 models.Provenance.make(current_user, "status:completed", self.target)
736 self.add_alert(Messages.FORMS__APPLICATION_PROCESSORS__ASSOCIATE_APPLICATION__FINALISE__STATUS_COMPLETED_NOTIFIED)
739class PublisherUpdateRequest(ApplicationProcessor):
740 """
741 ~~PublisherUpdateRequest:FormProcessor~~
742 """
744 def pre_validate(self):
745 if self.source is None:
746 raise Exception("You cannot validate a form from a non-existent source")
748 super(ApplicationProcessor, self).pre_validate()
750 def patch_target(self):
751 if self.source is None:
752 raise Exception("You cannot patch a target from a non-existent source")
754 super().patch_target()
755 self._carry_subjects()
756 self._carry_fixed_aspects()
757 self._merge_notes_forward()
758 self.target.set_owner(self.source.owner)
759 self.target.set_editor_group(self.source.editor_group)
760 self.target.set_editor(self.source.editor)
761 self._carry_continuations()
762 self.target.bibjson().labels = self.source.bibjson().labels
764 # we carry this over for completeness, although it will be overwritten in the finalise() method
765 self.target.set_application_status(self.source.application_status)
767 def finalise(self, save_target=True, email_alert=True):
768 # FIXME: this first one, we ought to deal with outside the form context, but for the time being this
769 # can be carried over from the old implementation
770 if self.source is None:
771 raise Exception("You cannot edit a not-existent application")
773 # if we are allowed to finalise, kick this up to the superclass
774 super(PublisherUpdateRequest, self).finalise()
776 # set the status to post submission review (will be updated again later after the review job runs)
777 if app.config.get("AUTOCHECK_INCOMING", False):
778 self.target.set_application_status(constants.APPLICATION_STATUS_POST_SUBMISSION_REVIEW)
779 else:
780 self.target.set_application_status(constants.APPLICATION_STATUS_UPDATE_REQUEST)
782 # automatically assign the Editorial group (turn this off in configuration if needed)
783 DOAJ.applicationService().auto_assign_ur_editor_group(self.target)
785 # Save the target
786 self.target.set_last_manual_update()
787 if save_target:
788 saved = self.target.save()
789 if saved is None:
790 raise Exception("Save on application failed")
792 # obtain the related journal, and attach the current application id to it
793 # ~~-> Journal:Service~~
794 journal_id = self.target.current_journal
795 journalService = DOAJ.journalService()
796 if journal_id is not None:
797 journal, _ = journalService.journal(journal_id)
798 if journal is not None:
799 journal.set_current_application(self.target.id)
800 if save_target:
801 saved = journal.save()
802 if saved is None:
803 raise Exception("Save on journal failed")
804 else:
805 self.target.remove_current_journal()
807 # Kick off the post-submission review
808 if app.config.get("AUTOCHECK_INCOMING", False):
809 # FIXME: imports are delayed because of a circular import problem buried in portality.decorators
810 from portality.tasks.application_autochecks import ApplicationAutochecks
811 from portality.tasks.helpers import background_helper
812 background_helper.submit_by_bg_task_type(ApplicationAutochecks,
813 application=self.target.id,
814 status_on_complete=constants.APPLICATION_STATUS_UPDATE_REQUEST)
816 # email the publisher to tell them we received their update request
817 if email_alert:
818 DOAJ.eventsService().trigger(models.Event(
819 constants.EVENT_APPLICATION_UR_SUBMITTED,
820 current_user and current_user.id,
821 context={
822 'application': self.target.data,
823 }
824 ))
826 def _carry_subjects(self):
827 # carry over the subjects
828 source_subjects = self.source.bibjson().subject
829 self.target.bibjson().subject = source_subjects
832class PublisherUpdateRequestReadOnly(ApplicationProcessor):
833 """
834 Read Only Application form for publishers. Nothing can be changed. Useful to show publishers what they
835 currently have submitted for review
837 ~~PublisherUpdateRequestReadOnly:FormProcessor~~
838 """
840 def finalise(self):
841 raise Exception("You cannot edit applications using the read-only form")
844###############################################
845### Journal form processors
846###############################################
848class ManEdJournalReview(ApplicationProcessor):
849 """
850 Managing Editor's Journal Review form. Should be used in a context where the form warrants full
851 admin privileges. It will permit doing every action.
853 ~~ManEdJournal:FormProcessor~~
854 """
855 def patch_target(self):
856 if self.source is None:
857 raise Exception("You cannot patch a target from a non-existent source")
859 super().patch_target()
860 self._carry_fixed_aspects()
861 self._merge_notes_forward(allow_delete=True)
863 # NOTE: this means you can't unset an owner once it has been set. But you can change it.
864 if (self.target.owner is None or self.target.owner == "") and (self.source.owner is not None):
865 self.target.set_owner(self.source.owner)
867 def finalise(self, account=None):
868 # FIXME: this first one, we ought to deal with outside the form context, but for the time being this
869 # can be carried over from the old implementation
871 if self.source is None:
872 raise Exception("You cannot edit a not-existent journal")
874 # if we are allowed to finalise, kick this up to the superclass
875 super(ManEdJournalReview, self).finalise()
877 # resolve any flags that were resolved in the form
878 self._resolve_flags(account)
880 # If we have changed the editors assinged to this application, let them know.
881 # ~~-> JournalForm:Crosswalk~~
882 is_editor_group_changed = JournalFormXWalk.is_new_editor_group(self.form, self.source)
883 is_associate_editor_changed = JournalFormXWalk.is_new_editor(self.form, self.source)
885 # has a full review been done
886 if self.source.last_full_review != self.target.last_full_review:
887 n = Messages.LAST_FULL_REVIEW_NOTE.format(date=self.target.last_full_review, username=account.id)
888 self.target.add_note(n, date=dates.now_str(), author_id=account.id)
890 # has the owner changed?
891 if self.source.owner != self.target.owner:
892 self.target.last_owner_transfer = dates.now_str()
893 changed_by = "unknown user"
894 if account is not None:
895 changed_by = account.id
896 n = Messages.OWNER_CHANGED_NOTE.format(date=dates.now_str(),
897 old_owner=self.source.owner,
898 new_owner=self.target.owner,
899 changed_by=changed_by)
900 self.target.add_note(n, date=dates.now_str(), author_id=changed_by)
902 is_new_flag_assignee = JournalFormXWalk.is_new_flag_assignee(self.form, self.source)
904 # Save the target
905 self.target.set_last_manual_update()
906 self.target.save()
908 # if we need to email the editor and/or the associate, handle those here
909 # ~~-> Email:Notifications~~
910 if is_editor_group_changed:
911 eventsSvc = DOAJ.eventsService()
912 eventsSvc.trigger(models.Event(constants.EVENT_JOURNAL_EDITOR_GROUP_ASSIGNED, current_user.id, {
913 "journal": self.target.data
914 }))
915 # try:
916 # emails.send_editor_group_email(self.target)
917 # except app_email.EmailException:
918 # self.add_alert("Problem sending email to editor - probably address is invalid")
919 # app.logger.exception('Error sending assignment email to editor.')
920 if is_associate_editor_changed:
921 events_svc = DOAJ.eventsService()
922 events_svc.trigger(models.Event(constants.EVENT_JOURNAL_ASSED_ASSIGNED, current_user.id, context={
923 "journal": self.target.data,
924 "old_editor": self.source.editor,
925 "new_editor": self.target.editor
926 }))
927 # try:
928 # emails.send_assoc_editor_email(self.target)
929 # except app_email.EmailException:
930 # self.add_alert("Problem sending email to associate editor - probably address is invalid")
931 # app.logger.exception('Error sending assignment email to associate.')
933 if is_new_flag_assignee:
934 eventsSvc = DOAJ.eventsService()
935 eventsSvc.trigger(models.Event(constants.EVENT_FLAG_ASSIGNED, current_user.id, {
936 "assignee": self.target.flags[0]["flag"]["assigned_to"],
937 "journal": self.target.data
938 }))
940 def validate(self):
941 # make use of the ability to disable validation, otherwise, let it run
942 if self.form is not None:
943 if self.form.make_all_fields_optional.data:
944 self.pre_validate()
945 return True
947 return super(ManEdJournalReview, self).validate()
950class EditorJournalReview(ApplicationProcessor):
951 """
952 Editors Journal Review form. This should be used in a context where an editor who owns an editorial group
953 is accessing a journal. This prevents re-assignment of Editorial group, but permits assignment of associate
954 editor.
956 ~~EditorJournal:FormProcessor~~
957 """
959 def patch_target(self):
960 if self.source is None:
961 raise Exception("You cannot patch a target from a non-existent source")
963 super().patch_target()
964 self._carry_fixed_aspects()
965 self.target.set_owner(self.source.owner)
966 self.target.set_editor_group(self.source.editor_group)
967 self._merge_notes_forward()
968 self._carry_continuations()
969 self.target.bibjson().labels = self.source.bibjson().labels
970 self.target.last_full_review = self.source.last_full_review
972 def pre_validate(self):
973 # call to super handles all the basic disabled field
974 super(EditorJournalReview, self).pre_validate()
976 # although the superclass sets the value of the disabled field, we still need to set the choices
977 # self.form.editor_group.data = self.source.editor_group
978 self.form.editor.choices = [(self.form.editor.data, self.form.editor.data)]
980 def finalise(self):
981 if self.source is None:
982 raise Exception("You cannot edit a not-existent journal")
984 # if we are allowed to finalise, kick this up to the superclass
985 super(EditorJournalReview, self).finalise()
987 # ~~-> ApplicationForm:Crosswalk~~
988 email_associate = ApplicationFormXWalk.is_new_editor(self.form, self.source)
990 # Save the target
991 self.target.set_last_manual_update()
992 self.target.save()
994 # if we need to email the associate, handle that here.
995 if email_associate:
996 events_svc = DOAJ.eventsService()
997 events_svc.trigger(models.Event(constants.EVENT_JOURNAL_ASSED_ASSIGNED, current_user.id, context={
998 "journal": self.target.data,
999 "old_editor": self.source.editor,
1000 "new_editor": self.target.editor
1001 }))
1002 # ~~-> Email:Notifications~~
1003 # try:
1004 # emails.send_assoc_editor_email(self.target)
1005 # except app_email.EmailException:
1006 # self.add_alert("Problem sending email to associate editor - probably address is invalid")
1007 # app.logger.exception('Error sending assignment email to associate.')
1010class AssEdJournalReview(ApplicationProcessor):
1011 """
1012 Associate Editors Journal Review form. This is to be used in a context where an associate editor (fewest rights)
1013 needs to access a journal for review. This editor cannot change the editorial group or the assigned editor.
1014 They also cannot change the owner of the journal. They cannot delete, only add notes.
1016 ~~AssEdJournal:FormProcessor~~
1017 """
1019 def patch_target(self):
1020 if self.source is None:
1021 raise Exception("You cannot patch a target from a non-existent source")
1023 super().patch_target()
1024 self._carry_fixed_aspects()
1025 self._merge_notes_forward()
1026 self.target.set_owner(self.source.owner)
1027 self.target.set_editor_group(self.source.editor_group)
1028 self.target.set_editor(self.source.editor)
1029 self._carry_continuations()
1030 self.target.bibjson().labels = self.source.bibjson().labels
1031 self.target.last_full_review = self.source.last_full_review
1033 def finalise(self):
1034 if self.source is None:
1035 raise Exception("You cannot edit a not-existent journal")
1037 # if we are allowed to finalise, kick this up to the superclass
1038 super(AssEdJournalReview, self).finalise()
1040 # Save the target
1041 self.target.set_last_manual_update()
1042 self.target.save()
1045class ReadOnlyJournal(ApplicationProcessor):
1046 """
1047 Read Only Journal form. Nothing can be changed. Useful for reviewing a journal and an application
1048 (or update request) side by side in 2 browser windows or tabs.
1050 ~~ReadOnlyJournal:FormProcessor~~
1051 """
1052 def form2target(self):
1053 pass # you can't edit objects using this form
1055 def patch_target(self):
1056 pass # you can't edit objects using this form
1058 def finalise(self):
1059 raise Exception("You cannot edit journals using the read-only form")
1062class ManEdBulkEdit(ApplicationProcessor):
1063 """
1064 Managing Editor's Journal Review form. Should be used in a context where the form warrants full
1065 admin privileges. It will permit doing every action.
1067 ~~ManEdBulkJournal:FormProcessor~~
1068 """
1069 pass