diff --git a/docs/admin/bibcirculation-admin-guide.rst b/docs/admin/bibcirculation-admin-guide.rst
deleted file mode 100644
index 818b9cea0..000000000
--- a/docs/admin/bibcirculation-admin-guide.rst
+++ /dev/null
@@ -1,58 +0,0 @@
-.. This file is part of Invenio
- Copyright (C) 2014 CERN.
-
- Invenio is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License as
- published by the Free Software Foundation; either version 2 of the
- License, or (at your option) any later version.
-
- Invenio is distributed in the hope that it will be useful, but
- WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with Invenio; if not, write to the Free Software Foundation, Inc.,
- 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-.. _bibcirculation-admin-guide:
-
-BibCirculation Admin Guide
-==========================
-
-1. Overview
------------
-
-BibCirculation enables you to manage the circulation of books (and other
-items) in a traditional library. BibCirculation has 2 sides: the user
-(borrower) interface and the admin (librarian) interface. In order to
-being able to use the librarian interface you need to have the
-correspondent rights as Invenio user.
-
-If you have rights to run BibCirculation, click on the "Administration"
-tab and select "Run Bibcirculation". You will see the so called "main
-menu", that will be present almost in every page in the librarian
-interface.
-
-2. Items
---------
-
-The first you need to circulate books are books. "Item" refers to
-anything that can have a barcode. In the case of books, an item is a
-copy of a book. The first thing you need is adding copies to the system.
-If you already have digitalized data about your copies, it is
-recommended to write a script to add the copies to the database.
-Otherwise, you need to add them one by one. To do this, search the book
-record in Invenio, go to the 'Detailed record' view, then the 'Holdings'
-tab. If you have BibCirculation rights, you will see a link. This link
-will let you add the first copy for that record (in case it has none) or
-it will take you to the record details in the librarian interface (in
-case it already has copies) where you can find a "Add new copy" button.
-
-You can get to the "Item details" page clicking in the book title link
-that can be found in many places around the module. You can also get to
-this page by searching a record using the "Items" in the main menu. In
-the "Item details" page the actions and the information diplayed will be
-different fot Periodicals and other records.
-
-FIXME
diff --git a/docs/admin/index.rst b/docs/admin/index.rst
index ef351c781..f70244274 100644
--- a/docs/admin/index.rst
+++ b/docs/admin/index.rst
@@ -1,48 +1,47 @@
.. This file is part of Invenio
Copyright (C) 2014, 2015 CERN.
Invenio is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
Invenio is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with Invenio; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
.. _admins-guide:
=============
Admin's Guide
=============
.. toctree::
:maxdepth: 1
bibauthority-admin-guide
bibcheck-admin-guide
- bibcirculation-admin-guide
bibclassify-admin-guide
bibconvert-admin-guide
bibedit-admin-guide
bibindex-admin-guide
bibknowledge-admin-guide
bibmatch-admin-guide
bibrank-admin-guide
bibsched-admin-guide
bibsort-admin-guide
bibupload-admin-guide
docextract-admin-guide
oaiharvest-admin-guide
oairepository-admin-guide
publiline-admin-guide
webcomment-admin-guide
webmessage-admin-guide
websearch-admin-guide
websession-admin-guide
webstyle-admin-guide
diff --git a/invenio/ext/legacy/layout.py b/invenio/ext/legacy/layout.py
index 74c9e3ecb..e7c0310a9 100644
--- a/invenio/ext/legacy/layout.py
+++ b/invenio/ext/legacy/layout.py
@@ -1,249 +1,242 @@
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Global organisation of the application's URLs.
This module binds together Invenio's legacy modules and maps them to their
corresponding URLs.
"""
from invenio.config import CFG_ACCESS_CONTROL_LEVEL_SITE, CFG_DEVEL_SITE
from invenio.ext.legacy.handler import WebInterfaceDirectory
from invenio.ext.legacy.handler import create_handler
from invenio.ext.logging import register_exception
from invenio.legacy.registry import webinterfaces
from invenio.utils import apache
class WebInterfaceDeprecatedPages(WebInterfaceDirectory):
"""Implement dumb interface for deprecated pages."""
_exports = ['']
def __call__(self, req, form):
"""Return deprecation warning."""
try:
from invenio.legacy.webpage import page
except ImportError:
register_exception()
def page(*args):
return args[1]
req.status = apache.HTTP_SERVICE_UNAVAILABLE
msg = "
This functionality will be soon deprecated.
"
try:
from invenio.config import CFG_SITE_ADMIN_EMAIL
msg += """
If you would still like to use it, please ask your
Invenio administrator %s to consider enabling it.
""" % CFG_SITE_ADMIN_EMAIL
except ImportError:
pass
try:
return page('Service disabled', msg, req=req)
except Exception:
return msg
def _lookup(self, component, path):
"""Return current interface for given path."""
return WebInterfaceDeprecatedPages(), path
index = __call__
class WebInterfaceDisabledPages(WebInterfaceDirectory):
"""This class implements a dumb interface to use as a fallback.
It is used in case the site is switched to read only mode,
i.e. CFG_ACCESS_CONTROL_LEVEL_SITE>0.
"""
_exports = ['']
def __call__(self, req, form):
try:
from invenio.legacy.webpage import page
except ImportError:
register_exception()
def page(*args):
return args[1]
req.status = apache.HTTP_SERVICE_UNAVAILABLE
msg = ("
This functionality is currently unavailable due to "
"a service maintenance.
")
try:
from invenio.config import CFG_SITE_ADMIN_EMAIL
msg += ("
"""
try:
return page('Service failure', msg, req=req)
except Exception:
return msg
def _lookup(self, component, path):
return WebInterfaceDumbPages(), path
index = __call__
try:
from invenio.legacy.bibdocfile.webinterface import \
bibdocfile_legacy_getfile
except ImportError:
register_exception(alert_admin=True, subject='EMERGENCY')
bibdocfile_legacy_getfile = WebInterfaceDumbPages
-try:
- from invenio.legacy.bibcirculation.admin_webinterface import \
- WebInterfaceBibCirculationAdminPages
-except ImportError:
- register_exception(alert_admin=True, subject='EMERGENCY')
- WebInterfaceBibCirculationAdminPages = WebInterfaceDumbPages
try:
from invenio.legacy.bibsched.webinterface import \
WebInterfaceBibSchedPages
except ImportError:
register_exception(alert_admin=True, subject='EMERGENCY')
WebInterfaceBibSchedPages = WebInterfaceDumbPages
class WebInterfaceAdminPages(WebInterfaceDirectory):
"""This class implements /admin2 admin pages."""
- _exports = ['index', 'bibcirculation', 'bibsched']
+ _exports = ['index', 'bibsched']
def index(self, req, form):
return "FIXME: return /help/admin content"
- bibcirculation = WebInterfaceBibCirculationAdminPages()
bibsched = WebInterfaceBibSchedPages()
class WebInterfaceInvenio(WebInterfaceDirectory):
""" The global URL layout is composed of the search API plus all
the other modules."""
_exports = [
'youraccount',
'yourbaskets',
'yourloans',
'yourcomments',
'ill',
'yourtickets',
'comments',
'error',
'oai2d', ('oai2d.py', 'oai2d'),
('getfile.py', 'getfile'),
'rss',
'stats',
'journal',
'help',
'exporter',
'kb',
'ping',
'admin2',
'textmining',
'goto',
'info',
]
def __init__(self):
self.getfile = bibdocfile_legacy_getfile
_mapping = dict(
youraccount='WebInterfaceYourAccountPages',
yourbaskets='WebInterfaceYourBasketsPages',
yourloans='WebInterfaceYourLoansPages',
ill='WebInterfaceILLPages',
yourtickets='WebInterfaceYourTicketsPages',
comments='WebInterfaceCommentsPages',
oai2d='WebInterfaceOAIProviderPages',
rss='WebInterfaceRSSFeedServicePages',
stats='WebInterfaceStatsPages',
journal='WebInterfaceJournalPages',
help='WebInterfaceDocumentationPages',
info='WebInterfaceInfoPages',
exporter='WebInterfaceFieldExporterPages',
kb='WebInterfaceBibKnowledgePages',
admin2='WebInterfaceAdminPages',
textmining='WebInterfaceDocExtract',
yourcomments='WebInterfaceYourCommentsPages',
goto='WebInterfaceGotoPages',
)
def __new__(cls):
from flask import current_app
if CFG_ACCESS_CONTROL_LEVEL_SITE > 0:
for key in cls._mapping.keys():
setattr(cls, key, WebInterfaceDisabledPages())
else:
webinterfaces_ = dict(webinterfaces)
webinterfaces_['WebInterfaceAdminPages'] = WebInterfaceAdminPages
for key, value in cls._mapping.items():
if value in webinterfaces_:
setattr(cls, key, webinterfaces_[value]())
else:
current_app.logger.error(
"Can not load {name}.".format(name=value))
setattr(cls, key, WebInterfaceDeprecatedPages())
return super(WebInterfaceInvenio, cls).__new__(cls)
# This creates the 'handler' function, which will be invoked directly
# by mod_python.
invenio_handler = create_handler(WebInterfaceInvenio())
diff --git a/invenio/legacy/bibcirculation/__init__.py b/invenio/legacy/bibcirculation/__init__.py
deleted file mode 100644
index 9b470b482..000000000
--- a/invenio/legacy/bibcirculation/__init__.py
+++ /dev/null
@@ -1,26 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# This file is part of Invenio.
-# Copyright (C) 2015 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-import warnings
-
-from invenio.utils.deprecation import RemovedInInvenio22Warning
-
-warnings.warn("BibCirculation will be removed in 2.2. Please check "
- "new Invenio-Circulation package.",
- RemovedInInvenio22Warning)
diff --git a/invenio/legacy/bibcirculation/admin_webinterface.py b/invenio/legacy/bibcirculation/admin_webinterface.py
deleted file mode 100644
index a2b62e99e..000000000
--- a/invenio/legacy/bibcirculation/admin_webinterface.py
+++ /dev/null
@@ -1,1983 +0,0 @@
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011, 2013 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-"""Invenio BibCirculation Administrator (URLs) Interface.
- The functions are positioned by grouping into logical
- categories('User Pages', 'Loans, Returns and Loan requests',
- 'ILLs', 'Libraries', 'Vendors' ...)
- These orders should be maintained and when necessary, improved
- for readability, as and when additional methods are added.
- When applicable, methods should be renamed, refactored and
- appropriate documentation added.
-"""
-
-__revision__ = ""
-
-from invenio.utils.url import redirect_to_url
-from invenio.config import CFG_SITE_URL, CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF
-from invenio.ext.legacy.handler import wash_urlargd, WebInterfaceDirectory
-
-import invenio.legacy.bibcirculation.adminlib as bal
-
-class WebInterfaceBibCirculationAdminPages(WebInterfaceDirectory):
- """Defines the set of /admin2/bibcirculation pages."""
-
- _exports = ['', 'index',
-
- # Loans, Loan Requests, Loan Returns related pages
- 'loan_on_desk_step1', 'loan_on_desk_step2', 'loan_on_desk_step3',
- 'loan_on_desk_step4', 'loan_on_desk_confirm', 'register_new_loan',
- 'create_loan', 'make_new_loan_from_request', 'loan_return',
- 'loan_return_confirm', 'claim_book_return',
- 'change_due_date_step1', 'change_due_date_step2',
- 'place_new_request_step1', 'place_new_request_step2',
- 'place_new_request_step3', 'place_new_loan_step1',
- 'place_new_loan_step2', 'place_new_loan_step3',
- 'create_new_request_step1', 'create_new_request_step2',
- 'create_new_request_step3', 'create_new_request_step4',
- 'create_new_loan_step1', 'create_new_loan_step2',
- 'all_requests', 'all_loans', 'all_expired_loans',
- 'get_pending_requests', 'get_waiting_requests',
- 'get_expired_loans_with_waiting_requests',
- 'get_loans_notes', 'get_item_loans_notes',
-
- # "Item" related pages
- 'get_item_details', 'get_item_requests_details', 'get_item_loans_details',
- 'get_item_req_historical_overview', 'get_item_loans_historical_overview',
- 'add_new_copy_step1', 'add_new_copy_step2', 'add_new_copy_step3',
- 'add_new_copy_step4', 'add_new_copy_step5',
- 'delete_copy_step1', 'delete_copy_step2',
- 'update_item_info_step1', 'update_item_info_step2', 'update_item_info_step3',
- 'update_item_info_step4', 'update_item_info_step5', 'update_item_info_step6',
- 'item_search', 'item_search_result',
-
- # "Borrower" related pages
- 'get_borrower_details', 'add_new_borrower_step1',
- 'add_new_borrower_step2', 'add_new_borrower_step3',
- 'update_borrower_info_step1', 'update_borrower_info_step2',
- 'get_borrower_requests_details', 'get_borrower_loans_details',
- 'bor_loans_historical_overview', 'bor_requests_historical_overview',
- 'get_borrower_ill_details', 'bor_ill_historical_overview',
- 'borrower_notification', 'get_borrower_notes',
- 'borrower_search', 'borrower_search_result',
-
- # ILL/Purchase/Acquisition related pages
- 'register_ill_from_proposal', 'register_ill_request_with_no_recid_step1',
- 'register_ill_request_with_no_recid_step2', 'register_ill_request_with_no_recid_step3',
- 'register_ill_request_with_no_recid_step4',
- 'register_ill_book_request', 'register_ill_book_request_result',
- 'register_ill_article_request_step1', 'register_ill_article_request_step2',
- 'register_ill_article_request_step3',
- 'register_purchase_request_step1', 'register_purchase_request_step2',
- 'register_purchase_request_step3',
- 'ill_request_details_step1', 'ill_request_details_step2',
- 'purchase_details_step1', 'purchase_details_step2', 'get_ill_library_notes',
- 'list_ill_request', 'list_purchase', 'list_proposal',
- 'ill_search', 'ill_search_result',
-
- # "Library" related pages
- 'get_library_details', 'merge_libraries_step1', 'merge_libraries_step2',
- 'merge_libraries_step3', 'add_new_library_step1', 'add_new_library_step2',
- 'add_new_library_step3', 'update_library_info_step1', 'update_library_info_step2',
- 'update_library_info_step3', 'update_library_info_step4', 'update_library_info_step5',
- 'get_library_notes', 'search_library_step1', 'search_library_step2',
-
- # "Vendor related pages
- 'get_vendor_details', 'add_new_vendor_step1', 'add_new_vendor_step2',
- 'add_new_vendor_step3', 'update_vendor_info_step1', 'update_vendor_info_step2',
- 'update_vendor_info_step3', 'update_vendor_info_step4', 'update_vendor_info_step5',
- 'get_vendor_notes', 'search_vendor_step1', 'search_vendor_step2'
- ]
-
-
-
- def index(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.index(req, ln)
-
-
-
-# Loans, Loan Requests, Loan Returns related pages
-
-
-
- def loan_on_desk_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/loan_on_desk_step1"""
- argd = wash_urlargd(form, {'key': (str, None), 'string': (str, None), 'ln': (str, "en")})
- key = argd['key']
- string = argd['string']
- ln = argd['ln']
-
- if string is not None:
- string = string.strip()
-
- return bal.loan_on_desk_step1(req, key, string, ln)
-
- def loan_on_desk_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/loan_on_desk_step2"""
- argd = wash_urlargd(form, {'user_id': (int, None), 'ln': (str, "en")})
- user_id = argd['user_id']
- ln = argd['ln']
-
- return bal.loan_on_desk_step2(req, user_id, ln)
-
- def loan_on_desk_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/loan_on_desk_step4"""
- argd = wash_urlargd(form, {'user_id': (int, None), 'barcode': (str, None),
- 'ln': (str, "en")})
- user_id = argd['user_id']
- list_of_barcodes = argd['barcode']
- ln = argd['ln']
-
- if list_of_barcodes is not None:
- list_of_barcodes = list_of_barcodes.split()
- else:
- list_of_barcodes = []
-
- return bal.loan_on_desk_step3(req, user_id, list_of_barcodes, ln)
-
- def loan_on_desk_step4(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/loan_on_desk_step5"""
- argd = wash_urlargd(form, {'list_of_barcodes': (str, None), 'user_id': (int, None),
- 'datepickerhidden': (str, None), 'note': (str, None), 'ln': (str, "en")})
- list_of_barcodes = argd['list_of_barcodes']
- user_id = argd['user_id']
- due_date = argd['datepickerhidden']
- note = argd['note']
- ln = argd['ln']
-
- list_of_barcodes = list_of_barcodes.strip('[]')
- list_of_barcodes = list_of_barcodes.split(',')
-
- for i in range(len(list_of_barcodes)):
- list_of_barcodes[i] = list_of_barcodes[i].strip('\' ')
-
- due_date = due_date.split(',')
-
-
- return bal.loan_on_desk_step4(req, list_of_barcodes, user_id, due_date, note, ln)
-
- def loan_on_desk_confirm(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/loan_on_desk_confirm"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'borrower_id': (str, None),
- 'ln': (str, "en")})
- barcode = argd['barcode']
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.loan_on_desk_confirm(req, barcode, borrower_id, ln)
-
- def register_new_loan(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/register_new_loan"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'borrower_id': (str, None),
- 'request_id': (str, None), 'new_note': (str, None),
- 'print_data': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- borrower_id = argd['borrower_id']
- request_id = argd['request_id']
- new_note = argd['new_note']
- print_data = argd['print_data']
- ln = argd['ln']
-
- if barcode is not None:
- barcode = barcode.strip()
-
- return bal.register_new_loan(req, barcode, borrower_id, request_id,
- new_note, print_data, ln)
-
- def create_loan(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/create_loan"""
- argd = wash_urlargd(form, {'request_id': (str, None), 'recid': (str, None),
- 'borrower_id': (str, None), 'ln': (str, "en")})
- request_id = argd['request_id']
- recid = argd['recid']
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.create_loan(req, request_id, recid, borrower_id, ln)
-
- def make_new_loan_from_request(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/make_new_loan_from_request"""
- argd = wash_urlargd(form, {'check_id': (str, None), 'barcode': (str, None),
- 'ln': (str, "en")})
- check_id = argd['check_id']
- barcode = argd['barcode']
- ln = argd['ln']
-
- return bal.make_new_loan_from_request(req, check_id, barcode, ln)
-
- def loan_return(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/loan_return"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.loan_return(req, ln)
-
- def loan_return_confirm(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/loan_return_confirm"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- ln = argd['ln']
- if barcode is not None:
- barcode = barcode.strip()
-
- return bal.loan_return_confirm(req, barcode, ln)
-
- def claim_book_return(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/claim_book_return"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'recid': (str, None),
- 'loan_id': (str, None), 'template': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- recid = argd['recid']
- loan_id = argd['loan_id']
- template = argd['template']
- ln = argd['ln']
- return bal.claim_book_return(req, borrower_id, recid, loan_id, template, ln)
-
-
- def change_due_date_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/change_due_date_step1"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'borrower_id': (str, None),
- 'ln': (str, "en")})
- barcode = argd['barcode']
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.change_due_date_step1(req, barcode, borrower_id, ln)
-
- def change_due_date_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/change_due_date_step2"""
- argd = wash_urlargd(form, {'new_due_date': (str, None), 'loan_id': (str, None),
- 'borrower_id': (str, None), 'ln': (str, "en")})
- new_due_date = argd['new_due_date']
- loan_id = argd['loan_id']
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.change_due_date_step2(req, new_due_date, loan_id, borrower_id, ln)
-
-
- def place_new_request_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/place_new_request_step1"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
- 'key': (str, None), 'string': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- recid = argd['recid']
- key = argd['key']
- string = argd['string']
- ln = argd['ln']
-
- if barcode is not None:
- barcode = barcode.strip()
- if recid is not None:
- recid = recid.strip()
- if string is not None:
- string = string.strip()
-
- return bal.place_new_request_step1(req, barcode, recid, key, string, ln)
-
- def place_new_request_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/place_new_request_step2"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
- 'user_info': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- recid = argd['recid']
- user_info = argd['user_info']
- ln = argd['ln']
-
- if user_info is not None:
- user_info = user_info.split(',')
-
- return bal.place_new_request_step2(req, barcode, recid, user_info, ln)
-
- def place_new_request_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/place_new_request_step3"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
- 'user_info': (str, None), 'period_from': (str, None),
- 'period_to': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- recid = argd['recid']
- user_info = argd['user_info']
- period_from = argd['period_from']
- period_to = argd['period_to']
- ln = argd['ln']
-
- if user_info is not None:
- user_info = user_info.split(',')
-
- return bal.place_new_request_step3(req, barcode, recid, user_info, period_from,
- period_to, ln)
-
-
- def place_new_loan_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/place_new_loan_step1"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
- 'key': (str, None), 'string': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- recid = argd['recid']
- key = argd['key']
- string = argd['string']
- ln = argd['ln']
-
- if barcode is not None:
- barcode = barcode.strip()
- if recid is not None:
- recid = recid.strip()
- if string is not None:
- string = string.strip()
-
- return bal.place_new_loan_step1(req, barcode, recid, key, string, ln)
-
- def place_new_loan_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/place_new_loan_step2"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
- 'user_info': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- recid = argd['recid']
- user_info = argd['user_info']
- ln = argd['ln']
- return bal.place_new_loan_step2(req, barcode, recid, user_info, ln)
-
- def place_new_loan_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/place_new_loan_step3"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'recid': (str, None),
- 'ccid': (str, None), 'name': (str, None), 'email': (str, None),
- 'phone': (str, None), 'address': (str, None), 'mailbox': (str, None),
- 'due_date': (str, None), 'notes': (str, None), 'ln': (str, "en")})
- barcode = argd['barcode']
- recid = argd['recid']
- ccid = argd['ccid']
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- mailbox = argd['mailbox']
- due_date = argd['due_date']
- notes = argd['notes']
- ln = argd['ln']
- return bal.place_new_loan_step3(req, barcode, recid, ccid, name, email,
- phone, address, mailbox, due_date, notes,
- ln)
-
-
- def create_new_request_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/create_new_request_step1"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'p': (str, None),
- 'f': (str, None), 'search': (str, None), 'ln': (str, "en")})
-
- borrower_id = argd['borrower_id']
- p = argd['p']
- f = argd['f']
- search = argd['search']
- ln = argd['ln']
-
- if borrower_id is not None:
- borrower_id = borrower_id.strip()
- if p is not None:
- p = p.strip()
-
- return bal.create_new_request_step1(req, borrower_id, p, f, search, ln)
-
- def create_new_request_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/create_new_request_step2"""
- argd = wash_urlargd(form, {'recid': (str, None), 'borrower_id': (str, None),
- 'ln': (str, "en")})
- recid = argd['recid']
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.create_new_request_step2(req, recid, borrower_id, ln)
-
- def create_new_request_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/create_new_request_step3"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'barcode': (str, None),
- 'recid': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- barcode = argd['barcode']
- recid = argd['recid']
- ln = argd['ln']
- return bal.create_new_request_step3(req, borrower_id, barcode, recid, ln)
-
- def create_new_request_step4(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/create_new_request_step4"""
- argd = wash_urlargd(form, {'period_from': (str, None), 'period_to': (str, None),
- 'barcode': (str, None), 'borrower_id': (str, None), 'recid': (str, None),
- 'ln': (str, "en")})
- period_from = argd['period_from']
- period_to = argd['period_to']
- barcode = argd['barcode']
- borrower_id = argd['borrower_id']
- recid = argd['recid']
- ln = argd['ln']
- return bal.create_new_request_step4(req, period_from, period_to, barcode,
- borrower_id, recid, ln)
-
-
- def create_new_loan_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/create_new_loan_step1"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.create_new_loan_step1(req, borrower_id, ln)
-
- def create_new_loan_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/create_new_loan_step2"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'barcode': (str, None),
- 'notes': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- barcode = argd['barcode']
- notes = argd['notes']
- ln = argd['ln']
- return bal.create_new_loan_step2(req, borrower_id, barcode, notes, ln)
-
-
- def all_requests(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/all_requests"""
- argd = wash_urlargd(form, {'request_id': (str, None), 'ln': (str, "en")})
- request_id = argd['request_id']
- ln = argd['ln']
- return bal.all_requests(req, request_id, ln)
-
- def all_loans(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/all_loans"""
- argd = wash_urlargd(form, {'msg': (str, None), 'ln': (str, "en")})
- msg = argd['msg']
- ln = argd['ln']
-
- return bal.all_loans(req, msg=msg, ln=ln)
-
- def all_expired_loans(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/all_expired_loans"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
-
- return bal.all_expired_loans(req, ln)
-
- def get_pending_requests(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_pending_requests"""
- argd = wash_urlargd(form, {'request_id': (str, None), 'print_data': (str, None),
- 'ln': (str, "en")})
- request_id = argd['request_id']
- print_data = argd['print_data']
- ln = argd['ln']
- return bal.get_pending_requests(req, request_id, print_data, ln)
-
- def get_waiting_requests(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_waiting_requests"""
- argd = wash_urlargd(form, {'request_id': (str, None), 'print_data': (str, None),
- 'ln': (str, "en")})
- request_id = argd['request_id']
- print_data = argd['print_data']
- ln = argd['ln']
- return bal.get_waiting_requests(req, request_id, print_data, ln)
-
- def get_expired_loans_with_waiting_requests(self, req, form):
- """ """
- argd = wash_urlargd(form, {'request_id': (str, None), 'ln': (str, "en")})
- request_id = argd['request_id']
- ln = argd['ln']
-
- return bal.get_expired_loans_with_waiting_requests(req, request_id, ln)
-
-
- def get_loans_notes(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_loans_notes"""
- argd = wash_urlargd(form, {'loan_id': (str, None), 'recid': (str, None),
- 'delete_key': (str, None), 'library_notes': (str, None),
- 'back': (str, ""), 'ln': (str, "en")})
- loan_id = argd['loan_id']
- delete_key = argd['delete_key']
- library_notes = argd['library_notes']
- back = argd['back']
- ln = argd['ln']
- return bal.get_loans_notes(req, loan_id, delete_key,
- library_notes, back, ln)
-
- def get_item_loans_notes(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_item_loans_notes"""
- argd = wash_urlargd(form, {'loan_id': (str, None), 'add_notes': (str, None),
- 'new_note': (str, None), 'ln': (str, "en")})
- loan_id = argd['loan_id']
- add_notes = argd['add_notes']
- new_note = argd['new_note']
- ln = argd['ln']
- return bal.get_item_loans_notes(req, loan_id, add_notes,
- new_note, ln)
-
-
-
-# "Item" related pages
-
-
-
-
- def get_item_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/"""
- argd = wash_urlargd(form, {'recid': (str, None), 'ln': (str, "en")})
- recid = argd['recid']
- ln = argd['ln']
-
- try:
- recid = int(recid)
- except:
- recid = None
-
- return bal.get_item_details(req, recid, ln)
-
- def get_item_requests_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/borrowers_search"""
- argd = wash_urlargd(form, {'recid': (str, None), 'request_id': (str, None),
- 'ln': (str, "en")})
- recid = argd['recid']
- request_id = argd['request_id']
- ln = argd['ln']
- return bal.get_item_requests_details(req, recid, request_id, ln)
-
- def get_item_loans_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/borrowers_search"""
- argd = wash_urlargd(form, {'recid': (str, None), 'barcode': (str, None),
- 'loan_id': (str, None), 'force': (str, None), 'ln': (str, "en")})
- recid = argd['recid']
- barcode = argd['barcode']
- loan_id = argd['loan_id']
- force = argd['force']
- ln = argd['ln']
- return bal.get_item_loans_details(req, recid, barcode, loan_id, force, ln)
-
- def get_item_req_historical_overview(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_item_req_historical_overview"""
- argd = wash_urlargd(form, {'recid': (str, None), 'ln': (str, "en")})
- recid = argd['recid']
- ln = argd['ln']
- return bal.get_item_req_historical_overview(req, recid, ln)
-
- def get_item_loans_historical_overview(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_item_loans_historical_overview"""
- argd = wash_urlargd(form, {'recid': (str, None), 'ln': (str, "en")})
- recid = argd['recid']
- ln = argd['ln']
- return bal.get_item_loans_historical_overview(req, recid, ln)
-
-
- def add_new_copy_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_copy_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.add_new_copy_step1(req, ln)
-
- def add_new_copy_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_copy_step2"""
- argd = wash_urlargd(form, {'p': (str, None), 'f': (str, None), 'ln': (str, "en")})
- p = argd['p']
- f = argd['f']
- ln = argd['ln']
-
- if p is not None:
- p = p.strip()
-
- return bal.add_new_copy_step2(req, p, f, ln)
-
- def add_new_copy_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_copy_step3"""
- argd = wash_urlargd(form, {'recid': (str, None), 'barcode': (str, None),
- 'ln': (str, "en")})
- recid = argd['recid']
- barcode = argd['barcode']
- ln = argd['ln']
- return bal.add_new_copy_step3(req, recid, barcode, ln)
-
- def add_new_copy_step4(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_copy_step4"""
- argd = wash_urlargd(form, {'barcode': (str, None), 'library': (str, ''),
- 'location': (str, ''), 'collection': (str, ''), 'description': (str, '-'),
- 'loan_period': (str, ''), 'status': (str, ''),
- 'expected_arrival_date': (str, ''), 'recid': (str, None), 'ln': (str, "en")})
-
- barcode = argd['barcode']
- library = argd['library']
- location = argd['location']
- collection = argd['collection']
- description = argd['description']
- loan_period = argd['loan_period']
- status = argd['status']
- expected_arrival_date = argd['expected_arrival_date']
- recid = argd['recid']
- ln = argd['ln']
-
- if barcode is not None:
- barcode = barcode.strip()
-
- library = library.strip()
- location = location.strip()
- collection = collection.strip()
- description = description.strip()
-
- loan_period = loan_period.strip()
- status = status.strip()
- expected_arrival_date = expected_arrival_date.strip()
-
- if recid is not None:
- recid = recid.strip()
-
- return bal.add_new_copy_step4(req, barcode, library, location, collection,
- description, loan_period, status,
- expected_arrival_date, recid, ln)
-
- def add_new_copy_step5(self, req, form):
-
- argd = wash_urlargd(form, {'barcode': (str, None), 'library': (str, None),
- 'location': (str, None), 'collection': (str, None), 'description': (str, '-'),
- 'loan_period': (str, None), 'status': (str, None),
- 'expected_arrival_date': (str, None), 'recid': (str, None), 'ln': (str, "en")})
-
- barcode = argd['barcode']
- library = argd['library']
- location = argd['location']
- collection = argd['collection']
- description = argd['description']
- loan_period = argd['loan_period']
- status = argd['status']
- expected_arrival_date = argd['expected_arrival_date']
- recid = argd['recid']
- ln = argd['ln']
- return bal.add_new_copy_step5(req, barcode, library, location, collection,
- description, loan_period, status, expected_arrival_date, recid, ln)
-
-
- def delete_copy_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/delete_copy_step1"""
- argd = wash_urlargd(form, {'barcode': (str, ''), 'ln': (str, "en")})
-
- barcode = argd['barcode']
- ln = argd['ln']
-
- return bal.delete_copy_step1(req, barcode, ln)
-
- def delete_copy_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/delete_copy_step2"""
- argd = wash_urlargd(form, {'barcode': (str, ''), 'ln': (str, "en")})
-
- barcode = argd['barcode']
- ln = argd['ln']
-
- return bal.delete_copy_step2(req, barcode, ln)
-
-
- def update_item_info_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_item_info_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.update_item_info_step1(req, ln)
-
- def update_item_info_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_item_info_step2"""
- argd = wash_urlargd(form, {'p': (str, '()'), 'f': (str, '()'), 'ln': (str, "en")})
- p = argd['p']
- f = argd['f']
- ln = argd['ln']
-
- p = p.strip()
-
- return bal.update_item_info_step2(req, p, f, ln)
-
- def update_item_info_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_item_info_step3"""
- argd = wash_urlargd(form, {'recid': (int, 0), 'ln': (str, "en")})
- recid = argd['recid']
- ln = argd['ln']
- return bal.update_item_info_step3(req, recid, ln)
-
- def update_item_info_step4(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_item_info_step4"""
- argd = wash_urlargd(form, {'barcode': (str, '()'), 'ln': (str, "en")})
- barcode = argd['barcode']
- ln = argd['ln']
- return bal.update_item_info_step4(req, barcode, ln)
-
- def update_item_info_step5(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_item_info_step5"""
- argd = wash_urlargd(form, {'barcode': (str, ''), 'old_barcode': (str, ''),
- 'library_id': (int, 0), 'location': (str, 'Unknown'), 'collection': (str, 'Unknown'),
- 'description': (str, '-'), 'loan_period': (str, '4 weeks'),
- 'status': (str, CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF), 'expected_arrival_date': (str, ''),
- 'recid': (int, 0), 'ln': (str, "en")})
-
- barcode = argd['barcode']
- old_barcode = argd['old_barcode']
- library = argd['library_id']
- location = argd['location']
- collection = argd['collection']
- description = argd['description']
- loan_period = argd['loan_period']
- status = argd['status']
- expected_arrival_date = argd['expected_arrival_date']
- recid = argd['recid']
- ln = argd['ln']
-
- barcode = barcode.strip()
- old_barcode = old_barcode.strip()
- location = location.strip()
- collection = collection.strip()
- description = description.strip()
- loan_period = loan_period.strip()
- status = status.strip()
- expected_arrival_date = expected_arrival_date.strip()
-
- return bal.update_item_info_step5(req, barcode, old_barcode, library, location,
- collection, description, loan_period,
- status, expected_arrival_date, recid, ln)
-
- def update_item_info_step6(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_item_info_step6"""
- argd = wash_urlargd(form, {'barcode': (str, '-'), 'old_barcode': (str, '-'),
- 'library_id': (int, 0), 'location': (str, 'Unknown'), 'collection': (str, 'Unknown'),
- 'description': (str, '-'), 'loan_period': (str, '4 weeks'),
- 'status': (str, CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF), 'expected_arrival_date': (str, ''),
- 'recid': (int, 0), 'ln': (str, "en")})
-
- barcode = argd['barcode']
- old_barcode = argd['old_barcode']
- library_id = argd['library_id']
- location = argd['location']
- collection = argd['collection']
- description = argd['description']
- loan_period = argd['loan_period']
- status = argd['status']
- expected_arrival_date = argd['expected_arrival_date']
- recid = argd['recid']
-
- ln = argd['ln']
-
- tup_infos = (barcode, old_barcode, library_id, location, collection,
- description, loan_period, status, expected_arrival_date, recid)
-
- return bal.update_item_info_step6(req, tup_infos, ln)
-
-
- def item_search(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/holdings_search"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.item_search(req, [], ln)
-
- def item_search_result(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/item_search_result"""
- argd = wash_urlargd(form, {'p': (str, ''), 'f': (str, ''),
- 'ln': (str, "en")})
- p = argd['p']
- f = argd['f']
- ln = argd['ln']
-
- if p is not None:
- p = p.strip()
-
- return bal.item_search_result(req, p, f, ln)
-
-
-
-
-# "Borrower" related pages
-
-
-
-
- def get_borrower_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/borrowers_search"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'update': (str, 'False'),
- 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- update = argd['update']
- ln = argd['ln']
-
- if update == 'True':
- update = True
- else:
- update = False
-
- return bal.get_borrower_details(req, borrower_id, update, ln)
-
- def add_new_borrower_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_borrower_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.add_new_borrower_step1(req, ln)
-
- def add_new_borrower_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_borrower_step2"""
- argd = wash_urlargd(form, {'name': (str, ''), 'email': (str, ''),
- 'phone': (str, ''), 'address': (str, ''), 'mailbox': (str, ''),
- 'notes': (str, ''), 'ln': (str, "en")})
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- mailbox = argd['mailbox']
- notes = argd['notes']
- ln = argd['ln']
-
- name = name.strip()
- email = email.strip()
- phone = phone.strip()
- address = address.strip()
- mailbox = mailbox.strip()
- notes = notes.strip()
-
- return bal.add_new_borrower_step2(req, name, email, phone, address,
- mailbox, notes, ln)
-
- def update_borrower_info_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_borrower_info_step1"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.update_borrower_info_step1(req, borrower_id, ln)
-
- def update_borrower_info_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_borrower_info_step2"""
- argd = wash_urlargd(form, {'borrower_id': (int, None), 'name': (str, ''),
- 'email': (str, ''), 'phone': (str, ''), 'address': (str, ''),
- 'mailbox': (str, ''), 'ln': (str, "en")})
-
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- mailbox = argd['mailbox']
- borrower_id = argd['borrower_id']
- ln = argd['ln']
-
- name = name.strip()
- email = email.strip()
- phone = phone.strip()
- address = address.strip()
- mailbox = mailbox.strip()
-
- return bal.update_borrower_info_step2(req, borrower_id, name, email, phone, address,
- mailbox, ln)
-
-
- def get_borrower_requests_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_borrower_requests_details"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'request_id': (str, None),
- 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- request_id = argd['request_id']
- ln = argd['ln']
- return bal.get_borrower_requests_details(req, borrower_id, request_id, ln)
-
- def get_borrower_loans_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_borrower_loans_details"""
- argd = wash_urlargd(form, {'recid': (str, None), 'barcode': (str, None),
- 'borrower_id': (str, None), 'renewal': (str, None),
- 'force': (str, None), 'loan_id': (str, None),
- 'ln': (str, "en")})
- recid = argd['recid']
- barcode = argd['barcode']
- borrower_id = argd['borrower_id']
- renewal = argd['renewal']
- force = argd['force']
- loan_id = argd['loan_id']
- ln = argd['ln']
- return bal.get_borrower_loans_details(req, recid, barcode, borrower_id,
- renewal, force, loan_id, ln)
-
- def bor_loans_historical_overview(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/bor_loans_historical_overview"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.bor_loans_historical_overview(req, borrower_id, ln)
-
- def bor_requests_historical_overview(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/bor_requests_historical_overview"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- ln = argd['ln']
- return bal.bor_requests_historical_overview(req, borrower_id, ln)
-
- def get_borrower_ill_details(self, req, form):
- """ """
- argd = wash_urlargd(form, {'borrower_id': (str, None),
- 'request_type': (str, ''), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- request_type = argd['request_type']
- ln = argd['ln']
-
- return bal.get_borrower_ill_details(req, borrower_id, request_type, ln)
-
- def bor_ill_historical_overview(self, req, form):
- """ """
- argd = wash_urlargd(form, {'borrower_id': (str, None),
- 'request_type': (str, ''), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- request_type = argd['request_type']
- ln = argd['ln']
-
- return bal.bor_ill_historical_overview(req, borrower_id, request_type, ln)
-
-
- def borrower_notification(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/borrower_notification"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'template': (str, None),
- 'message': (str, None), 'load_msg_template': (str, 'True'), 'subject': (str, None),
- 'send_message': (str, None), 'from_address': (str, None), 'ln': (str, "en")})
-
- borrower_id = argd['borrower_id']
- template = argd['template']
- message = argd['message']
- load_msg_template = argd['load_msg_template']
- subject = argd['subject']
- send_message = argd['send_message']
- from_address = argd['from_address']
- ln = argd['ln']
-
- return bal.borrower_notification(req, borrower_id, template, message,
- load_msg_template, subject, send_message,
- from_address, ln)
-
- def get_borrower_notes(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_borrower_notes"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'delete_key': (str, None),
- 'library_notes': (str, None), 'ln': (str, "en")})
- borrower_id = argd['borrower_id']
- delete_key = argd['delete_key']
- library_notes = argd['library_notes']
- ln = argd['ln']
- return bal.get_borrower_notes(req, borrower_id, delete_key,
- library_notes, ln)
-
- def borrower_search(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/borrowers_search"""
- argd = wash_urlargd(form, {'empty_barcode': (str, None),
- 'redirect_to_new_request': (str, "no"),
- 'ln': (str, "en")})
- empty_barcode = argd['empty_barcode']
- redirect_to_new_request = argd['redirect_to_new_request']
- ln = argd['ln']
-
- if redirect_to_new_request == 'yes':
- redirect_to_new_request = True
- else:
- redirect_to_new_request = False
-
- return bal.borrower_search(req, empty_barcode,
- redirect_to_new_request=redirect_to_new_request, ln=ln)
-
- def borrower_search_result(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/borrower_search_result"""
- argd = wash_urlargd(form, {'column': (str, "name"), 'string': (str, ''),
- 'redirect_to_new_request': (str, "no"), 'ln': (str, "en")})
- column = argd['column']
- string = argd['string']
- redirect_to_new_request = argd['redirect_to_new_request']
- ln = argd['ln']
-
- string = string.strip()
- if redirect_to_new_request == 'yes':
- redirect_to_new_request = True
- else:
- redirect_to_new_request = False
-
- return bal.borrower_search_result(req, column, string,
- redirect_to_new_request=redirect_to_new_request,
- ln=ln)
-
-
-
-
-# ILL/Purchase/Acquisition related pages
-
-
- def register_ill_from_proposal(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/register_ill_from_proposal"""
- argd = wash_urlargd(form, {'ill_request_id': (str, None), 'bor_id': (str, None), 'ln': (str, "en")})
- ill_request_id = argd['ill_request_id']
- ln = argd['ln']
- bor_id = argd['bor_id']
-
- return bal.register_ill_from_proposal(req, ill_request_id, bor_id, ln)
-
- def register_ill_request_with_no_recid_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/register_ill_request_with_no_recid_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en"), 'borrower_id': (str, None)})
- ln = argd['ln']
- borrower_id = argd['borrower_id']
- if borrower_id == 'None':
- borrower_id = None
-
- return bal.register_ill_request_with_no_recid_step1(req, borrower_id, ln)
-
- def register_ill_request_with_no_recid_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/register_ill_request_with_no_recid_step2"""
-
- argd = wash_urlargd(form, {'title': (str, ''), 'authors': (str, ''),
- 'place': (str, ''), 'publisher': (str, ''), 'year': (str, ''),
- 'edition': (str, ''), 'isbn': (str, ''), 'budget_code': (str, ''),
- 'period_of_interest_from': (str, ''), 'period_of_interest_to': (str, ''),
- 'additional_comments': (str, ''), 'only_edition': (str, 'No'), 'key': (str, None),
- 'string': (str, ''), 'borrower_id': (str, None), 'ln': (str, "en")})
-
- title = argd['title']
- authors = argd['authors']
- place = argd['place']
- publisher = argd['publisher']
- year = argd['year']
- edition = argd['edition']
- isbn = argd['isbn']
- budget_code = argd['budget_code']
- period_of_interest_from = argd['period_of_interest_from']
- period_of_interest_to = argd['period_of_interest_to']
- additional_comments = argd['additional_comments']
- only_edition = argd['only_edition']
- key = argd['key']
- string = argd['string']
- borrower_id = argd['borrower_id']
- ln = argd['ln']
-
- if borrower_id is not None:
- borrower_id = borrower_id.strip()
- if borrower_id == 'None':
- borrower_id = None
-
- title = title.strip()
- authors = authors.strip()
- place = place.strip()
- publisher = publisher.strip()
- year = year.strip()
- edition = edition.strip()
- isbn = isbn.strip()
- budget_code = budget_code.strip()
- period_of_interest_from = period_of_interest_from.strip()
- period_of_interest_to = period_of_interest_to.strip()
- string = string.strip()
-
- return bal.register_ill_request_with_no_recid_step2(req, title, authors, place,
- publisher, year, edition, isbn, budget_code, period_of_interest_from,
- period_of_interest_to, additional_comments,
- only_edition, key, string, borrower_id, ln)
-
- def register_ill_request_with_no_recid_step3(self, req, form):
- """ """
- argd = wash_urlargd(form, {'title': (str, None), 'authors': (str, None),
- 'place': (str, None), 'publisher': (str, None), 'year': (str, None),
- 'edition': (str, None), 'isbn': (str, None), 'user_info': (str, None),
- 'budget_code': (str, ''), 'period_of_interest_from': (str, None),
- 'period_of_interest_to': (str, None), 'additional_comments': (str, None),
- 'only_edition': (str, 'No'), 'ln': (str, "en")})
-
- title = argd['title']
- authors = argd['authors']
- place = argd['place']
- publisher = argd['publisher']
- year = argd['year']
- edition = argd['edition']
- isbn = argd['isbn']
-
- user_info = argd['user_info']
-
- budget_code = argd['budget_code']
- period_of_interest_from = argd['period_of_interest_from']
- period_of_interest_to = argd['period_of_interest_to']
- additional_comments = argd['additional_comments']
- only_edition = argd['only_edition']
-
- ln = argd['ln']
-
- if user_info is not None:
- user_info = user_info.split(',')
-
- return bal.register_ill_request_with_no_recid_step3(req, title, authors, place,
- publisher, year, edition, isbn,
- user_info, budget_code,
- period_of_interest_from,
- period_of_interest_to,
- additional_comments,
- only_edition, ln)
-
- def register_ill_request_with_no_recid_step4(self, req, form):
- """ """
-
- argd = wash_urlargd(form, {'title': (str, None), 'authors': (str, None),
- 'place': (str, None), 'publisher': (str, None), 'year': (str, None),
- 'edition': (str, None), 'isbn': (str, None), 'borrower_id': (str, None),
- 'budget_code': (str, ''), 'period_of_interest_from': (str, None),
- 'period_of_interest_to': (str, None), 'additional_comments': (str, None),
- 'only_edition': (str, None), 'ln': (str, "en")})
-
- title = argd['title']
- authors = argd['authors']
- place = argd['place']
- publisher = argd['publisher']
- year = argd['year']
- edition = argd['edition']
- isbn = argd['isbn']
-
- borrower_id = argd['borrower_id']
-
- budget_code = argd['budget_code']
- period_of_interest_from = argd['period_of_interest_from']
- period_of_interest_to = argd['period_of_interest_to']
- additional_comments = argd['additional_comments']
- only_edition = argd['only_edition']
-
- ln = argd['ln']
-
- book_info = (title, authors, place, publisher, year, edition, isbn)
-
- request_details = (budget_code, period_of_interest_from, period_of_interest_to,
- additional_comments, only_edition)
-
- return bal.register_ill_request_with_no_recid_step4(req, book_info, borrower_id,
- request_details, ln)
-
-
- def register_ill_book_request(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/holdings_search"""
- argd = wash_urlargd(form, {'borrower_id': (str, None), 'ln': (str, "en")})
- ln = argd['ln']
- borrower_id = argd['borrower_id']
- return bal.register_ill_book_request(req, borrower_id, ln)
-
- def register_ill_book_request_result(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/item_search_result"""
- argd = wash_urlargd(form, {'borrower_id': (str, None),'p': (str, None),
- 'f': (str, None), 'ln': (str, "en")})
- p = argd['p']
- f = argd['f']
- ln = argd['ln']
- borrower_id = argd['borrower_id']
- return bal.register_ill_book_request_result(req, borrower_id, p, f, ln)
-
-
- def register_ill_article_request_step1(self, req, form):
- """ """
- argd = wash_urlargd(form, {'ln': (str, "en")})
-
- ln = argd['ln']
-
- return bal.register_ill_article_request_step1(req, ln)
-
- def register_ill_article_request_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/register_ill_request_with_no_recid_step2"""
-
- argd = wash_urlargd(form, {'periodical_title': (str, None),
- 'article_title': (str, None), 'author': (str, None),
- 'report_number': (str, None), 'volume': (str, None),
- 'issue': (str, None), 'page': (str, None), 'year': (str, None),
- 'budget_code': (str, ''), 'issn': (str, None),
- 'period_of_interest_from': (str, None),
- 'period_of_interest_to': (str, None),
- 'additional_comments': (str, None), 'key': (str, None),
- 'string': (str, None), 'ln': (str, "en")})
-
- periodical_title = argd['periodical_title']
- article_title = argd['article_title']
- author = argd['author']
- report_number = argd['report_number']
- volume = argd['volume']
- issue = argd['issue']
- page = argd['page']
- year = argd['year']
- budget_code = argd['budget_code']
- issn = argd['issn']
- period_of_interest_from = argd['period_of_interest_from']
- period_of_interest_to = argd['period_of_interest_to']
- additional_comments = argd['additional_comments']
- key = argd['key']
- string = argd['string']
- ln = argd['ln']
-
- return bal.register_ill_article_request_step2(req, periodical_title, article_title,
- author, report_number,
- volume, issue, page, year, budget_code,
- issn, period_of_interest_from,
- period_of_interest_to,
- additional_comments, key, string, ln)
-
- def register_ill_article_request_step3(self, req, form):
-
- argd = wash_urlargd(form, {'periodical_title': (str, ''), 'article_title': (str, ''),
- 'author': (str, ''), 'report_number': (str, ''), 'volume': (str, ''),
- 'issue': (str, ''), 'page': (str, ''), 'year': (str, ''), 'issn': (str, ''),
- 'user_info': (str, None), 'request_details': (str, '()'),
- 'ln': (str, "en"), 'period_of_interest_from': (str, ''),
- 'period_of_interest_to': (str, ''), 'budget_code': (str, ''),
- 'additional_comments': (str, '')})
-
- periodical_title = argd['periodical_title']
- article_title = argd['article_title']
- author = argd['author']
- report_number = argd['report_number']
- volume = argd['volume']
- issue = argd['issue']
- page = argd['page']
- year = argd['year']
- issn = argd['issn']
- user_info = argd['user_info']
- request_details = argd['request_details']
- ln = argd['ln']
- period_of_interest_from = argd['period_of_interest_from']
- period_of_interest_to = argd['period_of_interest_to']
- budget_code = argd['budget_code']
- additional_comments = argd['additional_comments']
-
- request_details = (period_of_interest_from, period_of_interest_to,
- budget_code, additional_comments)
-
- if user_info is not None:
- user_info = user_info.split(',')
-
- return bal.register_ill_article_request_step3(req, periodical_title, article_title,
- author, report_number, volume, issue, page, year, issn,
- user_info, request_details, ln)
-
-
- def register_purchase_request_step1(self, req, form):
- """ """
- argd = wash_urlargd(form, {'type': (str, 'acq-book'),
- 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
- 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
- 'this_edition_only': (str, 'No'),
- 'isbn': (str, ''), 'standard_number': (str, ''),
- 'budget_code': (str, ''), 'cash': (str, 'No'),
- 'period_of_interest_from': (str, ''),
- 'period_of_interest_to': (str, ''),
- 'additional_comments': (str, ''), 'ln': (str, "en")})
-
- request_type = argd['type'].strip()
- title = argd['title'].strip()
- authors = argd['authors'].strip()
- place = argd['place'].strip()
- publisher = argd['publisher'].strip()
- year = argd['year'].strip()
- edition = argd['edition'].strip()
- this_edition_only = argd['this_edition_only'].strip()
- isbn = argd['isbn'].strip()
- standard_number = argd['standard_number'].strip()
- budget_code = argd['budget_code'].strip()
- cash = argd['cash'] == 'Yes'
- period_of_interest_from = argd['period_of_interest_from'].strip()
- period_of_interest_to = argd['period_of_interest_to'].strip()
- additional_comments = argd['additional_comments'].strip()
- ln = argd['ln']
-
- return bal.register_purchase_request_step1(req, request_type, title,
- authors, place, publisher, year, edition,
- this_edition_only, isbn, standard_number,
- budget_code, cash, period_of_interest_from,
- period_of_interest_to, additional_comments, ln)
-
- def register_purchase_request_step2(self, req, form):
- """ """
- argd = wash_urlargd(form, {'type': (str, 'acq-book'), 'recid': (str, ''),
- 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
- 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
- 'this_edition_only': (str, 'No'),
- 'isbn': (str, ''), 'standard_number': (str, ''),
- 'budget_code': (str, ''), 'cash': (str, 'No'),
- 'period_of_interest_from': (str, ''),
- 'period_of_interest_to': (str, ''),
- 'additional_comments': (str, ''), 'p': (str, ''),
- 'f': (str, ''), 'ln': (str, "en")})
-
- request_type = argd['type'].strip()
- recid = argd['recid'].strip()
- title = argd['title'].strip()
- authors = argd['authors'].strip()
- place = argd['place'].strip()
- publisher = argd['publisher'].strip()
- year = argd['year'].strip()
- edition = argd['edition'].strip()
- this_edition_only = argd['this_edition_only'].strip()
- isbn = argd['isbn'].strip()
- standard_number = argd['standard_number'].strip()
- budget_code = argd['budget_code'].strip()
- cash = (argd['cash'] == 'Yes')
- period_of_interest_from = argd['period_of_interest_from'].strip()
- period_of_interest_to = argd['period_of_interest_to'].strip()
- additional_comments = argd['additional_comments'].strip()
- p = argd['p'].strip()
- f = argd['f'].strip()
- ln = argd['ln']
-
- return bal.register_purchase_request_step2(req, request_type, recid, title, authors,
- place, publisher, year, edition, this_edition_only,
- isbn, standard_number, budget_code, cash,
- period_of_interest_from, period_of_interest_to,
- additional_comments, p, f, ln)
-
- def register_purchase_request_step3(self, req, form):
- """ """
- argd = wash_urlargd(form, {'type': (str, 'acq-book'), 'recid': (str, ''),
- 'title': (str, ''), 'authors': (str, ''), 'place': (str, ''),
- 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
- 'this_edition_only': (str, 'No'),
- 'isbn': (str, ''), 'standard_number': (str, ''),
- 'budget_code': (str, ''), 'cash': (str, 'No'),
- 'period_of_interest_from': (str, ''),
- 'period_of_interest_to': (str, ''),
- 'additional_comments': (str, ''),
- 'borrower_id': (str, ''), 'ln': (str, "en")})
-
- request_type = argd['type'].strip()
- recid = argd['recid'].strip()
- title = argd['title'].strip()
- authors = argd['authors'].strip()
- place = argd['place'].strip()
- publisher = argd['publisher'].strip()
- year = argd['year'].strip()
- edition = argd['edition'].strip()
- this_edition_only = argd['this_edition_only'].strip()
- isbn = argd['isbn'].strip()
- standard_number = argd['standard_number'].strip()
- budget_code = argd['budget_code'].strip()
- cash = (argd['cash'] == 'Yes')
- period_of_interest_from = argd['period_of_interest_from'].strip()
- period_of_interest_to = argd['period_of_interest_to'].strip()
- additional_comments = argd['additional_comments'].strip()
- borrower_id = argd['borrower_id'].strip()
- ln = argd['ln']
-
- return bal.register_purchase_request_step3(req, request_type, recid, title, authors,
- place, publisher, year, edition, this_edition_only,
- isbn, standard_number,
- budget_code, cash, period_of_interest_from,
- period_of_interest_to, additional_comments,
- borrower_id, ln)
-
-
- def ill_request_details_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/ill_request_details_step1"""
-
- argd = wash_urlargd(form, {'delete_key': (str, None), 'ill_request_id': (str, None),
- 'new_status': (str, None), 'ln': (str, "en")})
-
- delete_key = argd['delete_key']
- ill_request_id = argd['ill_request_id']
- new_status = argd['new_status']
- ln = argd['ln']
-
- return bal.ill_request_details_step1(req, delete_key, ill_request_id, new_status, ln)
-
- def ill_request_details_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/ill_request_details_step2"""
-
- argd = wash_urlargd(form, {'delete_key': (str, None),
- 'ill_request_id': (str, None), 'recid': (str, ''), 'new_status': (str, None),
- 'library_id': (str, None), 'request_date': (str, None),
- 'expected_date': (str, None), 'arrival_date': (str, None),
- 'due_date': (str, None), 'return_date': (str, None),
- 'cost': (str, None), 'currency': (str, None),
- 'barcode': (str, None), 'library_notes': (str, None),
- 'title': (str, None), 'authors': (str, None), 'place': (str, None),
- 'publisher': (str, None), 'year': (str, None),
- 'edition': (str, None), 'isbn': (str, None),
- 'periodical_title': (str,None), 'volume': (str,''),
- 'issue': (str,''), 'page': (str,''), 'issn': (str,None),
- 'ln': (str, "en")})
-
- delete_key = argd['delete_key']
- ill_request_id = argd['ill_request_id']
- recid = argd['recid']
- new_status = argd['new_status']
- library_id = argd['library_id']
- request_date = argd['request_date']
- expected_date = argd['expected_date']
- arrival_date = argd['arrival_date']
- due_date = argd['due_date']
- return_date = argd['return_date']
- cost = argd['cost']
- currency = argd['currency']
- barcode = argd['barcode']
- library_notes = argd['library_notes']
-
- title = argd['title']
- authors = argd['authors']
- place = argd['place']
- publisher = argd['publisher']
- year = argd['year']
- edition = argd['edition']
- isbn = argd['isbn']
-
- periodical_title = argd['periodical_title']
- volume = argd['volume']
- issue = argd['issue']
- page = argd['page']
- issn = argd['issn']
-
- ln = argd['ln']
-
- if library_notes is not None:
- library_notes = library_notes.strip()
- if delete_key is not None:
- delete_key = delete_key.strip()
- if ill_request_id is not None:
- ill_request_id = ill_request_id.strip()
- if recid is not None:
- recid = recid.strip()
- if new_status is not None:
- new_status = new_status.strip()
- if library_id is not None:
- library_id = library_id.strip()
- if return_date is not None:
- return_date = return_date.strip()
- if expected_date is not None:
- expected_date = expected_date.strip()
- if arrival_date is not None:
- arrival_date = arrival_date.strip()
- if due_date is not None:
- due_date = due_date.strip()
- if return_date is not None:
- return_date = return_date.strip()
- if cost is not None:
- cost = cost.strip()
- if currency is not None:
- currency = currency.strip()
- if barcode is not None:
- barcode = barcode.strip()
-
- if title is not None:
- title = title.strip()
- if authors is not None:
- authors = authors.strip()
- if place is not None:
- place = place.strip()
- if publisher is not None:
- publisher = publisher.strip()
- if year is not None:
- year = year.strip()
- if edition is not None:
- edition = edition.strip()
- if isbn is not None:
- isbn = isbn.strip()
-
-
- if periodical_title is not None:
- periodical_title = periodical_title.strip()
- if volume is not None:
- volume = volume.strip()
- if issue is not None:
- issue = issue.strip()
- if page is not None:
- page = page.strip()
- if issn is not None:
- issn = issn.strip()
-
- article_info = {'periodical_title': periodical_title, 'title': title, 'authors': authors,
- 'place': place, 'publisher': publisher, 'year' : year, 'edition': "", 'issn' : issn,
- 'volume': volume, 'issue': issue, 'page': page }
-
- if recid:
- book_info = "{'recid': " + str(recid) + "}"
- else:
- book_info = {'title': title, 'authors': authors, 'place': place, 'publisher': publisher,
- 'year': year, 'edition': edition, 'isbn': isbn}
-
- return bal.ill_request_details_step2(req, delete_key, ill_request_id, new_status,
- library_id, request_date, expected_date, arrival_date,
- due_date, return_date, cost, currency, barcode,
- library_notes, book_info, article_info, ln)
-
- def purchase_details_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/purchase_details_step1"""
-
- argd = wash_urlargd(form, {'delete_key': (str, None), 'ill_request_id': (str, None),
- 'new_status': (str, None), 'ln': (str, "en")})
-
- delete_key = argd['delete_key']
- ill_request_id = argd['ill_request_id']
- new_status = argd['new_status']
- ln = argd['ln']
-
- return bal.purchase_details_step1(req, delete_key, ill_request_id, new_status, ln)
-
- def purchase_details_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/purchase_details_step2"""
-
- argd = wash_urlargd(form, {'ill_request_id': (str, None), 'recid': (str, ''),
- 'new_status': (str, None), 'library_id': (str, None),
- 'request_date': (str, None), 'expected_date': (str, None),
- 'arrival_date': (str, None), 'due_date': (str, None),
- 'return_date': (str, None), 'cost': (str, ''), 'authors': (str, ''),
- 'library_notes': (str, ''), 'title': (str, ''), 'place': (str, ''),
- 'publisher': (str, ''), 'year': (str, ''), 'edition': (str, ''),
- 'isbn': (str, ''), 'budget_code': (str, ''),
- 'standard_number': (str, ''), 'ln': (str, "en")})
-
- ill_request_id = argd['ill_request_id']
- new_status = argd['new_status']
- library_id = argd['library_id']
- request_date = argd['request_date']
- expected_date = argd['expected_date']
- arrival_date = argd['arrival_date']
- due_date = argd['due_date']
- return_date = argd['return_date']
- cost = argd['cost'].strip()
- budget_code = argd['budget_code'].strip()
- library_notes = argd['library_notes'].strip()
- standard_number = argd['standard_number'].strip()
-
- recid = argd['recid'].strip()
- title = argd['title'].strip()
- authors = argd['authors'].strip()
- place = argd['place'].strip()
- publisher = argd['publisher'].strip()
- year = argd['year'].strip()
- edition = argd['edition'].strip()
- isbn = argd['isbn'].strip()
- ln = argd['ln'].strip()
-
- if ill_request_id is not None:
- ill_request_id = ill_request_id.strip()
- if new_status is not None:
- new_status = new_status.strip()
- if library_id is not None:
- library_id = library_id.strip()
- if return_date is not None:
- return_date = return_date.strip()
- if expected_date is not None:
- expected_date = expected_date.strip()
- if arrival_date is not None:
- arrival_date = arrival_date.strip()
- if due_date is not None:
- due_date = due_date.strip()
- if return_date is not None:
- return_date = return_date.strip()
-
- if recid:
- item_info = "{'recid': " + str(recid) + "}"
- else:
- item_info = {'title': title, 'authors': authors,
- 'place': place, 'publisher': publisher,
- 'year': year, 'edition': edition, 'isbn': isbn,
- 'standard_number': standard_number}
-
- return bal.purchase_details_step2(req, None, ill_request_id,
- new_status, library_id, request_date,
- expected_date, arrival_date, due_date,
- return_date, cost, budget_code,
- library_notes, item_info, ln)
-
- def get_ill_library_notes(self, req, form):
- """ """
- argd = wash_urlargd(form, {'ill_id': (str, None), 'delete_key': (str, None),
- 'library_notes': (str, None), 'ln': (str, "en")})
- ill_id = argd['ill_id']
- delete_key = argd['delete_key']
- library_notes = argd['library_notes']
- ln = argd['ln']
-
- return bal.get_ill_library_notes(req, ill_id, delete_key, library_notes, ln)
-
-
- def list_ill_request(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/list_ill_request"""
- argd = wash_urlargd(form, {'status': (str, None), 'ln': (str, "en")})
- status = argd['status']
- ln = argd['ln']
-
- return bal.list_ill_request(req, status, ln)
-
- def list_purchase(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/list_purchase"""
- argd = wash_urlargd(form, {'status': (str, None), 'recid': (str, None), 'ln': (str, "en")})
- status = argd['status']
- recid = argd['recid']
- ln = argd['ln']
-
- return bal.list_purchase(req, status, recid, ln)
-
- def list_proposal(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/list_proposal"""
- argd = wash_urlargd(form, {'status': (str, None), 'ln': (str, "en")})
- status = argd['status']
- ln = argd['ln']
-
- return bal.list_proposal(req, status, ln)
-
-
- def ill_search(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/holdings_search"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.ill_search(req, ln)
-
- def ill_search_result(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/item_search_result"""
- argd = wash_urlargd(form, {'p': (str, None), 'f': (str, None), 'date_from': (str, None),
- 'date_to': (str, None), 'ln': (str, "en")})
- p = argd['p']
- f = argd['f']
- date_from = argd['date_from']
- date_to = argd['date_to']
- ln = argd['ln']
-
- if p is not None:
- p = p.strip()
- if date_from is not None:
- date_from = date_from.strip()
- if date_to is not None:
- date_to = date_to.strip()
-
- return bal.ill_search_result(req, p, f, date_from, date_to, ln)
-
-
-
-
-# "Library" related pages
-
-
-
-
- def get_library_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_library_details"""
- argd = wash_urlargd(form, {'library_id': (str, None), 'ln': (str, "en")})
- library_id = argd['library_id']
- ln = argd['ln']
- return bal.get_library_details(req, library_id, ln)
-
- def merge_libraries_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/merge_libraries_step1"""
- argd = wash_urlargd(form, {'library_id': (int, None), 'p': (str, None),
- 'f': (str, None), 'ln': (str, None)})
-
- library_id = argd['library_id']
- p = argd['p']
- f = argd['f']
- ln = argd['ln']
-
- if p is not None:
- p = p.strip()
-
- return bal.merge_libraries_step1(req, library_id, f, p, ln)
-
- def merge_libraries_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/merge_libraries_step2"""
- argd = wash_urlargd(form, {'library_from': (int, None), 'library_to': (int, None),
- 'ln': (str, "en")})
-
- library_from = argd['library_from']
- library_to = argd['library_to']
- ln = argd['ln']
-
- return bal.merge_libraries_step2(req, library_from, library_to, ln)
-
- def merge_libraries_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/merge_libraries_step2"""
- argd = wash_urlargd(form, {'library_from': (int, None), 'library_to': (int, None),
- 'ln': (str, "en")})
-
- library_from = argd['library_from']
- library_to = argd['library_to']
- ln = argd['ln']
-
- return bal.merge_libraries_step3(req, library_from, library_to, ln)
-
-
- def add_new_library_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_library_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.add_new_library_step1(req, ln)
-
- def add_new_library_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_library_step2"""
- argd = wash_urlargd(form, {'name': (str, ''), 'email': (str, ''),
- 'phone': (str, ''), 'address': (str, ''), 'type': (str, ''),
- 'notes': (str, None), 'ln': (str, "en")})
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- library_type = argd['type']
- notes = argd['notes']
- ln = argd['ln']
-
- name = name.strip()
- email = email.strip()
- phone = phone.strip()
- address = address.strip()
- library_type = library_type.strip()
-
- return bal.add_new_library_step2(req, name, email, phone, address,
- library_type, notes, ln)
-
- def add_new_library_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_library_step3"""
- argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
- 'phone': (str, None), 'address': (str, None), 'lib_type': (str, None),
- 'notes': (str, None), 'ln': (str, "en")})
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- library_type = argd['lib_type']
- notes = argd['notes']
- ln = argd['ln']
-
- return bal.add_new_library_step3(req,name, email, phone, address, library_type, notes, ln)
-
-
- def update_library_info_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_library_info_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.update_library_info_step1(req, ln)
-
- def update_library_info_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_library_info_step2"""
- argd = wash_urlargd(form, {'column': (str, None), 'string': (str, None),
- 'ln': (str, "en")})
- column = argd['column']
- string = argd['string']
- ln = argd['ln']
-
- if string is not None:
- string = string.strip()
-
- return bal.update_library_info_step2(req, column, string, ln)
-
- def update_library_info_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_library_info_step3"""
- argd = wash_urlargd(form, {'library_id': (str, None), 'ln': (str, "en")})
- library_id = argd['library_id']
- ln = argd['ln']
- return bal.update_library_info_step3(req, library_id, ln)
-
- def update_library_info_step4(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_library_info_step4"""
- argd = wash_urlargd(form, {'name': (str, ''), 'email': (str, ''),
- 'phone': (str, ''), 'address': (str, ''), 'library_id': (str, ''),
- 'lib_type': (str, ''), 'ln': (str, "en")})
-
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- lib_type = argd['lib_type']
- library_id = argd['library_id']
- ln = argd['ln']
-
- name = name.strip()
- email = email.strip()
- phone = phone.strip()
- address = address.strip()
- lib_type = lib_type.strip()
-
- return bal.update_library_info_step4(req, name, email, phone, address, lib_type,
- library_id, ln)
-
- def update_library_info_step5(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_library_info_step5"""
- argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
- 'phone': (str, None), 'address': (str, None), 'library_id': (str, None),
- 'lib_type': (str, None), 'ln': (str, "en")})
-
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- lib_type = argd['lib_type']
- library_id = argd['library_id']
- ln = argd['ln']
-
- return bal.update_library_info_step5(req, name, email, phone, address, lib_type,
- library_id, ln)
-
-
- def get_library_notes(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_library_notes"""
- argd = wash_urlargd(form, {'library_id': (str, None), 'delete_key': (str, None),
- 'library_notes': (str, None), 'ln': (str, "en")})
- library_id = argd['library_id']
- delete_key = argd['delete_key']
- library_notes = argd['library_notes']
- ln = argd['ln']
- return bal.get_library_notes(req, library_id, delete_key, library_notes, ln)
-
- def search_library_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/search_library_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.search_library_step1(req=req, ln=ln)
-
- def search_library_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/search_library_step2"""
- argd = wash_urlargd(form, {'column': (str, ''), 'string': (str, ''), 'ln': (str, "en")})
- column = argd['column']
- string = argd['string']
- ln = argd['ln']
-
- string = string.strip()
-
- return bal.search_library_step2(req, column, string, ln)
-
-
-
-# "Vendor related pages
-
-
-
- def get_vendor_details(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_vendor_details"""
- argd = wash_urlargd(form, {'vendor_id': (str, None), 'ln': (str, "en")})
- vendor_id = argd['vendor_id']
- ln = argd['ln']
- return bal.get_vendor_details(req, vendor_id, ln)
-
- def add_new_vendor_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_vendor_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.add_new_vendor_step1(req, ln)
-
- def add_new_vendor_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_vendor_step2"""
- argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
- 'phone': (str, None), 'address': (str, None), 'notes': (str, None), 'ln': (str, "en")})
-
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- notes = argd['notes']
- ln = argd['ln']
-
- if name is not None:
- name = name.strip()
- if email is not None:
- email = email.strip()
- if phone is not None:
- phone = phone.strip()
- if address is not None:
- address = address.strip()
-
- return bal.add_new_vendor_step2(req, name, email, phone, address,
- notes, ln)
-
- def add_new_vendor_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/add_new_vendor_step3"""
- argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
- 'phone': (str, None), 'address': (str, None), 'notes': (str, None),
- 'ln': (str, "en")})
-
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- notes = argd['notes']
- ln = argd['ln']
- return bal.add_new_vendor_step3(req, name, email, phone, address,
- notes, ln)
-
-
- def update_vendor_info_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_vendor_info_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.update_vendor_info_step1(req, ln)
-
- def update_vendor_info_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_vendor_info_step2"""
- argd = wash_urlargd(form, {'column': (str, None), 'string': (str, None),
- 'ln': (str, "en")})
-
- column = argd['column']
- string = argd['string']
- ln = argd['ln']
-
- if string is not None:
- string = string.strip()
-
- return bal.update_vendor_info_step2(req, column, string, ln)
-
- def update_vendor_info_step3(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_vendor_info_step3"""
- argd = wash_urlargd(form, {'vendor_id': (str, None), 'ln': (str, "en")})
- vendor_id = argd['vendor_id']
- ln = argd['ln']
- return bal.update_vendor_info_step3(req, vendor_id, ln)
-
- def update_vendor_info_step4(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_vendor_info_step4"""
- argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
- 'phone': (str, None), 'address': (str, None), 'vendor_id': (str, None),
- 'ln': (str, "en")})
-
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- vendor_id = argd['vendor_id']
- ln = argd['ln']
-
- if name is not None:
- name = name.strip()
- if email is not None:
- email = email.strip()
- if phone is not None:
- phone = phone.strip()
- if address is not None:
- address = address.strip()
-
- return bal.update_vendor_info_step4(req, name, email, phone, address,
- vendor_id, ln)
-
- def update_vendor_info_step5(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/update_vendor_info_step5"""
- argd = wash_urlargd(form, {'name': (str, None), 'email': (str, None),
- 'phone': (str, None), 'address': (str, None), 'vendor_id': (str, None),
- 'ln': (str, "en")})
-
- name = argd['name']
- email = argd['email']
- phone = argd['phone']
- address = argd['address']
- vendor_id = argd['vendor_id']
- ln = argd['ln']
- return bal.update_vendor_info_step5(req, name, email, phone, address,
- vendor_id, ln)
-
-
- def get_vendor_notes(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/get_vendor_notes"""
- argd = wash_urlargd(form, {'vendor_id': (str, None), 'add_notes': (str, None),
- 'new_note': (str, None), 'ln': (str, "en")})
- vendor_id = argd['vendor_id']
- add_notes = argd['add_notes']
- new_note = argd['new_note']
- ln = argd['ln']
- return bal.get_vendor_notes(req, vendor_id, add_notes, new_note, ln)
-
- def search_vendor_step1(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/search_vendor_step1"""
- argd = wash_urlargd(form, {'ln': (str, "en")})
- ln = argd['ln']
- return bal.search_vendor_step1(req, ln)
-
- def search_vendor_step2(self, req, form):
- """http://cds.cern.ch/admin2/bibcirculation/search_vendor_step2"""
- argd = wash_urlargd(form, {'column': (str, ''), 'string': (str, ''), 'ln': (str, "en")})
- column = argd['column']
- string = argd['string']
- ln = argd['ln']
-
- if string is not None:
- string = string.strip()
-
- return bal.search_vendor_step2(req, column, string, ln)
-
-
- def __call__(self, req, form):
- """Redirect calls without final slash."""
- redirect_to_url(req, '%s/admin2/bibcirculation/' % CFG_SITE_URL)
diff --git a/invenio/legacy/bibcirculation/adminlib.py b/invenio/legacy/bibcirculation/adminlib.py
deleted file mode 100644
index ff1873b83..000000000
--- a/invenio/legacy/bibcirculation/adminlib.py
+++ /dev/null
@@ -1,6284 +0,0 @@
-# Administrator interface for Bibcirculation
-#
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-# """Invenio Bibcirculation Administrator Interface."""
-
-from __future__ import division
-
-"""
- Invenio Bibcirculation Administrator.
- The functions are positioned by grouping into logical
- categories('User Pages', 'Loans, Returns and Loan requests',
- 'ILLs', 'Libraries', 'Vendors' ...)
- These orders should be maintained and when necessary, improved
- for readability, as and when additional methods are added.
- When applicable, methods should be renamed, refactored and
- appropriate documentation added.
-"""
-
-__revision__ = "$Id$"
-
-__lastupdated__ = """$Date$"""
-
-import datetime, time, types
-
-# Other Invenio imports
-from invenio.config import \
- CFG_SITE_LANG, \
- CFG_SITE_URL, \
- CFG_SITE_SECURE_URL, \
- CFG_CERN_SITE
-import invenio.modules.access.engine as acce
-from invenio.legacy.webpage import page
-from invenio.legacy.webuser import getUid, page_not_authorized
-from invenio.ext.logging import register_exception
-from invenio.ext.email import send_email
-from invenio.legacy.search_engine import perform_request_search, record_exists
-from invenio.utils.url import create_html_link, create_url, redirect_to_url
-from invenio.base.i18n import gettext_set_language
-from invenio.config import \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, \
- CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS, \
- CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW, \
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN, \
- CFG_BIBCIRCULATION_ACQ_STATUS_NEW, \
- CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED
-
-# Bibcirculation imports
-from invenio.legacy.bibcirculation.config import \
- CFG_BIBCIRCULATION_TEMPLATES, CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, \
- CFG_BIBCIRCULATION_LOANS_EMAIL, CFG_BIBCIRCULATION_ILLS_EMAIL, \
- CFG_BIBCIRCULATION_PROPOSAL_TYPE, CFG_BIBCIRCULATION_ACQ_STATUS
-from invenio.legacy.bibcirculation.utils import book_title_from_MARC, \
- update_status_if_expired, \
- renew_loan_for_X_days, \
- print_pending_hold_requests_information, \
- print_new_loan_information, \
- validate_date_format, \
- generate_email_body, \
- book_information_from_MARC, \
- search_user, \
- tag_all_requests_as_done, \
- update_user_info_from_ldap, \
- update_request_data, \
- update_requests_statuses, \
- has_date_format, \
- generate_tmp_barcode, \
- looks_like_dictionary
-import invenio.legacy.bibcirculation.db_layer as db
-import invenio.legacy.template
-bc_templates = invenio.legacy.template.load('bibcirculation')
-
-
-
-def is_adminuser(req):
- """check if user is a registered administrator. """
-
- return acce.acc_authorize_action(req, "runbibcirculation")
-
-def mustloginpage(req, message):
- """show a page asking the user to login."""
-
- navtrail_previous_links = '' \
- 'Admin Area > ' \
- '' \
- 'BibCirculation Admin ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL)
-
- return page_not_authorized(req=req, text=message,
- navtrail=navtrail_previous_links)
-
-def load_template(template):
- """
- Load a letter/notification template from
- bibcirculation_config.py.
-
- @type template: string.
- @param template: template that will be used.
-
- @return: template(string)
- """
-
- if template == "overdue_letter":
- output = CFG_BIBCIRCULATION_TEMPLATES['OVERDUE']
-
- elif template == "reminder":
- output = CFG_BIBCIRCULATION_TEMPLATES['REMINDER']
-
- elif template == "notification":
- output = CFG_BIBCIRCULATION_TEMPLATES['NOTIFICATION']
-
- elif template == "ill_received":
- output = CFG_BIBCIRCULATION_TEMPLATES['ILL_RECEIVED']
-
- elif template == "ill_recall1":
- output = CFG_BIBCIRCULATION_TEMPLATES['ILL_RECALL1']
-
- elif template == "ill_recall2":
- output = CFG_BIBCIRCULATION_TEMPLATES['ILL_RECALL2']
-
- elif template == "ill_recall3":
- output = CFG_BIBCIRCULATION_TEMPLATES['ILL_RECALL3']
-
- elif template == "claim_return":
- output = CFG_BIBCIRCULATION_TEMPLATES['SEND_RECALL']
-
- elif template == "proposal_notification":
- output = CFG_BIBCIRCULATION_TEMPLATES['PROPOSAL_NOTIFICATION']
-
- elif template == "proposal_acceptance":
- output = CFG_BIBCIRCULATION_TEMPLATES['PROPOSAL_ACCEPTANCE_NOTIFICATION']
-
- elif template == "proposal_refusal":
- output = CFG_BIBCIRCULATION_TEMPLATES['PROPOSAL_REFUSAL_NOTIFICATION']
-
- elif template == "purchase_notification":
- output = CFG_BIBCIRCULATION_TEMPLATES['PURCHASE_NOTIFICATION']
-
- elif template == "purchase_received_tid":
- output = CFG_BIBCIRCULATION_TEMPLATES['PURCHASE_RECEIVED_TID']
-
- elif template == "purchase_received_cash":
- output = CFG_BIBCIRCULATION_TEMPLATES['PURCHASE_RECEIVED_CASH']
-
- else:
- output = CFG_BIBCIRCULATION_TEMPLATES['EMPTY']
-
- return output
-
-def index(req, ln=CFG_SITE_LANG):
- """
- main function to show pages for bibcirculationadmin
- """
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_index(ln=ln)
-
- return page(title=_("BibCirculation Admin"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-
-###
-### Loans, Loan Requests, Loan Returns related templates.
-###
-
-
-
-
-def loan_on_desk_step1(req, key, string, ln=CFG_SITE_LANG):
- """
- Step 1/4 of loan procedure.
- Search a user/borrower and return a list with all the possible results.
-
- @type key: string.
- @param key: attribute that will be considered during the search. Can be 'name',
- 'email' or 'ccid/id'.
-
- @type string: string.
- @param string: keyword used during the search.
-
- @return: list of potential borrowers.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- infos = []
- _ = gettext_set_language(ln)
-
- if key and not string:
- infos.append(_('Empty string. Please, try again.'))
- body = bc_templates.tmpl_loan_on_desk_step1(result=None, key=key,
- string=string, infos=infos,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("Loan on desk"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- result = search_user(key, string)
- borrowers_list = []
-
- if len(result) == 0 and key:
- if CFG_CERN_SITE:
- infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
- else:
- new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/add_new_borrower_step1',
- {'ln': ln}, _("Register new borrower."))
- message = _("0 borrowers found.") + ' ' + new_borrower_link
- infos.append(message)
- elif len(result) == 1:
- return loan_on_desk_step2(req, result[0][0], ln)
- else:
- for user in result:
- borrower_data = db.get_borrower_data_by_id(user[0])
- borrowers_list.append(borrower_data)
-
- body = bc_templates.tmpl_loan_on_desk_step1(result=borrowers_list,
- key=key,
- string=string,
- infos=infos,
- ln=ln)
-
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("Circulation management"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def loan_on_desk_step2(req, user_id, ln=CFG_SITE_LANG):
- """
- Step 2/4 of loan procedure.
- Display the user/borrower's information.
-
- @type user_id: integer
- @param user_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- _ = gettext_set_language(ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- infos = []
-
- body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
- infos=infos,
- ln=ln)
-
- return page(title=_("Circulation management"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def loan_on_desk_step3(req, user_id, list_of_barcodes, ln=CFG_SITE_LANG):
- """
- Step 3/4 of loan procedure.
- Checks that the barcodes exist and that there are no request on these records.
- Lets the librarian change the due dates and add notes.
-
- @type user_id: integer
- @param user_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @type list_of_barcodes: list
- @param list_of_barcodes: list of strings with the barcodes
- introduced by the librarian with the barcode reader
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- _ = gettext_set_language(ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- infos = []
- list_of_books = []
-
- # to avoid duplicates
- aux = []
- for bc in list_of_barcodes:
- if bc not in aux:
- aux.append(bc)
- list_of_barcodes = aux
-
- for value in list_of_barcodes:
- recid = db.get_id_bibrec(value)
- loan_id = db.is_item_on_loan(value)
- item_description = db.get_item_description(value)
-
- if recid is None:
- infos.append(_('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': value, 'x_strong_tag_open': '', 'x_strong_tag_close': ''} + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
- infos=infos,
- ln=ln)
- elif loan_id:
- infos.append('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on a loan. Cannot be checked out.' % {'x_barcode': value, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
- infos=infos,
- ln=ln)
- elif user_id is None:
- infos.append(_('You must select one borrower.'))
- body = bc_templates.tmpl_loan_on_desk_step1(result=None,
- key='',
- string='',
- infos=infos,
- ln=ln)
- else:
-
- queue = db.get_queue_request(recid, item_description)
- (library_id, location) = db.get_lib_location(value)
- tup = (recid, value, library_id, location)
- list_of_books.append(tup)
- book_details = db.get_item_info(value)
- item_status = book_details[7]
-
- if item_status != CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF:
- message = _("%(x_strong_tag_open)sWARNING:%(x_strong_tag_close)s Note that item %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s status is %(x_strong_tag_open)s%(x_status)s%(x_strong_tag_close)s") % {'x_barcode': value, 'x_strong_tag_open': '', 'x_strong_tag_close': '', 'x_status': item_status}
-
- infos.append(message)
-
- if CFG_CERN_SITE:
- library_type = db.get_library_type(library_id)
- if library_type != CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN:
- library_name = db.get_library_name(library_id)
- message = _("%(x_strong_tag_open)sWARNING:%(x_strong_tag_close)s Note that item %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s location is %(x_strong_tag_open)s%(x_location)s%(x_strong_tag_close)s") % {'x_barcode': value, 'x_strong_tag_open': '', 'x_strong_tag_close': '', 'x_location': library_name}
- infos.append(message)
-
- if len(queue) != 0 and queue[0][0] != user_id:
- message = _("Another user is waiting for the book: %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s. \n\n If you want continue with this loan choose %(x_strong_tag_open)s[Continue]%(x_strong_tag_close)s.") % {'x_title': book_title_from_MARC(recid), 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
- infos.append(message)
-
- body = bc_templates.tmpl_loan_on_desk_step3(user_id=user_id,
- list_of_books=list_of_books,
- infos=infos, ln=ln)
-
- if list_of_barcodes == []:
- infos.append(_('Empty barcode.') + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
- infos=infos,
- ln=ln)
-
- if infos == []:
- # shortcut to simplify loan process
- due_dates = []
- for bc in list_of_barcodes:
- due_dates.append(renew_loan_for_X_days(bc))
-
- return loan_on_desk_step4(req, list_of_barcodes, user_id,
- due_dates, None, ln)
-
- else:
- return page(title=_("Circulation management"),
- uid=id_user,
- req=req,
- body=body,
- metaheaderadd = "" % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def loan_on_desk_step4(req, list_of_barcodes, user_id,
- due_date, note, ln=CFG_SITE_LANG):
- """
- Step 4/4 of loan procedure.
- Checks that items are not on loan and that the format of
- the dates is correct and creates the loans
-
- @type user_id: integer
- @param user_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @type list_of_barcodes: list
- @param list_of_barcodes: list of strings with the barcodes
- introduced by the librarian with the barcode reader
-
- @type due_date: list.
- @param due_date: list of due dates.
-
- @type note: string.
- @param note: note about the new loan.
-
- @return: page with the list 'Last Loans'
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- _ = gettext_set_language(ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- infos = []
-
- #loaned_on = datetime.date.today()
-
- #Check if one of the given items is on loan.
- on_loan = []
- for barcode in list_of_barcodes:
- is_on_loan = db.is_item_on_loan(barcode)
- if is_on_loan:
- on_loan.append(barcode)
-
- if len(on_loan) != 0:
- message = _("The items with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s are already on loan.") % {'x_barcode': on_loan, 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
- infos.append(message)
-
- body = bc_templates.tmpl_loan_on_desk_step1(result=None, key='',
- string='', infos=infos,
- ln=ln)
-
- return page(title=_("Loan on desk"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- # validate the period of interest given by the admin
- for date in due_date:
- if validate_date_format(date) is False:
- infos = []
- message = _("The given due date %(x_strong_tag_open)s%(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': date, 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
-
- infos.append(message)
-
- list_of_books = []
- for bc in list_of_barcodes:
- recid = db.get_id_bibrec(bc)
- (library_id, location) = db.get_lib_location(bc)
- tup = (recid, bc, library_id, location)
- list_of_books.append(tup)
-
- body = bc_templates.tmpl_loan_on_desk_step3(user_id=user_id,
- list_of_books=list_of_books,
- infos=infos, ln=ln)
-
- return page(title=_("Circulation management"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- #if borrower_id == None:
- # db.new_borrower(ccid, name, email, phone, address, mailbox, '')
- # borrower_id = db.get_borrower_id_by_email(email)
-
- for i in range(len(list_of_barcodes)):
- note_format = {}
- if note:
- note_format[time.strftime("%Y-%m-%d %H:%M:%S")] = str(note)
- barcode = list_of_barcodes[i]
- recid = db.get_id_bibrec(barcode)
- db.new_loan(user_id, recid, barcode, due_date[i],
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- 'normal', note_format)
-
- # Duplicate requests on items belonging to a single record has been disabled.
- db.tag_requests_as_done(user_id, barcode)
- # tag_all_requests_as_done(barcode, user_id)
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
- update_requests_statuses(barcode)
-
- infos.append(_("A loan for the item %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s, with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s, has been registered with success.") % {'x_title': book_title_from_MARC(recid), 'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- infos.append(_("You could enter the barcode for this user's next loan, if any."))
- body = bc_templates.tmpl_loan_on_desk_step2(user_id=user_id,
- infos=infos, ln=ln)
- return page(title=_("Circulation management"),
- uid=id_user,
- req=req,
- body=body,
- metaheaderadd = "" % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def loan_on_desk_confirm(req, barcode=None, borrower_id=None, ln=CFG_SITE_LANG):
- """
- *** Obsolete and unmantained function ***
- Confirm the return of an item.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- result = db.loan_on_desk_confirm(barcode, borrower_id)
-
- body = bc_templates.tmpl_loan_on_desk_confirm(result=result,
- barcode=barcode,
- borrower_id=borrower_id,
- ln=ln)
-
- return page(title=_("Loan on desk confirm"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_new_loan(req, barcode, borrower_id,
- request_id, new_note, print_data, ln=CFG_SITE_LANG):
- """
- Register a new loan. This function is from the "Create Loan" pages.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @type request_id: integer.
- @param request_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
-
- @type new_note: string.
- @param new_note: associate a note to this loan.
-
- @type print_data: string.
- @param print_data: print the information about this loan.
-
- @return: new loan
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- has_recid = db.get_id_bibrec(barcode)
- loan_id = db.is_item_on_loan(barcode)
-
- recid = db.get_request_recid(request_id)
- req_barcode = db.get_requested_barcode(request_id)
- req_description = db.get_item_description(req_barcode)
- # Get all the items belonging to the record whose
- # description is the same.
- list_of_barcodes = db.get_barcodes(recid, req_description)
-
- infos = []
-
- if print_data == 'true':
- return print_new_loan_information(req, ln)
-
- else:
- if has_recid is None:
- message = _('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''} + ' ' + _('Please, try again.')
- infos.append(message)
- borrower = db.get_borrower_details(borrower_id)
- title = _("Create Loan")
- body = bc_templates.tmpl_create_loan(request_id=request_id,
- recid=recid,
- borrower=borrower,
- infos=infos,
- ln=ln)
-
- elif loan_id:
- infos.append(_('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on loan.') % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- borrower = db.get_borrower_details(borrower_id)
- title = _("Create Loan")
- body = bc_templates.tmpl_create_loan(request_id=request_id,
- recid=recid,
- borrower=borrower,
- infos=infos,
- ln=ln)
-
- elif barcode not in list_of_barcodes:
- infos.append(_('The given barcode "%(x_barcode)s" does not correspond to requested item.') % {'x_barcode': barcode})
- borrower = db.get_borrower_details(borrower_id)
- title = _("Create Loan")
- body = bc_templates.tmpl_create_loan(request_id=request_id,
- recid=recid,
- borrower=borrower,
- infos=infos,
- ln=ln)
-
- else:
- recid = db.get_id_bibrec(barcode)
- #loaned_on = datetime.date.today()
- due_date = renew_loan_for_X_days(barcode)
-
- if new_note:
- note_format = '[' + time.ctime() + '] ' + new_note + '\n'
- else:
- note_format = ''
-
- last_id = db.new_loan(borrower_id, recid, barcode,
- due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- 'normal', note_format)
-
- tag_all_requests_as_done(barcode, borrower_id)
-
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
-
- db.update_loan_request_status(CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
- request_id)
- db.update_request_barcode(barcode, request_id)
- update_requests_statuses(barcode)
-
- result = db.get_all_loans(20)
-
- infos.append(_('A new loan has been registered with success.'))
-
- title = _("Current loans")
- body = bc_templates.tmpl_all_loans(result=result,
- infos=infos,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def create_loan(req, request_id, recid, borrower_id, ln=CFG_SITE_LANG):
- """
- Create a new loan from a hold request.
-
- @type request_id: integer.
- @param request_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- borrower = db.get_borrower_details(borrower_id)
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_create_loan(request_id=request_id,
- recid=recid,
- borrower=borrower,
- infos=infos,
- ln=ln)
-
- return page(title=_("Create Loan"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def make_new_loan_from_request(req, check_id, barcode, ln=CFG_SITE_LANG):
- """
- Turns a request into a loan.
-
- @type check_id: integer.
- @param check_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- recid = db.get_request_recid(check_id)
- borrower_id = db.get_request_borrower_id(check_id)
- borrower_info = db.get_borrower_details(borrower_id)
-
- due_date = renew_loan_for_X_days(barcode)
- if db.is_item_on_loan(barcode):
- infos.append('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on loan.' % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- return redirect_to_url(req,
- '%s/admin2/bibcirculation/all_loans?ln=%s&msg=ok' % (CFG_SITE_SECURE_URL, ln))
- else:
- db.new_loan(borrower_id, recid, barcode, due_date,
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, 'normal', '')
- infos.append(_('A new loan has been registered with success.'))
-
- tag_all_requests_as_done(barcode, borrower_id)
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
- update_requests_statuses(barcode)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_register_new_loan(borrower_info=borrower_info,
- infos=infos,
- recid=recid,
- ln=ln)
-
- return page(title=_("New Loan"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def loan_return(req, ln=CFG_SITE_LANG):
- """
- Page where is possible to register the return of an item.
- """
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- body = bc_templates.tmpl_loan_return(infos=infos, ln=ln)
-
- return page(title=_("Loan return"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def loan_return_confirm(req, barcode, ln=CFG_SITE_LANG):
- """
- Performs the return of a loan and displays a confirmation page.
- In case the book is requested, it is possible to select a request
- and make a loan from it (make_new_loan_from_request)
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- infos = []
- _ = gettext_set_language(ln)
-
- recid = db.get_id_bibrec(barcode)
- loan_id = db.is_item_on_loan(barcode)
-
- if recid is None:
- infos.append(_('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''} + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_loan_return(infos=infos, ln=ln)
-
- elif loan_id is None:
- message = _("The item the with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is not on loan. Please, try again.") % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
-
- infos.append(message)
- body = bc_templates.tmpl_loan_return(infos=infos, ln=ln)
-
- else:
-
- library_id = db.get_item_info(barcode)[1]
- if CFG_CERN_SITE:
- library_type = db.get_library_type(library_id)
- if library_type != CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN:
- library_name = db.get_library_name(library_id)
- message = _("%(x_strong_tag_open)sWARNING:%(x_strong_tag_close)s Note that item %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s location is %(x_strong_tag_open)s%(x_location)s%(x_strong_tag_close)s") % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': '', 'x_location': library_name}
- infos.append(message)
-
- borrower_id = db.get_borrower_id(barcode)
- borrower_name = db.get_borrower_name(borrower_id)
-
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, barcode)
- db.return_loan(barcode)
-
- update_requests_statuses(barcode)
-
- description = db.get_item_description(barcode)
- result = db.get_pending_loan_request(recid, description)
- body = bc_templates.tmpl_loan_return_confirm(
- infos=infos,
- borrower_name=borrower_name,
- borrower_id=borrower_id,
- recid=recid,
- barcode=barcode,
- return_date=datetime.date.today(),
- result=result,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("Loan return"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def claim_book_return(req, borrower_id, recid, loan_id,
- template, ln=CFG_SITE_LANG):
- """
- Claim the return of an item.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- recid: identify the record. It is also the primary key of
- the table bibrec.
-
- template: letter template.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- email_body = generate_email_body(load_template(template), loan_id)
-
- email = db.get_borrower_email(borrower_id)
- subject = book_title_from_MARC(int(recid))
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_borrower_notification(email=email,
- subject=subject,
- email_body=email_body,
- borrower_id=borrower_id,
- from_address=CFG_BIBCIRCULATION_LOANS_EMAIL,
- ln=ln)
-
-
- return page(title=_("Claim return"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def change_due_date_step1(req, barcode, borrower_id, ln=CFG_SITE_LANG):
- """
- Change the due date of a loan, step1.
-
- loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- loan_id = db.get_current_loan_id(barcode)
- loan_details = db.get_loan_infos(loan_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_change_due_date_step1(loan_details=loan_details,
- loan_id=loan_id,
- borrower_id=borrower_id,
- ln=ln)
- return page(title=_("Change due date"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- #metaheaderadd = '' % CFG_SITE_SECURE_URL,
- metaheaderadd = '' % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def change_due_date_step2(req, new_due_date, loan_id, borrower_id,
- ln=CFG_SITE_LANG):
- """
- Change the due date of a loan, step2.
-
- due_date: new due date.
-
- loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- db.update_due_date(loan_id, new_due_date)
- update_status_if_expired(loan_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_change_due_date_step2(new_due_date=new_due_date,
- borrower_id=borrower_id,
- ln=ln)
- return page(title=_("Change due date"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def place_new_request_step1(req, barcode, recid, key, string, ln=CFG_SITE_LANG):
- """
- Place a new request from the item's page, step1.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- recid: identify the record. It is also the primary key of
- the table bibrec.
-
- key: search field.
-
- string: search pattern.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- recid = db.get_id_bibrec(barcode)
- infos = []
-
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
- if not barcode:
- return page(title=_("Item search"),
- req=req,
- body=bc_templates.tmpl_item_search(infos=[], ln=ln),
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- if key and not string:
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_place_new_request_step1(result=None,
- key=key,
- string=string,
- barcode=barcode,
- recid=recid,
- infos=infos,
- ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- result = search_user(key, string)
- borrowers_list = []
-
- if len(result) == 0 and key:
- if CFG_CERN_SITE:
- infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
- else:
- new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/add_new_borrower_step1',
- {'ln': ln}, _("Register new borrower."))
- message = _("0 borrowers found.") + ' ' + new_borrower_link
- infos.append(message)
- else:
- for user in result:
- borrower_data = db.get_borrower_data_by_id(user[0])
- borrowers_list.append(borrower_data)
-
- if len(result) == 1:
- return place_new_request_step2(req, barcode, recid,
- borrowers_list[0], ln)
- else:
- body = bc_templates.tmpl_place_new_request_step1(result=borrowers_list,
- key=key,
- string=string,
- barcode=barcode,
- recid=recid,
- infos=infos,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def place_new_request_step2(req, barcode, recid, user_info, ln=CFG_SITE_LANG):
- """
- Place a new request from the item's page, step2.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type user_info: list.
- @param user_info: information of the user/borrower who was selected.
-
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if not user_info:
- # Case someone try directly to access to step2 without passing by previous step
- if barcode:
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=bc_templates.tmpl_place_new_request_step1(result=None,
- key=None,
- string=None,
- barcode=barcode,
- recid=recid,
- infos=[],
- ln=ln),
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
- else:
- return page(title=_("Item search"),
- req=req,
- body=bc_templates.tmpl_item_search(infos=[], ln=ln),
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
- body = bc_templates.tmpl_place_new_request_step2(barcode=barcode,
- recid=recid,
- user_info=user_info,
- infos=[],
- ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body,
- metaheaderadd="" % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def place_new_request_step3(req, barcode, recid, user_info,
- period_from, period_to, ln=CFG_SITE_LANG):
- """
- Place a new request from the item's page, step3.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @return: new request.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
- if user_info:
- (_id, ccid, name, email, phone, address, mailbox) = user_info
- else:
- # Case someone try directly to access to step3 without passing by previous step
- if barcode:
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=bc_templates.tmpl_place_new_request_step1(result=None,
- key="",
- string="",
- barcode=barcode,
- recid=recid,
- infos=[],
- ln=ln),
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
- else:
-
- return page(title=_("Item search"),
- req=req,
- body=bc_templates.tmpl_item_search(infos=[], ln=ln),
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- # validate the period of interest given by the admin
- if not period_from or validate_date_format(period_from) is False:
- infos = []
- infos.append(_("The period of interest %(x_strong_tag_open)sFrom: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_from, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
-
- body = bc_templates.tmpl_place_new_request_step2(barcode=barcode,
- recid=recid,
- user_info=user_info,
- infos=infos,
- ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- elif not period_to or validate_date_format(period_to) is False:
- infos = []
- infos.append(_("The period of interest %(x_strong_tag_open)sTo: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_to, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
-
- body = bc_templates.tmpl_place_new_request_step2(barcode=barcode,
- recid=recid,
- user_info=user_info,
- infos=infos,
- ln=ln)
-
- # Register request
- borrower_id = db.get_borrower_id_by_email(email)
-
- if borrower_id is None:
- db.new_borrower(ccid, name, email, phone, address, mailbox, '')
- borrower_id = db.get_borrower_id_by_email(email)
-
- req_id = db.new_hold_request(borrower_id, recid, barcode,
- period_from, period_to,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
-
- pending_request = update_requests_statuses(barcode)
-
- if req_id == pending_request:
- (title, year, author,
- isbn, publisher) = book_information_from_MARC(int(recid))
- details = db.get_loan_request_details(req_id)
- if details:
- library = details[3]
- location = details[4]
- request_date = details[7]
- else:
- location = ''
- library = ''
- request_date = ''
-
- link_to_holdings_details = CFG_SITE_URL + \
- '/record/%s/holdings' % str(recid)
-
- subject = _('New request')
- message = load_template('notification')
-
- message = message % (name, ccid, email, address, mailbox, title,
- author, publisher, year, isbn, location, library,
- link_to_holdings_details, request_date)
-
-
- send_email(fromaddr = CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
- toaddr = CFG_BIBCIRCULATION_LOANS_EMAIL,
- subject = subject,
- content = message,
- header = '',
- footer = '',
- attempt_times=1,
- attempt_sleeptime=10
- )
- send_email(fromaddr = CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
- toaddr = email,
- subject = subject,
- content = message,
- header = '',
- footer = '',
- attempt_times=1,
- attempt_sleeptime=10
- )
-
- body = bc_templates.tmpl_place_new_request_step3(ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def place_new_loan_step1(req, barcode, recid, key, string, ln=CFG_SITE_LANG):
- """
- Place a new loan from the item's page, step1.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type key: string.
- @param key: search field.
-
- @type string: string.
- @param string: search pattern.
-
- @return: list of users/borrowers.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- recid = db.get_id_bibrec(barcode)
- infos = []
-
- if key and not string:
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_place_new_loan_step1(result=None,
- key=key,
- string=string,
- barcode=barcode,
- recid=recid,
- infos=infos,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- return page(title=_("New loan"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- result = search_user(key, string)
- borrowers_list = []
-
- if len(result) == 0 and key:
- if CFG_CERN_SITE:
- infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
- else:
- new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/add_new_borrower_step1',
- {'ln': ln}, _("Register new borrower."))
- message = _("0 borrowers found.") + ' ' + new_borrower_link
- infos.append(message)
- else:
- for user in result:
- borrower_data = db.get_borrower_data_by_id(user[0])
- borrowers_list.append(borrower_data)
-
- body = bc_templates.tmpl_place_new_loan_step1(result=borrowers_list,
- key=key,
- string=string,
- barcode=barcode,
- recid=recid,
- infos=infos,
- ln=ln)
-
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("New loan"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def place_new_loan_step2(req, barcode, recid, user_info, ln=CFG_SITE_LANG):
- """
- Place a new loan from the item's page, step2.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type user_info: list.
- @param user_info: information of the user/borrower who was selected.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_place_new_loan_step2(barcode=barcode,
- recid=recid,
- user_info=user_info,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("New loan"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def place_new_loan_step3(req, barcode, recid, ccid, name, email, phone,
- address, mailbox, due_date, notes, ln=CFG_SITE_LANG):
- """
- Place a new loan from the item's page, step3.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type name: string.
- @type email: string.
- @type phone: string.
- @type address: string.
- @type mailbos: string.
- @type due_date: string.
- @type notes: string.
-
- @return: new loan.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if notes:
- notes_format = '[' + time.ctime() + '] ' + notes + '\n'
- else:
- notes_format = ''
-
- #loaned_on = datetime.date.today()
-
- borrower_id = db.get_borrower_id_by_email(email)
- borrower_info = db.get_borrower_data(borrower_id)
-
- if db.is_on_loan(barcode):
- infos.append(_("Item with barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is already on loan.") % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
-
- copies = db.get_item_copies_details(recid)
- requests = db.get_item_requests(recid)
- loans = db.get_item_loans(recid)
- purchases = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_NEW, recid)
-
- req_hist_overview = db.get_item_requests_historical_overview(recid)
- loans_hist_overview = db.get_item_loans_historical_overview(recid)
- purchases_hist_overview = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, recid)
-
- title = _("Item details")
- body = bc_templates.tmpl_get_item_details(
- recid=recid, copies=copies,
- requests=requests, loans=loans,
- purchases=purchases,
- req_hist_overview=req_hist_overview,
- loans_hist_overview=loans_hist_overview,
- purchases_hist_overview=purchases_hist_overview,
- infos=infos, ln=ln)
-
- elif borrower_id != 0:
- db.new_loan(borrower_id, recid, barcode,
- due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- 'normal', notes_format)
-
- tag_all_requests_as_done(barcode, borrower_id)
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
- update_requests_statuses(barcode)
-
- title = _("New loan")
- body = bc_templates.tmpl_register_new_loan(borrower_info=borrower_info,
- infos=infos,
- recid=recid, ln=ln)
-
- else:
- db.new_borrower(ccid, name, email, phone, address, mailbox, '')
- borrower_id = db.get_borrower_id_by_email(email)
-
- db.new_loan(borrower_id, recid, barcode,
- due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- 'normal', notes_format)
- tag_all_requests_as_done(barcode, borrower_id)
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
- update_requests_statuses(barcode)
- title = _("New loan")
- body = bc_templates.tmpl_register_new_loan(borrower_info=borrower_info,
- infos=infos,
- recid=recid,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def create_new_request_step1(req, borrower_id, p="", f="", search=None,
- ln=CFG_SITE_LANG):
- """
- Create a new request from the borrower's page, step1.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- p: search pattern.
-
- f: field
-
- search: search an item.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if borrower_id != None:
- borrower = db.get_borrower_details(borrower_id)
- else:
- message = _('Empty borrower ID.')
- return borrower_search(req, message, False, ln)
-
- if search and p == '':
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- result = ''
-
- elif search and f == 'barcode':
- p = p.strip('\'" \t')
- has_recid = db.get_id_bibrec(p)
-
- if has_recid is None:
- infos.append(_('The barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s does not exist on BibCirculation database.') % {'x_barcode': p, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- result = ''
- else:
- result = has_recid
-
- elif search:
- result = perform_request_search(cc="Books", sc="1", p=p, f=f)
-
- else:
- result = ''
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if type(result) is types.IntType or type(result) is types.LongType:
- recid = result
- holdings_information = db.get_holdings_information(recid)
- user_info = db.get_borrower_details(borrower_id)
- body = bc_templates.tmpl_create_new_request_step2(user_info=user_info,
- holdings_information=holdings_information,
- recid=recid, ln=ln)
-
- else:
- body = bc_templates.tmpl_create_new_request_step1(borrower=borrower,
- infos=infos,
- result=result,
- p=p,
- f=f,
- ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def create_new_request_step2(req, recid, borrower_id, ln=CFG_SITE_LANG):
- """
- Create a new request from the borrower's page, step2.
-
- recid: identify the record. It is also the primary key of
- the table bibrec.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- holdings_information = db.get_holdings_information(recid)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- user_info = db.get_borrower_details(borrower_id)
-
- body = bc_templates.tmpl_create_new_request_step2(user_info=user_info,
- holdings_information=holdings_information,
- recid=recid, ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def create_new_request_step3(req, borrower_id, barcode, recid,
- ln=CFG_SITE_LANG):
- """
- Create a new request from the borrower's page, step3.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- recid: identify the record. It is also the primary key of
- the table bibrec.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- item_info = db.get_item_info(barcode)
-
- if item_info[6] == 'Reference':
- body = bc_templates.tmpl_book_not_for_loan(ln=ln)
- else:
- body = bc_templates.tmpl_create_new_request_step3(
- borrower_id=borrower_id,
- barcode=barcode,
- recid=recid,
- ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body,
- metaheaderadd = "" % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def create_new_request_step4(req, period_from, period_to, barcode,
- borrower_id, recid, ln=CFG_SITE_LANG):
- """
- Create a new request from the borrower's page, step4.
-
- period_from: begining of the period of interest.
-
- period_to: end of the period of interest.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- recid: identify the record. It is also the primary key of
- the table bibrec.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- db.new_hold_request(borrower_id, recid, barcode,
- period_from, period_to,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
-
- update_requests_statuses(barcode)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_create_new_request_step4(ln=ln)
-
- return page(title=_("New request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def create_new_loan_step1(req, borrower_id, ln=CFG_SITE_LANG):
- """
- Create a new loan from the borrower's page, step1.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- borrower = db.get_borrower_details(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_create_new_loan_step1(borrower=borrower,
- infos=infos,
- ln=ln)
-
- return page(title=_("New loan"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def create_new_loan_step2(req, borrower_id, barcode, notes, ln=CFG_SITE_LANG):
- """
- Create a new loan from the borrower's page, step2.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- notes: notes about the new loan.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
- #borrower_info = db.get_borrower_data(borrower_id)
-
- has_recid = db.get_id_bibrec(barcode)
- loan_id = db.is_item_on_loan(barcode)
-
- if notes:
- notes_format = '[' + time.ctime() + '] ' + notes + '\n'
- else:
- notes_format = ''
-
- infos = []
-
- if has_recid is None:
- infos.append(_('%(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s Unknown barcode.') % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''} + ' ' + _('Please, try again.'))
- borrower = db.get_borrower_details(borrower_id)
- title = _("New loan")
- body = bc_templates.tmpl_create_new_loan_step1(borrower=borrower,
- infos=infos,
- ln=ln)
-
- elif loan_id:
- infos.append(_('The item with the barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s is on loan.') % {'x_barcode': barcode, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- borrower = db.get_borrower_details(borrower_id)
- title = _("New loan")
- body = bc_templates.tmpl_create_new_loan_step1(borrower=borrower,
- infos=infos,
- ln=ln)
-
- else:
- #loaned_on = datetime.date.today()
- due_date = renew_loan_for_X_days(barcode)
- db.new_loan(borrower_id, has_recid, barcode,
- due_date, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- 'normal', notes_format)
- tag_all_requests_as_done(barcode, borrower_id)
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, barcode)
- update_requests_statuses(barcode)
- result = db.get_all_loans(20)
- title = _("Current loans")
- infos.append(_('A new loan has been registered with success.'))
- body = bc_templates.tmpl_all_loans(result=result, infos=infos, ln=ln)
-
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def all_requests(req, request_id, ln=CFG_SITE_LANG):
- """
- Display all requests.
-
- @type request_id: integer.
- @param request_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if request_id:
- db.update_loan_request_status(CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED,
- request_id)
- result = db.get_all_requests()
- else:
- result = db.get_all_requests()
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_all_requests(result=result, ln=ln)
-
- return page(title=_("List of hold requests"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def all_loans(req, msg=None, ln=CFG_SITE_LANG):
- """
- Display all loans.
-
- @type loans_per_page: integer.
- @param loans_per_page: number of loans per page.
-
- @type jloan: integer.
- @param jloan: jump to next loan.
-
- @return: list with all loans (current loans).
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if msg == 'ok':
- infos.append(_('A new loan has been registered with success.'))
-
- result = db.get_all_loans(20)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_all_loans(result=result, infos=infos, ln=ln)
-
- return page(title=_("Current loans"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def all_expired_loans(req, ln=CFG_SITE_LANG):
- """
- Display all loans.
-
- @type loans_per_page: integer.
- @param loans_per_page: number of loans per page.
-
- @return: list with all expired loans (overdue loans).
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- result = db.get_all_expired_loans()
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_all_expired_loans(result=result,
- infos=infos,
- ln=ln)
-
- return page(title=_('Overdue loans'),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_pending_requests(req, request_id, print_data, ln=CFG_SITE_LANG):
- """
- Retrun all loan requests that are pending. If request_id is not None,
- cancel the request and then, return all loan requests that are pending.
-
- @type request_id: integer.
- @param request_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
-
- @type print_data: string.
- @param print_data: print requests information.
-
- @return: list of pending requests (on shelf with hold).
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if print_data == 'true':
- return print_pending_hold_requests_information(req, ln)
-
- elif request_id:
- # Cancel a request too.
- db.update_loan_request_status(CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED,
- request_id)
- barcode = db.get_request_barcode(request_id)
- update_requests_statuses(barcode)
- result = db.get_loan_request_by_status(CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
-
- else:
- result = db.get_loan_request_by_status(CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_pending_requests(result=result, ln=ln)
-
- return page(title=_("Items on shelf with holds"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_waiting_requests(req, request_id, print_data, ln=CFG_SITE_LANG):
- """
- Get all loans requests that are waiting.
-
- @type request_id: integer.
- @param request_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
-
- @type print_data: string.
- @param print_data: print requests information.
-
- @return: list of waiting requests (on loan with hold).
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if print_data == 'true':
- return print_pending_hold_requests_information(req, ln)
-
- elif request_id:
- db.update_loan_request_status(CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED,
- request_id)
-
- result = db.get_loan_request_by_status(CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
- aux = ()
-
- for request in result:
- if db.get_nb_copies_on_loan(request[1]):
- aux += request,
-
- result = aux
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_waiting_requests(result=result, ln=ln)
-
- return page(title=_("Items on loan with holds"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_expired_loans_with_waiting_requests(req, request_id, ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if request_id:
- db.update_loan_request_status(CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED,
- request_id)
- result = db.get_expired_loans_with_waiting_requests()
-
- else:
- result = db.get_expired_loans_with_waiting_requests()
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_get_expired_loans_with_waiting_requests(result=result,
- ln=ln)
-
- return page(title=_("Overdue loans with holds"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def get_loans_notes(req, loan_id, delete_key,
- library_notes, back, ln=CFG_SITE_LANG):
- """
- Get loan's note(s).
-
- @type loan_id: integer.
- @param loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
-
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if delete_key and loan_id:
- if looks_like_dictionary(db.get_loan_notes(loan_id)):
- loans_notes = eval(db.get_loan_notes(loan_id))
- if delete_key in loans_notes.keys():
- del loans_notes[delete_key]
- db.update_loan_notes(loan_id, loans_notes)
-
- elif library_notes:
- if db.get_loan_notes(loan_id):
- if looks_like_dictionary(db.get_loan_notes(loan_id)):
- loans_notes = eval(db.get_loan_notes(loan_id))
- else:
- loans_notes = {}
- else:
- loans_notes = {}
-
- note_time = time.strftime("%Y-%m-%d %H:%M:%S")
- if note_time not in loans_notes.keys():
- loans_notes[note_time] = str(library_notes)
- db.update_loan_notes(loan_id, loans_notes)
-
- loans_notes = db.get_loan_notes(loan_id)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- referer = req.headers_in.get('referer')
-
- body = bc_templates.tmpl_get_loans_notes(loans_notes=loans_notes,
- loan_id=loan_id,
- referer=referer, back=back,
- ln=ln)
- return page(title=_("Loan notes"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_item_loans_notes(req, loan_id, add_notes, new_note, ln=CFG_SITE_LANG):
- """
- Get loan's notes.
-
- @param loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
-
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @param add_notes: display the textarea where will be written a new notes.
-
- @param new_notes: note that will be added to the others library's notes.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if new_note:
- date = '[' + time.ctime() + '] '
- new_line = '\n'
- new_note = date + new_note + new_line
- db.add_new_loan_note(new_note, loan_id)
-
- loans_notes = db.get_loan_notes(loan_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_loans_notes(loans_notes=loans_notes,
- loan_id=loan_id,
- add_notes=add_notes,
- ln=ln)
- return page(title=_("Loan notes"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-
-
-###
-### Items and their copies' related .
-###
-
-
-
-def get_item_details(req, recid, ln=CFG_SITE_LANG):
- """
- Display the details of an item.
-
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @return: item details.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- id_user = 1
- infos = []
-
- if recid == None:
- infos.append(_("Record id not valid"))
-
- copies = db.get_item_copies_details(recid)
- requests = db.get_item_requests(recid)
- loans = db.get_item_loans(recid)
- purchases = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_NEW, recid)
-
- req_hist_overview = db.get_item_requests_historical_overview(recid)
- loans_hist_overview = db.get_item_loans_historical_overview(recid)
- purchases_hist_overview = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, recid)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_item_details(recid=recid,
- copies=copies,
- requests=requests,
- loans=loans,
- purchases=purchases,
- req_hist_overview=req_hist_overview,
- loans_hist_overview=loans_hist_overview,
- purchases_hist_overview=purchases_hist_overview,
- infos=infos,
- ln=ln)
-
- return page(title=_("Item details"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_item_requests_details(req, recid, request_id, ln=CFG_SITE_LANG):
- """
- Display all requests for a specific item.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type request_id: integer.
- @param request_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
-
- @return: Item requests details.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if request_id:
- db.cancel_request(request_id)
- update_request_data(request_id)
-
- result = db.get_item_requests(recid)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_item_requests_details(result=result,
- ln=ln)
-
- return page(title=_("Hold requests") + \
- " - %s" % (book_title_from_MARC(recid)),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_item_loans_details(req, recid, barcode, loan_id, force,
- ln=CFG_SITE_LANG):
- """
- Show all the details about all current loans related with a record.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type loan_id: integer.
- @param loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
-
- @type force: string.
- @param force: force the renew of a loan, when usually this is not possible.
-
- @return: item loans details.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if loan_id and barcode and force == 'true':
- new_due_date = renew_loan_for_X_days(barcode)
- #db.update_due_date(loan_id, new_due_date)
- db.renew_loan(loan_id, new_due_date)
- update_status_if_expired(loan_id)
- infos.append(_("Loan renewed with success."))
-
- elif barcode:
- recid = db.get_id_bibrec(barcode)
- item_description = db.get_item_description(barcode)
- queue = db.get_queue_request(recid, item_description)
- new_due_date = renew_loan_for_X_days(barcode)
-
-
- force_renew_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/get_item_loans_details',
- {'barcode': barcode, 'loan_id': loan_id, 'force': 'true',
- 'recid': recid, 'ln': ln}, (_("Yes")))
-
- no_renew_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/get_item_loans_details',
- {'recid': recid, 'ln': ln},
- (_("No")))
-
- if len(queue) != 0:
- title = book_title_from_MARC(recid)
- message = _("Another user is waiting for this book %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s.") % {'x_title': title, 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
- message += '\n\n'
- message += _("Do you want renew this loan anyway?")
- message += '\n\n'
- message += "[%s] [%s]" % (force_renew_link, no_renew_link)
- infos.append(message)
- else:
- db.renew_loan(loan_id, new_due_date)
- #db.update_due_date(loan_id, new_due_date)
- update_status_if_expired(loan_id)
- infos.append(_("Loan renewed with success."))
-
- result = db.get_item_loans(recid)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_item_loans_details(result=result,
- recid=recid,
- infos=infos,
- ln=ln)
-
- return page(title=_("Loans details") + \
- " - %s" % (book_title_from_MARC(int(recid))),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_item_req_historical_overview(req, recid, ln=CFG_SITE_LANG):
- """
- Display the requests historical overview of an item.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @return: Item requests - historical overview.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- req_hist_overview = db.get_item_requests_historical_overview(recid)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_item_req_historical_overview(
- req_hist_overview=req_hist_overview,
- ln=ln)
-
- return page(title=_("Requests") + " - " + _("historical overview"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_item_loans_historical_overview(req, recid, ln=CFG_SITE_LANG):
- """
- Display the loans historical overview of an item.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @return: Item loans - historical overview.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- loans_hist_overview = db.get_item_loans_historical_overview(recid)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_get_item_loans_historical_overview(
- loans_hist_overview=loans_hist_overview,
- ln=ln)
-
- return page(title=_("Loans") + " - " + _("historical overview"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def add_new_copy_step1(req, ln=CFG_SITE_LANG):
- """
- Add a new copy.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_add_new_copy_step1(ln)
-
- return page(title=_("Add new copy") + " - I",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_copy_step2(req, p, f, ln=CFG_SITE_LANG):
- """
- Add a new copy.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- result = perform_request_search(cc="Books", sc="1", p=p, f=f)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_add_new_copy_step2(result=result, ln=ln)
-
- return page(title=_("Add new copy") + " - II",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_copy_step3(req, recid, barcode, ln=CFG_SITE_LANG):
- """
- Add a new copy.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
- result = db.get_item_copies_details(recid)
- libraries = db.get_internal_libraries()
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if barcode is not None:
- if not db.barcode_in_use(barcode):
- barcode = None
-
- tmp_barcode = generate_tmp_barcode()
-
- body = bc_templates.tmpl_add_new_copy_step3(recid=recid,
- result=result,
- libraries=libraries,
- original_copy_barcode=barcode,
- tmp_barcode=tmp_barcode,
- infos=infos,
- ln=ln)
-
- return page(title=_("Add new copy") + " - III",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_copy_step4(req, barcode, library, location, collection, description,
- loan_period, status, expected_arrival_date, recid,
- ln=CFG_SITE_LANG):
-
- """
- Add a new copy.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- infos = []
-
- result = db.get_item_copies_details(recid)
- libraries = db.get_internal_libraries()
-
- if db.barcode_in_use(barcode):
- infos.append(_("The given barcode %(x_name)s is already in use.", x_name=barcode))
- title = _("Add new copy") + " - III"
- body = bc_templates.tmpl_add_new_copy_step3(recid=recid,
- result=result,
- libraries=libraries,
- original_copy_barcode=None,
- tmp_barcode=None,
- infos=infos,
- ln=ln)
- elif not barcode:
- infos.append(_("The given barcode is empty."))
- title = _("Add new copy") + " - III"
- body = bc_templates.tmpl_add_new_copy_step3(recid=recid,
- result=result,
- libraries=libraries,
- original_copy_barcode=None,
- tmp_barcode=None,
- infos=infos,
- ln=ln)
- elif barcode[:3] == 'tmp' \
- and status in [CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF,
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS]:
- infos.append(_("The status selected does not accept tamporary barcodes."))
- title = _("Add new copy") + " - III"
- tmp_barcode = generate_tmp_barcode()
- body = bc_templates.tmpl_add_new_copy_step3(recid=recid,
- result=result,
- libraries=libraries,
- original_copy_barcode=None,
- tmp_barcode=tmp_barcode,
- infos=infos,
- ln=ln)
-
-
- else:
- library_name = db.get_library_name(library)
- tup_infos = (barcode, library, library_name, location, collection,
- description, loan_period, status, expected_arrival_date,
- recid)
- title = _("Add new copy") + " - IV"
- body = bc_templates.tmpl_add_new_copy_step4(tup_infos=tup_infos, ln=ln)
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body,
- metaheaderadd='' % CFG_SITE_SECURE_URL,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_copy_step5(req, barcode, library, location, collection, description,
- loan_period, status, expected_arrival_date, recid,
- ln=CFG_SITE_LANG):
- """
- Add a new copy.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
- if not db.barcode_in_use(barcode):
- db.add_new_copy(barcode, recid, library, collection, location, description.strip() or '-',
- loan_period, status, expected_arrival_date)
- update_requests_statuses(barcode)
- else:
- infos.append(_("The given barcode %(x_name)s is already in use.", x_name=barcode))
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_add_new_copy_step5(infos=infos, recid=recid, ln=ln)
-
- return page(title=_("Add new copy") + " - V",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def delete_copy_step1(req, barcode, ln):
- #id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- barcode = barcode.strip('\'" \t')
- recid = db.get_id_bibrec(barcode)
- if recid:
- #recid = recid[0]
-
- infos.append(_("Do you really want to delete this copy of the book?"))
-
- copies = db.get_item_copies_details(recid)
-
- title = _("Delete copy")
- body = bc_templates.tmpl_delete_copy_step1(barcode_to_delete=barcode,
- recid=recid,
- result=copies,
- infos=infos,
- ln=ln)
-
- else:
- message = _("""The barcode %(x_name)s was not found""", x_name=(barcode))
- infos.append(message)
- title = _("Item search")
- body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
-
- return page(title=title,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def delete_copy_step2(req, barcode, ln):
-
- #id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- barcode = barcode.strip('\'" \t')
- recid = db.get_id_bibrec(barcode)
-
- if recid:
- #recid = recid[0]
-
- if db.delete_copy(barcode)==1:
- message = _("The copy with barcode %(x_name)s has been deleted.", x_name=barcode)
- else:
- message = _('It was NOT possible to delete the copy with barcode %(x_name)s', x_name=barcode)
-
- infos.append(message)
-
- copies = db.get_item_copies_details(recid)
- requests = db.get_item_requests(recid)
- loans = db.get_item_loans(recid)
- purchases = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_NEW, recid)
-
- req_hist_overview = db.get_item_requests_historical_overview(recid)
- loans_hist_overview = db.get_item_loans_historical_overview(recid)
- purchases_hist_overview = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, recid)
-
- title = _("Item details")
- body = bc_templates.tmpl_get_item_details(
- recid=recid, copies=copies,
- requests=requests, loans=loans,
- purchases=purchases,
- req_hist_overview=req_hist_overview,
- loans_hist_overview=loans_hist_overview,
- purchases_hist_overview=purchases_hist_overview,
- infos=infos, ln=ln)
-
- else:
- message = _("The barcode %(x_name)s was not found", x_name=barcode)
- infos.append(message)
- title = _("Item search")
- body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
- return page(title=title,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def update_item_info_step1(req, ln=CFG_SITE_LANG):
- """
- Update the item's information.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_update_item_info_step1(ln=ln)
-
- return page(title=_("Update item information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_item_info_step2(req, p, f, ln=CFG_SITE_LANG):
- """
- Update the item's information.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- result = perform_request_search(cc="Books", sc="1", p=p, f=f)
-
- body = bc_templates.tmpl_update_item_info_step2(result=result, ln=ln)
-
- return page(title="Update item information",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_item_info_step3(req, recid, ln=CFG_SITE_LANG):
- """
- Update the item's information.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- result = db.get_item_copies_details(recid)
-
- body = bc_templates.tmpl_update_item_info_step3(recid=recid, result=result,
- ln=ln)
-
- return page(title=_("Update item information"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_item_info_step4(req, barcode, ln=CFG_SITE_LANG):
- """
- Update the item's information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- recid = db.get_id_bibrec(barcode)
- result = db.get_item_info(barcode)
- libraries = db.get_internal_libraries()
- libraries += db.get_hidden_libraries()
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if recid == None:
- _ = gettext_set_language(ln)
- infos = []
- infos.append(_("Barcode %(x_name)s not found", x_name=barcode))
- return item_search(req, infos, ln)
-
-
- body = bc_templates.tmpl_update_item_info_step4(recid=recid,
- result=result,
- libraries=libraries,
- ln=ln)
-
- return page(title=_("Update item information"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_item_info_step5(req, barcode, old_barcode, library, location,
- collection, description, loan_period, status,
- expected_arrival_date, recid, ln=CFG_SITE_LANG):
-
- """
- Update the item's information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- library_name = db.get_library_name(library)
- tup_infos = (barcode, old_barcode, library, library_name, location,
- collection, description, loan_period, status,
- expected_arrival_date, recid)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_update_item_info_step5(tup_infos=tup_infos, ln=ln)
-
- return page(title=_("Update item information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_item_info_step6(req, tup_infos, ln=CFG_SITE_LANG):
- """
- Update the item's information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- # tuple containing information for the update process.
- (barcode, old_barcode, library_id, location, collection,
- description, loan_period, status, expected_arrival_date, recid) = tup_infos
-
- is_on_loan = db.is_on_loan(old_barcode)
- #is_requested = db.is_requested(old_barcode)
-
- # if item on loan and new status is CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF,
- # item has to be returned.
- if is_on_loan and status == CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF:
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, old_barcode)
- db.return_loan(old_barcode)
-
- if not is_on_loan and status == CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN:
- status = db.get_copy_details(barcode)[7]
- infos.append(_("Item [%(x_name)s] updated, but the status was not modified.",x_name=old_barcode))
-
- # update item information.
- db.update_item_info(old_barcode, library_id, collection, location, description.strip(),
- loan_period, status, expected_arrival_date)
- update_requests_statuses(old_barcode)
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if barcode != old_barcode:
- if db.barcode_in_use(barcode):
- infos.append(_("Item [%(x_name)s] updated, but the barcode was not modified because it is already in use.", x_name=old_barcode))
- else:
- if db.update_barcode(old_barcode, barcode):
- infos.append(_("Item [%(x_name)s] updated to [%(x_new)s] with success.",
- x_name=old_barcode, x_new=barcode))
- else:
- infos.append(_("Item [%(x_name)s] updated, but the barcode was not modified because it was not found (!?).", x_name=old_barcode))
-
- copies = db.get_item_copies_details(recid)
- requests = db.get_item_requests(recid)
- loans = db.get_item_loans(recid)
- purchases = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_NEW, recid)
-
- req_hist_overview = db.get_item_requests_historical_overview(recid)
- loans_hist_overview = db.get_item_loans_historical_overview(recid)
- purchases_hist_overview = db.get_item_purchases(CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, recid)
-
- body = bc_templates.tmpl_get_item_details(recid=recid,
- copies=copies,
- requests=requests,
- loans=loans,
- purchases=purchases,
- req_hist_overview=req_hist_overview,
- loans_hist_overview=loans_hist_overview,
- purchases_hist_overview=purchases_hist_overview,
- infos=infos,
- ln=ln)
-
- return page(title=_("Update item information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- else:
- return redirect_to_url(req, CFG_SITE_SECURE_URL +
- "/record/edit/#state=edit&recid=" + str(recid))
-
-def item_search(req, infos=[], ln=CFG_SITE_LANG):
- """
- Display a form where is possible to searh for an item.
- """
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- _ = gettext_set_language(ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
-
- return page(title=_("Item search"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def item_search_result(req, p, f, ln=CFG_SITE_LANG):
- """
- Search an item and return a list with all the possible results. To retrieve
- the information desired, we use the method 'perform_request_search' (from
- search_engine.py). In the case of BibCirculation, we are just looking for
- books (items) inside the collection 'Books'.
-
- @type p: string
- @param p: search pattern
-
- @type f: string
- @param f: search field
-
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if p == '':
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- return item_search(req, infos, ln)
-
- if f == 'barcode':
- p = p.strip('\'" \t')
- recid = db.get_id_bibrec(p)
-
- if recid is None:
- infos.append(_('The barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s does not exist on BibCirculation database.') % {'x_barcode': p, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
- else:
- return get_item_details(req, recid, ln=ln)
-
- elif f == 'recid':
- p = p.strip('\'" \t')
- recid = p
-
- if not record_exists(recid):
- infos.append(_("Requested record does not seem to exist."))
- body = bc_templates.tmpl_item_search(infos=infos, ln=ln)
- else:
- return get_item_details(req, recid, ln=ln)
-
- else:
- result = perform_request_search(cc="Books", sc="1", p=p, f=f)
- body = bc_templates.tmpl_item_search_result(result=result, ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return page(title=_("Item search result"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-
-
-###
-### "Borrower" related templates
-###
-
-
-
-def get_borrower_details(req, borrower_id, update, ln=CFG_SITE_LANG):
- """
- Display the details of a borrower.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if update and CFG_CERN_SITE:
- update_user_info_from_ldap(borrower_id)
-
- borrower = db.get_borrower_details(borrower_id)
- if borrower == None:
- info = _('Borrower not found.') + ' ' + _('Please, try again.')
- return borrower_search(req, info, False, ln)
-
- else:
- requests = db.get_borrower_request_details(borrower_id)
- loans = db.get_borrower_loan_details(borrower_id)
- notes = db.get_borrower_notes(borrower_id)
- ill = db.get_ill_requests_details(borrower_id)
- proposals = db.get_proposal_requests_details(borrower_id)
-
- req_hist = db.bor_requests_historical_overview(borrower_id)
- loans_hist = db.bor_loans_historical_overview(borrower_id)
- ill_hist = db.bor_ill_historical_overview(borrower_id)
- proposal_hist = db.bor_proposal_historical_overview(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_borrower_details(borrower=borrower,
- requests=requests,
- loans=loans,
- notes=notes,
- ill=ill,
- proposals=proposals,
- req_hist=req_hist,
- loans_hist=loans_hist,
- ill_hist=ill_hist,
- proposal_hist=proposal_hist,
- ln=ln)
-
- return page(title=_("Borrower details"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_borrower_step1(req, ln=CFG_SITE_LANG):
- """
- Add new borrower. Step 1
- """
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_add_new_borrower_step1(ln=ln)
-
- return page(title=_("Add new borrower") + " - I",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_borrower_step2(req, name, email, phone, address, mailbox,
- notes, ln=CFG_SITE_LANG):
- """
- Add new borrower. Step 2.
-
- @type name: string.
- @type email: string.
- @type phone: string.
- @type address: string.
- @type mailbox: string.
- @type notes: string.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if name == '':
- infos.append(_("Please, insert a name"))
-
- if email == '':
- infos.append(_("Please, insert a valid email address"))
- else:
- borrower_id = db.get_borrower_id_by_email(email)
- if borrower_id is not None:
- infos.append(_("There is already a borrower using the following email:")
- + " %s" % (email))
-
- tup_infos = (name, email, phone, address, mailbox, notes)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if len(infos) > 0:
- body = bc_templates.tmpl_add_new_borrower_step1(tup_infos=tup_infos,
- infos=infos, ln=ln)
- title = _("Add new borrower") + " - I"
- else:
- if notes != '':
- borrower_notes = {}
- note_time = time.strftime("%Y-%m-%d %H:%M:%S")
- borrower_notes[note_time] = notes
- else:
- borrower_notes = ''
-
- borrower_id = db.new_borrower(None, name, email, phone,
- address, mailbox, borrower_notes)
-
- return redirect_to_url(req,
- '%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s' \
- % (CFG_SITE_SECURE_URL, ln, borrower_id))
-
-
- #body = bc_templates.tmpl_add_new_borrower_step2(tup_infos=tup_infos,
- # infos=infos, ln=ln)
- #title = _("Add new borrower") + " - II"
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_borrower_step3(req, tup_infos, ln=CFG_SITE_LANG):
- """
- Add new borrower. Step 3.
-
- @type tup_infos: tuple.
- @param tup_infos: tuple containing borrower information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if tup_infos[5] != '':
- borrower_notes = {}
- note_time = time.strftime("%Y-%m-%d %H:%M:%S")
- borrower_notes[note_time] = str(tup_infos[5])
- else:
- borrower_notes = ''
-
- db.new_borrower(None, tup_infos[0], tup_infos[1], tup_infos[2],
- tup_infos[3], tup_infos[4], str(borrower_notes))
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_add_new_borrower_step3(ln=ln)
-
- return page(title=_("Add new borrower") + " - III",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_borrower_info_step1(req, borrower_id, ln=CFG_SITE_LANG):
- """
- Update the borrower's information.
-
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- borrower_details = db.get_borrower_details(borrower_id)
-
- tup_infos = (borrower_details[0], borrower_details[2], borrower_details[3],
- borrower_details[4], borrower_details[5], borrower_details[6])
-
- body = bc_templates.tmpl_update_borrower_info_step1(tup_infos=tup_infos,
- ln=ln)
-
- return page(title=_("Update borrower information"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_borrower_info_step2(req, borrower_id, name, email, phone, address,
- mailbox, ln=CFG_SITE_LANG):
- """
- Update the borrower's information.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if name == '':
- infos.append(_("Please, insert a name"))
-
- if email == '':
- infos.append(_("Please, insert a valid email address"))
- else:
- borrower_email_id = db.get_borrower_id_by_email(email)
- if borrower_email_id is not None and borrower_id != borrower_email_id:
- infos.append(_("There is already a borrower using the following email:")
- + " %s" % (email))
-
- tup_infos = (borrower_id, name, email, phone, address, mailbox)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if len(infos) > 0:
- body = bc_templates.tmpl_update_borrower_info_step1(tup_infos=tup_infos,
- infos=infos, ln=ln)
- else:
- db.update_borrower_info(borrower_id, name, email,
- phone, address, mailbox)
-
- return redirect_to_url(req,
- '%s/admin2/bibcirculation/get_borrower_details?ln=%s&borrower_id=%s' \
- % (CFG_SITE_SECURE_URL, ln, borrower_id))
-
- return page(title=_("Update borrower information"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def get_borrower_requests_details(req, borrower_id, request_id,
- ln=CFG_SITE_LANG):
- """
- Display loans details of a borrower.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @type request_id: integer.
- @param request_id: identify the hold request to be cancelled
-
- @return: borrower requests details.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if request_id:
- db.cancel_request(request_id)
- update_request_data(request_id)
-
- result = db.get_borrower_request_details(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- name = db.get_borrower_name(borrower_id)
-
- title = _("Hold requests details") + " - %s" % (name)
- body = bc_templates.tmpl_borrower_request_details(result=result,
- borrower_id=borrower_id,
- ln=ln)
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_borrower_loans_details(req, recid, barcode, borrower_id,
- renewal, force, loan_id, ln=CFG_SITE_LANG):
- """
- Show borrower's loans details.
-
- @type recid: integer.
- @param recid: identify the record. It is also the primary key of
- the table bibrec.
-
- @type barcode: string.
- @param barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @type renewal: string.
- @param renewal: renew all loans.
-
- @type force: string.
- @param force: force the renew of a loan, when usually this is not possible.
-
- @type loan_id: integer.
- @param loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
-
- @return: borrower loans details.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- force_renew_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/get_borrower_loans_details',
- {'barcode': barcode, 'borrower_id': borrower_id,
- 'loan_id': loan_id, 'force': 'true', 'ln': ln},
- (_("Yes")))
-
- no_renew_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/get_borrower_loans_details',
- {'borrower_id': borrower_id, 'ln': ln},
- (_("No")))
-
- if barcode and loan_id and recid:
- item_description = db.get_item_description(barcode)
- queue = db.get_queue_request(recid, item_description)
- new_due_date = renew_loan_for_X_days(barcode)
-
- if len(queue) != 0:
- title = book_title_from_MARC(recid)
- message = _("Another user is waiting for this book %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s.") % {'x_title': title, 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
- message += '\n\n'
- message += _("Do you want renew this loan anyway?")
- message += '\n\n'
- message += "[%s] [%s]" % (force_renew_link, no_renew_link)
- infos.append(message)
-
- else:
- #db.update_due_date(loan_id, new_due_date)
- db.renew_loan(loan_id, new_due_date)
- #update_status_if_expired(loan_id)
- infos.append(_("Loan renewed with success."))
-
- elif loan_id and barcode and force == 'true':
- new_due_date = renew_loan_for_X_days(barcode)
- db.renew_loan(loan_id, new_due_date)
- update_status_if_expired(loan_id)
- infos.append(_("Loan renewed with success."))
-
- elif borrower_id and renewal=='true':
- list_of_loans = db.get_recid_borrower_loans(borrower_id)
- for (loan_id, recid, barcode) in list_of_loans:
- item_description = db.get_item_description(barcode)
- queue = db.get_queue_request(recid, item_description)
- new_due_date = renew_loan_for_X_days(barcode)
-
- force_renewall_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/get_borrower_loans_details',
- {'barcode': barcode, 'borrower_id': borrower_id,
- 'loan_id': loan_id, 'force': 'true', 'ln': ln},
- (_("Yes")))
-
- if len(queue) != 0:
- title = book_title_from_MARC(recid)
- message = _("Another user is waiting for this book %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s.") % {'x_title': title, 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
- message += '\n\n'
- message += _("Do you want renew this loan anyway?")
- message += '\n\n'
- message += "[%s] [%s]" % (force_renewall_link, no_renew_link)
- infos.append(message)
-
- else:
- db.renew_loan(loan_id, new_due_date)
- update_status_if_expired(loan_id)
-
- if infos == []:
- infos.append(_("All loans renewed with success."))
-
- borrower_loans = db.get_borrower_loan_details(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_borrower_loans_details(
- borrower_loans=borrower_loans,
- borrower_id=borrower_id,
- infos=infos, ln=ln)
-
- return page(title=_("Loans details") + \
- " - %s" %(db.get_borrower_name(borrower_id)),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def bor_loans_historical_overview(req, borrower_id, ln=CFG_SITE_LANG):
- """
- Display the loans historical overview of a borrower.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @return: borrower loans - historical overview.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- loans_hist_overview = db.bor_loans_historical_overview(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_bor_loans_historical_overview(
- loans_hist_overview = loans_hist_overview,
- ln=ln)
-
- return page(title=_("Loans") + " - " + _("historical overview"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def bor_requests_historical_overview(req, borrower_id, ln=CFG_SITE_LANG):
- """
- Display the requests historical overview of a borrower.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @return: borrower requests - historical overview.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- req_hist_overview = db.bor_requests_historical_overview(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_bor_requests_historical_overview(
- req_hist_overview = req_hist_overview,
- ln=ln)
-
- return page(title=_("Requests") + " - " + _("historical overview"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_borrower_ill_details(req, borrower_id, request_type='', ln=CFG_SITE_LANG):
- """
- Display ILL details of a borrower.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @type ill_id: integer.
- @param ill_id: identify the ILL request. It is also the primary key
- of the table crcILLREQUEST.
-
- @return: borrower ILL details.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if request_type == 'proposal-book':
- result = db.get_proposal_requests_details(borrower_id)
- else:
- result = db.get_ill_requests_details(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- name = db.get_borrower_name(borrower_id)
-
- title = _("ILL details") + "- %s" % (name)
- body = bc_templates.tmpl_borrower_ill_details(result=result,
- borrower_id=borrower_id,
- ln=ln)
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def bor_ill_historical_overview(req, borrower_id, request_type='', ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if request_type == 'proposal-book':
- result = db.bor_proposal_historical_overview(borrower_id)
- else:
- result = db.bor_ill_historical_overview(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- name = db.get_borrower_name(borrower_id)
-
- title = _("ILL historical overview") + " - %s" % (name)
- body = bc_templates.tmpl_borrower_ill_details(result=result,
- borrower_id=borrower_id,
- ln=ln)
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-
-def borrower_notification(req, borrower_id, template, message, load_msg_template,
- subject, send_message, from_address, ln=CFG_SITE_LANG):
- """
- Send an email to a borrower or simply load and display an editable email
- template.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- @type borrower_email: string.
- @param borrower_email: The librarian can change the email manually.
- In that case, this value will be taken instead
- of the that in borrower details.
-
- @type template: string.
- @param template: The name of the notification template to be loaded.
- If the @param load_msg_template holds True, the
- template is not loaded.
-
- @type message: string.
- @param message: Message to be sent if the flag @param send_message is set.
-
- @type subject: string.
- @param subject: Subject of the message.
-
- @type from_address: string.
- @param from_address: From address in the message sent.
-
- @return: Display the email template or send an email to a borrower.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- email = db.get_borrower_email(borrower_id)
-
- if load_msg_template == 'False' and template is not None:
- # Do not load the template. It is the email body itself.
- body = bc_templates.tmpl_borrower_notification(email=email,
- subject=subject,
- email_body=template,
- borrower_id=borrower_id,
- from_address=from_address,
- ln=ln)
-
- elif send_message:
- send_email(fromaddr = from_address,
- toaddr = email,
- subject = subject,
- content = message,
- header = '',
- footer = '',
- attempt_times = 1,
- attempt_sleeptime = 10
- )
- body = bc_templates.tmpl_send_notification(ln=ln)
-
- else:
- show_template = load_template(template)
- body = bc_templates.tmpl_borrower_notification(email=email,
- subject=subject,
- email_body=show_template,
- borrower_id=borrower_id,
- from_address=from_address,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return page(title="User Notification",
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_borrower_notes(req, borrower_id, delete_key, library_notes,
- ln=CFG_SITE_LANG):
- """
- Retrieve the notes of a borrower.
-
- @type borrower_id: integer.
- @param borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if delete_key and borrower_id:
- if looks_like_dictionary(db.get_borrower_notes(borrower_id)):
- borrower_notes = eval(db.get_borrower_notes(borrower_id))
- if delete_key in borrower_notes.keys():
- del borrower_notes[delete_key]
- db.update_borrower_notes(borrower_id, borrower_notes)
-
- elif library_notes:
- if db.get_borrower_notes(borrower_id):
- if looks_like_dictionary(db.get_borrower_notes(borrower_id)):
- borrower_notes = eval(db.get_borrower_notes(borrower_id))
- else:
- borrower_notes = {}
- else:
- borrower_notes = {}
-
- note_time = time.strftime("%Y-%m-%d %H:%M:%S")
- if note_time not in borrower_notes.keys():
- borrower_notes[note_time] = str(library_notes)
- db.update_borrower_notes(borrower_id, borrower_notes)
-
- borrower_notes = db.get_borrower_notes(borrower_id)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_borrower_notes(borrower_notes=borrower_notes,
- borrower_id=borrower_id,
- ln=ln)
-
- return page(title=_("Borrower notes"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def borrower_search(req, empty_barcode, redirect_to_new_request=False,
- ln=CFG_SITE_LANG):
- """
- Page (for administrator) where is it possible to search
- for a borrower (who is on crcBORROWER table) using his/her name,
- email, phone or id.
-
- If redirect_to_new_request is False, the returned page will be "Borrower details"
- If redirect_to_new_request is True, the returned page will be "New Request"
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if empty_barcode:
- infos.append(empty_barcode)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_borrower_search(infos=infos,
- redirect_to_new_request=redirect_to_new_request,
- ln=ln)
-
- if redirect_to_new_request:
- title = _("New Request")
- else:
- title = _("Borrower Search")
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def borrower_search_result(req, column, string, redirect_to_new_request=False,
- ln=CFG_SITE_LANG):
- """
- Search a borrower and return a list with all the possible results.
-
- @type column: string
- @param column: identify the column, of the table crcBORROWER, that will be
- considered during the search. Can be 'name', 'email' or 'id'.
-
- @type string: string
- @param string: string used for the search process.
-
- If redirect_to_new_request is True, the returned page will be "Borrower details"
- If redirect_to_new_request is False, the returned page will be "New Request"
-
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if string == '':
- message = _('Empty string.') + ' ' + _('Please, try again.')
- return borrower_search(req, message, redirect_to_new_request, ln)
- else:
- result = search_user(column, string)
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- if len(result) == 1:
- if redirect_to_new_request:
- return create_new_request_step1(req, result[0][0])
-
- else:
- return get_borrower_details(req, result[0][0], False, ln)
- #return create_new_request_step1(req, borrower_id, p, f, search, ln)
- else:
- body = bc_templates.tmpl_borrower_search_result(result=result,
- redirect_to_new_request=redirect_to_new_request,
- ln=ln)
-
- return page(title=_("Borrower search result"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-
-
-###
-### ILL/Purchase/Acquisition related functions.
-### Naming of the methods is not intuitive. Should be improved
-### and appropriate documentation added, when required.
-### Also, methods could be refactored.
-###
-
-
-
-
-def register_ill_from_proposal(req, ill_request_id, bor_id=None, ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- book_info = db.get_ill_book_info(ill_request_id)
-
- infos = []
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if looks_like_dictionary(book_info):
- book_info = eval(book_info)
- if not bor_id:
- bid = db.get_ill_borrower(ill_request_id)
- else:
- bid = bor_id
-
- if 'recid' in book_info and bid:
- recid = book_info['recid']
- if not db.has_loan_request(bid, recid, ill=1):
- db.tag_requests_as_done(bid, recid=recid)
- library_notes = {}
- library_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = \
- _("This ILL has been created from a proposal.")
- db.register_ill_from_proposal(ill_request_id,
- bid, library_notes)
- infos.append(_('An ILL has been created for the user.'))
- else:
- infos.append(_('An active ILL already exists for this user on this record.'))
- else:
- infos.append(_('Could not create an ILL from the proposal'))
- else:
- infos.append(_('Could not create an ILL from the proposal'))
-
- ill_req = db.get_ill_requests(CFG_BIBCIRCULATION_ILL_STATUS_NEW)
- body = bc_templates.tmpl_list_ill(ill_req, infos=infos, ln=ln)
- return page(title=_("ILL requests"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- #return redirect_to_url(req,
- # '%s/admin2/bibcirculation/list_proposal?status=%s' % \
- # (CFG_SITE_SECURE_URL, CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE))
-
-def register_ill_request_with_no_recid_step1(req, borrower_id,
- ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_register_ill_request_with_no_recid_step1(
- infos=infos,
- borrower_id=borrower_id,
- admin=True, ln=ln)
-
- return page(title=_("Register ILL request"),
- uid=id_user,
- req=req,
- metaheaderadd = "" % CFG_SITE_SECURE_URL,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_ill_request_with_no_recid_step2(req, title, authors, place,
- publisher, year, edition, isbn, budget_code,
- period_of_interest_from, period_of_interest_to,
- additional_comments, only_edition, key, string,
- borrower_id, ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
- book_info = (title, authors, place, publisher, year, edition, isbn)
- request_details = (budget_code, period_of_interest_from,
- period_of_interest_to, additional_comments, only_edition)
-
-
- if borrower_id in (None, '', 'None'):
- body = None
- if not key:
- borrowers_list = None
-
- elif not string:
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- borrowers_list = None
-
- else:
- if validate_date_format(period_of_interest_from) is False:
- infos = []
- infos.append(_("The period of interest %(x_strong_tag_open)sFrom: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_from, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
-
- body = bc_templates.tmpl_register_ill_request_with_no_recid_step1(
- infos=infos,
- borrower_id=None,
- admin=True,
- ln=ln)
-
- elif validate_date_format(period_of_interest_to) is False:
- infos = []
- infos.append(_("The period of interest %(x_strong_tag_open)sTo: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_to, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
-
- body = bc_templates.tmpl_register_ill_request_with_no_recid_step1(
- infos=infos,
- ln=ln)
-
- else:
- result = search_user(key, string)
-
- borrowers_list = []
- if len(result) == 0:
- infos.append(_("0 borrowers found."))
- else:
- for user in result:
- borrower_data = db.get_borrower_data_by_id(user[0])
- borrowers_list.append(borrower_data)
-
- if body == None:
- body = bc_templates.tmpl_register_ill_request_with_no_recid_step2(
- book_info=book_info, request_details=request_details,
- result=borrowers_list, key=key, string=string,
- infos=infos, ln=ln)
-
- else:
- user_info = db.get_borrower_data_by_id(borrower_id)
-
-
- return register_ill_request_with_no_recid_step3(req, title, authors,
- place, publisher,year, edition,
- isbn, user_info, budget_code,
- period_of_interest_from,
- period_of_interest_to,
- additional_comments, only_edition,
- ln)
-
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
-
-
- return page(title=_("Register ILL request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_ill_request_with_no_recid_step3(req, title, authors, place,
- publisher, year, edition, isbn,
- user_info, budget_code,
- period_of_interest_from,
- period_of_interest_to,
- additional_comments,
- only_edition, ln=CFG_SITE_LANG):
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- request_details = (budget_code, period_of_interest_from,
- period_of_interest_to, additional_comments, only_edition)
-
- book_info = (title, authors, place, publisher, year, edition, isbn)
-
- if user_info is None:
- return register_ill_request_with_no_recid_step2(req, title, authors,
- place, publisher, year, edition, isbn, budget_code,
- period_of_interest_from, period_of_interest_to,
- additional_comments, only_edition, 'name', None,
- None, ln)
-
- else:
- body = bc_templates.tmpl_register_ill_request_with_no_recid_step3(
- book_info=book_info,
- user_info=user_info,
- request_details=request_details,
- admin=True,
- ln=ln)
-
- return page(title=_("Register ILL request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_ill_request_with_no_recid_step4(req, book_info, borrower_id,
- request_details, ln):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- _ = gettext_set_language(ln)
-
- (title, authors, place, publisher, year, edition, isbn) = book_info
- #create_ill_record(book_info))
-
- (budget_code, period_of_interest_from,
- period_of_interest_to, library_notes, only_edition) = request_details
-
- ill_request_notes = {}
- if library_notes:
- ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = \
- str(library_notes)
-
-### budget_code ###
- if db.get_borrower_data_by_id(borrower_id) == None:
- _ = gettext_set_language(ln)
- infos = []
- infos.append(_("Request not registered: wrong borrower id"))
- body = bc_templates.tmpl_register_ill_request_with_no_recid_step2(
- book_info=book_info,
- request_details=request_details, result=[],
- key='name', string=None, infos=infos, ln=ln)
-
- return page(title=_("Register ILL request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
- else:
- book_info = {'title': title, 'authors': authors, 'place': place,
- 'publisher': publisher,'year' : year, 'edition': edition,
- 'isbn' : isbn}
- db.ill_register_request_on_desk(borrower_id, book_info,
- period_of_interest_from,
- period_of_interest_to,
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- str(ill_request_notes),
- only_edition, 'book', budget_code)
-
- return list_ill_request(req, CFG_BIBCIRCULATION_ILL_STATUS_NEW, ln)
-
-
-def register_ill_book_request(req, borrower_id, ln=CFG_SITE_LANG):
- """
- Display a form where is possible to searh for an item.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- body = bc_templates.tmpl_register_ill_book_request(infos=infos,
- borrower_id=borrower_id,
- ln=ln)
-
- return page(title=_("Register ILL Book request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_ill_book_request_result(req, borrower_id, p, f, ln=CFG_SITE_LANG):
- """
- Search an item and return a list with all the possible results. To retrieve
- the information desired, we use the method 'perform_request_search' (from
- search_engine.py). In the case of BibCirculation, we are just looking for
- books (items) inside the collection 'Books'.
-
- @type p: string
- @param p: search pattern
-
- @type f: string
- @param f: search field
-
- @return: list of recids
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
- if p == '':
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_register_ill_book_request(infos=infos,
- borrower_id=borrower_id,
- ln=ln)
- else:
- if f == 'barcode':
- p = p.strip('\'" \t')
- recid = db.get_id_bibrec(p)
-
- if recid is None:
- infos.append(_('The barcode %(x_strong_tag_open)s%(x_barcode)s%(x_strong_tag_close)s does not exist on BibCirculation database.') % {'x_barcode': p, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
- body = bc_templates.tmpl_register_ill_book_request(infos=infos,
- borrower_id=borrower_id,
- ln=ln)
- else:
- body = bc_templates.tmpl_register_ill_book_request_result(
- result=[recid],
- borrower_id=borrower_id,
- ln=ln)
- else:
- result = perform_request_search(cc="Books", sc="1", p=p, f=f)
- if len(result) == 0:
- return register_ill_request_with_no_recid_step1(req,
- borrower_id, ln)
- else:
- body = bc_templates.tmpl_register_ill_book_request_result(
- result=result,
- borrower_id=borrower_id,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return page(title=_("Register ILL Book request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_ill_article_request_step1(req, ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- ' > ' \
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_register_ill_article_request_step1(infos=infos,
- ln=ln)
-
- return page(title=_("Register ILL Article request"),
- uid=id_user,
- req=req,
- body=body,
- metaheaderadd = ""%(CFG_SITE_SECURE_URL),
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_ill_article_request_step2(req, periodical_title, article_title,
- author, report_number, volume, issue,
- pages, year, budget_code, issn,
- period_of_interest_from,
- period_of_interest_to,
- additional_comments, key, string,
- ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if key and not string:
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- article_info = (periodical_title, article_title, author, report_number,
- volume, issue, pages, year, issn)
- request_details = (period_of_interest_from, period_of_interest_to,
- budget_code, additional_comments)
-
- body = bc_templates.tmpl_register_ill_article_request_step2(
- article_info=article_info,
- request_details=request_details,
- result=None, key=key,
- string=string, infos=infos,
- ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return page(title=_("Register ILL request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- result = search_user(key, string)
- borrowers_list = []
-
- if len(result) == 0 and key:
- if CFG_CERN_SITE:
- infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
- else:
- new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/add_new_borrower_step1',
- {'ln': ln}, _("Register new borrower."))
- message = _("0 borrowers found.") + ' ' + new_borrower_link
- infos.append(message)
- else:
- for user in result:
- borrower_data = db.get_borrower_data_by_id(user[0])
- borrowers_list.append(borrower_data)
-
- if validate_date_format(period_of_interest_from) is False:
- infos = []
-
- infos.append(_("The period of interest %(x_strong_tag_open)sFrom: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_from, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
-
- body = bc_templates.tmpl_register_ill_article_request_step1(infos=infos,
- ln=ln)
-
- elif validate_date_format(period_of_interest_to) is False:
- infos = []
- infos.append(_("The period of interest %(x_strong_tag_open)sTo: %(x_date)s%(x_strong_tag_close)s is not a valid date or date format") % {'x_date': period_of_interest_to, 'x_strong_tag_open': '', 'x_strong_tag_close': ''})
-
- body = bc_templates.tmpl_register_ill_article_request_step1(infos=infos,
- ln=ln)
-
- else:
- article_info = (periodical_title, article_title, author, report_number,
- volume, issue, pages, year, issn)
-
- request_details = (period_of_interest_from, period_of_interest_to,
- budget_code, additional_comments)
-
- body = bc_templates.tmpl_register_ill_article_request_step2(
- article_info=article_info,
- request_details=request_details,
- result=borrowers_list,
- key=key, string=string,
- infos=infos, ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return invenio.webpage.page(title=_("Register ILL request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_ill_article_request_step3(req, periodical_title, title, authors,
- report_number, volume, issue,
- page_number, year, issn, user_info,
- request_details, ln=CFG_SITE_LANG):
-
- #id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- #info = (title, authors, "", "", year, "", issn)
-
- #create_ill_record(info)
-
- item_info = {'periodical_title': periodical_title, 'title': title,
- 'authors': authors, 'place': "", 'publisher': "",
- 'year' : year, 'edition': "", 'issn' : issn,
- 'volume': volume, 'issue': issue, 'page': page_number }
-
-
- (period_of_interest_from, period_of_interest_to, budget_code,
- library_notes) = request_details
-
- only_edition = ""
-
- if user_info is None:
- return register_ill_article_request_step2(req, periodical_title, title,
- authors, report_number, volume, issue,
- page_number, year, budget_code, issn,
- period_of_interest_from,
- period_of_interest_to,
- library_notes, 'name', None, ln)
- else:
- borrower_id = user_info[0]
-
- ill_request_notes = {}
- if library_notes:
- ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] \
- = str(library_notes)
-
- db.ill_register_request_on_desk(borrower_id, item_info,
- period_of_interest_from,
- period_of_interest_to,
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- str(ill_request_notes),
- only_edition, 'article', budget_code)
-
-
- return list_ill_request(req, CFG_BIBCIRCULATION_ILL_STATUS_NEW, ln)
-
-
-def register_purchase_request_step1(req, request_type, recid, title, authors,
- place, publisher, year, edition, this_edition_only,
- isbn, standard_number,
- budget_code, cash, period_of_interest_from,
- period_of_interest_to, additional_comments,
- ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
- if recid:
- fields = (request_type, recid, budget_code, cash,
- period_of_interest_from, period_of_interest_to,
- additional_comments)
- else:
- fields = (request_type, title, authors, place, publisher, year, edition,
- this_edition_only, isbn, standard_number, budget_code,
- cash, period_of_interest_from, period_of_interest_to,
- additional_comments)
-
- body = bc_templates.tmpl_register_purchase_request_step1(infos=infos,
- fields=fields, admin=True, ln=ln)
-
- return page(title=_("Register purchase request"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- metaheaderadd='' % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_purchase_request_step2(req, request_type, recid, title, authors,
- place, publisher, year, edition, this_edition_only,
- isbn, standard_number,
- budget_code, cash, period_of_interest_from,
- period_of_interest_to, additional_comments,
- p, f, ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- infos = []
-
- if cash and budget_code == '':
- budget_code = 'cash'
-
- if recid:
- fields = (request_type, recid, budget_code, cash,
- period_of_interest_from, period_of_interest_to,
- additional_comments)
- else:
- fields = (request_type, title, authors, place, publisher, year, edition,
- this_edition_only, isbn, standard_number, budget_code,
- cash, period_of_interest_from, period_of_interest_to,
- additional_comments)
-
- if budget_code == '' and not cash:
- infos.append(_("Payment method information is mandatory. \
- Please, type your budget code or tick the 'cash' checkbox."))
- body = bc_templates.tmpl_register_purchase_request_step1(infos=infos,
- fields=fields, admin=True, ln=ln)
-
- else:
-
-########################
-########################
- if p and not f:
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
-
- body = bc_templates.tmpl_register_purchase_request_step2(
- infos=infos, fields=fields,
- result=None, p=p, f=f, ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return page(title=_("Register ILL request"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
- result = search_user(f, p)
- borrowers_list = []
-
- if len(result) == 0 and f:
- if CFG_CERN_SITE:
- infos.append(_("0 borrowers found.") + ' ' +_("Search by CCID."))
- else:
- new_borrower_link = create_html_link(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/add_new_borrower_step1',
- {'ln': ln}, _("Register new borrower."))
- message = _("0 borrowers found.") + ' ' + new_borrower_link
- infos.append(message)
- else:
- for user in result:
- borrower_data = db.get_borrower_data_by_id(user[0])
- borrowers_list.append(borrower_data)
-
- body = bc_templates.tmpl_register_purchase_request_step2(
- infos=infos, fields=fields,
- result=borrowers_list, p=p,
- f=f, ln=ln)
-########################
-########################
-
- return page(title=_("Register purchase request"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- metaheaderadd='' % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def register_purchase_request_step3(req, request_type, recid, title, authors,
- place, publisher, year, edition, this_edition_only,
- isbn, standard_number,
- budget_code, cash, period_of_interest_from,
- period_of_interest_to, additional_comments,
- borrower_id, ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- infos = []
-
- if recid:
- fields = (request_type, recid, budget_code, cash,
- period_of_interest_from, period_of_interest_to,
- additional_comments)
- else:
- fields = (request_type, title, authors, place, publisher, year, edition,
- this_edition_only, isbn, standard_number, budget_code,
- cash, period_of_interest_from, period_of_interest_to,
- additional_comments)
-
- if budget_code == '' and not cash:
- infos.append(_("Payment method information is mandatory. \
- Please, type your budget code or tick the 'cash' checkbox."))
- body = bc_templates.tmpl_register_purchase_request_step1(infos=infos,
- fields=fields, admin=True, ln=ln)
- else:
- if recid:
- item_info = "{'recid': " + str(recid) + "}"
- title = book_title_from_MARC(recid)
- else:
- item_info = {'title': title, 'authors': authors, 'place': place,
- 'publisher': publisher, 'year' : year, 'edition': edition,
- 'isbn' : isbn, 'standard_number': standard_number}
-
- ill_request_notes = {}
- if additional_comments:
- ill_request_notes[time.strftime("%Y-%m-%d %H:%M:%S")] \
- = str(additional_comments)
-
- if cash and budget_code == '':
- budget_code = 'cash'
-
-
- if borrower_id:
- borrower_email = db.get_borrower_email(borrower_id)
- else:
- borrower_email = db.get_invenio_user_email(id_user)
- borrower_id = db.get_borrower_id_by_email(borrower_email)
-
- db.ill_register_request_on_desk(borrower_id, item_info,
- period_of_interest_from,
- period_of_interest_to,
- CFG_BIBCIRCULATION_ACQ_STATUS_NEW,
- str(ill_request_notes),
- this_edition_only, request_type, budget_code)
-
- msg_for_user = load_template('purchase_notification') % title
- send_email(fromaddr = CFG_BIBCIRCULATION_ILLS_EMAIL,
- toaddr = borrower_email,
- subject = _("Your book purchase request"),
- header = '', footer = '',
- content = msg_for_user,
- attempt_times=1,
- attempt_sleeptime=10
- )
-
- return redirect_to_url(req,
- '%s/admin2/bibcirculation/list_purchase?ln=%s&status=%s' % \
- (CFG_SITE_SECURE_URL, ln,
- CFG_BIBCIRCULATION_ACQ_STATUS_NEW))
-
- return page(title=_("Register purchase request"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- metaheaderadd='' % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def ill_request_details_step1(req, delete_key, ill_request_id, new_status,
- ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if delete_key and ill_request_id:
- if looks_like_dictionary(db.get_ill_request_notes(ill_request_id)):
- library_notes = eval(db.get_ill_request_notes(ill_request_id))
- if delete_key in library_notes.keys():
- del library_notes[delete_key]
- db.update_ill_request_notes(ill_request_id, library_notes)
-
- if new_status:
- db.update_ill_request_status(ill_request_id, new_status)
-
- ill_request_borrower_details = \
- db.get_ill_request_borrower_details(ill_request_id)
-
- if ill_request_borrower_details is None \
- or len(ill_request_borrower_details) == 0:
- infos.append(_("Borrower request details not found."))
-
- ill_request_details = db.get_ill_request_details(ill_request_id)
- if ill_request_details is None or len(ill_request_details) == 0:
- infos.append(_("Request not found."))
-
-
- libraries = db.get_external_libraries()
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- title = _("ILL request details")
- if infos == []:
- body = bc_templates.tmpl_ill_request_details_step1(
- ill_request_id=ill_request_id,
- ill_request_details=ill_request_details,
- libraries=libraries,
- ill_request_borrower_details=ill_request_borrower_details,
- ln=ln)
- else:
- body = bc_templates.tmpl_display_infos(infos, ln)
-
- return page(title=title,
- uid=id_user,
- req=req,
- metaheaderadd='' % CFG_SITE_SECURE_URL,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def ill_request_details_step2(req, delete_key, ill_request_id, new_status,
- library_id, request_date, expected_date,
- arrival_date, due_date, return_date,
- cost, _currency, barcode, library_notes,
- book_info, article_info, ln=CFG_SITE_LANG):
-
- #id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if delete_key and ill_request_id:
- if looks_like_dictionary(db.get_ill_request_notes(ill_request_id)):
- library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
- if delete_key in library_previous_notes.keys():
- del library_previous_notes[delete_key]
- db.update_ill_request_notes(ill_request_id, library_previous_notes)
-
- if db.get_ill_request_notes(ill_request_id):
- if looks_like_dictionary(db.get_ill_request_notes(ill_request_id)):
- library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
- else:
- library_previous_notes = {}
- else:
- library_previous_notes = {}
-
- if library_notes:
- library_previous_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = \
- str(library_notes)
-
- if new_status == CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED:
- borrower_id = db.get_ill_borrower(ill_request_id)
- barcode = db.get_ill_barcode(ill_request_id)
- db.update_ill_loan_status(borrower_id, barcode, return_date, 'ill')
-
- db.update_ill_request(ill_request_id, library_id, request_date,
- expected_date, arrival_date, due_date, return_date,
- new_status, cost, barcode,
- str(library_previous_notes))
-
- request_type = db.get_ill_request_type(ill_request_id)
- if request_type == 'book':
- item_info = book_info
- else:
- item_info = article_info
- db.update_ill_request_item_info(ill_request_id, item_info)
-
- if new_status == CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN:
- # Redirect to an email template when the ILL 'book' arrives
- # (Not for articles.)
- subject = _("ILL received: ")
- book_info = db.get_ill_book_info(ill_request_id)
- if looks_like_dictionary(book_info):
- book_info = eval(book_info)
- if 'recid' in book_info:
- subject += "'" + book_title_from_MARC(int(book_info['recid'])) + "'"
- bid = db.get_ill_borrower(ill_request_id)
- msg = load_template("ill_received")
-
- return redirect_to_url(req,
- create_url(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/borrower_notification',
- {'borrower_id': bid,
- 'subject': subject,
- 'load_msg_template': False,
- 'template': msg,
- 'from_address': CFG_BIBCIRCULATION_ILLS_EMAIL
- }
- )
- )
-
- return list_ill_request(req, new_status, ln)
-
-
-def purchase_details_step1(req, delete_key, ill_request_id, new_status,
- ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- if delete_key and ill_request_id:
- if looks_like_dictionary(db.get_ill_request_notes(ill_request_id)):
- library_notes = eval(db.get_ill_request_notes(ill_request_id))
- if delete_key in library_notes.keys():
- del library_notes[delete_key]
- db.update_ill_request_notes(ill_request_id, library_notes)
-
- if new_status:
- db.update_ill_request_status(ill_request_id, new_status)
-
- ill_request_borrower_details = \
- db.get_purchase_request_borrower_details(ill_request_id)
-
- if ill_request_borrower_details is None \
- or len(ill_request_borrower_details) == 0:
- infos.append(_("Borrower request details not found."))
-
- ill_request_details = db.get_ill_request_details(ill_request_id)
- if ill_request_details is None or len(ill_request_details) == 0:
- infos.append(_("Request not found."))
-
- vendors = db.get_all_vendors()
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- if infos == []:
- body = bc_templates.tmpl_purchase_details_step1(
- ill_request_id=ill_request_id,
- ill_request_details=ill_request_details,
- libraries=vendors,
- ill_request_borrower_details=ill_request_borrower_details,
- ln=ln)
- title = _("Purchase details")
- else:
- body = bc_templates.tmpl_display_infos(infos, ln)
-
- return page(title=title,
- uid=id_user,
- req=req,
- metaheaderadd = "" % CFG_SITE_SECURE_URL,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def purchase_details_step2(req, delete_key, ill_request_id, new_status,
- library_id, request_date, expected_date,
- arrival_date, due_date, return_date,
- cost, budget_code, library_notes,
- item_info, ln=CFG_SITE_LANG):
-
- #id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if delete_key and ill_request_id:
- if looks_like_dictionary(db.get_ill_request_notes(ill_request_id)):
- library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
- if delete_key in library_previous_notes.keys():
- del library_previous_notes[delete_key]
- db.update_ill_request_notes(ill_request_id, library_previous_notes)
-
- if db.get_ill_request_notes(ill_request_id):
- if looks_like_dictionary(db.get_ill_request_notes(ill_request_id)):
- library_previous_notes = eval(db.get_ill_request_notes(ill_request_id))
- else:
- library_previous_notes = {}
- else:
- library_previous_notes = {}
-
- if library_notes:
- library_previous_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = \
- str(library_notes)
-
- if new_status == CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED:
- borrower_id = db.get_ill_borrower(ill_request_id)
-
- db.update_purchase_request(ill_request_id, library_id, request_date,
- expected_date, arrival_date, due_date, return_date,
- new_status, cost, budget_code,
- str(library_previous_notes))
-
- request_type = db.get_ill_request_type(ill_request_id)
-
- if request_type not in CFG_BIBCIRCULATION_PROPOSAL_TYPE:
- db.update_ill_request_item_info(ill_request_id, item_info)
-
- if new_status in (CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE):
-
- barcode = db.get_ill_barcode(ill_request_id)
- if new_status == CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER:
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER, barcode)
- subject = _("Book suggestion accepted: ")
- template = "proposal_acceptance"
- else:
- db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW, barcode)
- subject = _("Book suggestion refused: ")
- template = "proposal_refusal"
-
- book_info = db.get_ill_book_info(ill_request_id)
- if looks_like_dictionary(book_info):
- book_info = eval(book_info)
- if 'recid' in book_info:
- bid = db.get_ill_borrower(ill_request_id)
- if db.has_loan_request(bid, book_info['recid']):
- subject += "'" + book_title_from_MARC(int(book_info['recid'])) + "'"
- return redirect_to_url(req,
- create_url(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/borrower_notification',
- {'borrower_id': bid,
- 'subject': subject,
- 'template': template,
- 'from_address': CFG_BIBCIRCULATION_ILLS_EMAIL
- }
- )
- )
-
- if new_status == CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED:
- barcode = db.get_ill_barcode(ill_request_id)
- # Reset the item description to the default value.
- db.set_item_description(barcode, '-')
- #db.update_item_status(CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS, barcode)
- borrower_id = db.get_ill_borrower(ill_request_id)
- recid = db.get_id_bibrec(barcode)
- if db.has_loan_request(borrower_id, recid):
- #If an ILL has already been created(After the book had been put aside), there
- #would be no waiting request by the proposer.
- db.update_loan_request_status(CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- barcode=barcode,
- borrower_id=borrower_id)
- return redirect_to_url(req,
- '%s/admin2/bibcirculation/update_item_info_step4?barcode=%s' % \
- (CFG_SITE_SECURE_URL, barcode))
-
- if new_status == CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED:
- subject = _("Purchase received: ")
- book_info = db.get_ill_book_info(ill_request_id)
- if looks_like_dictionary(book_info):
- book_info = eval(book_info)
- if 'recid' in book_info:
- subject += "'" + book_title_from_MARC(int(book_info['recid'])) + "'"
- bid = db.get_ill_borrower(ill_request_id)
-
- if budget_code == 'cash':
- msg = load_template("purchase_received_cash") % cost
- else:
- msg = load_template("purchase_received_tid") % cost
-
- return redirect_to_url(req,
- create_url(CFG_SITE_SECURE_URL +
- '/admin2/bibcirculation/borrower_notification',
- {'borrower_id': bid,
- 'subject': subject,
- 'load_msg_template': False,
- 'template': msg,
- 'from_address': CFG_BIBCIRCULATION_ILLS_EMAIL
- }
- )
- )
- if new_status in CFG_BIBCIRCULATION_ACQ_STATUS or \
- new_status == CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER:
- # The items 'on order' whether for acquisition for the library or purchase
- # on behalf of the user are displayed in the same list.
- return redirect_to_url(req,
- '%s/admin2/bibcirculation/list_purchase?ln=%s&status=%s' % \
- (CFG_SITE_SECURE_URL, ln, new_status))
- else:
- return redirect_to_url(req,
- '%s/admin2/bibcirculation/list_proposal?ln=%s&status=%s' % \
- (CFG_SITE_SECURE_URL, ln, new_status))
-
-
-def get_ill_library_notes(req, ill_id, delete_key, library_notes,
- ln=CFG_SITE_LANG):
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if delete_key and ill_id:
- if looks_like_dictionary(db.get_ill_notes(ill_id)):
- ill_notes = eval(db.get_ill_notes(ill_id))
- if delete_key in ill_notes.keys():
- del ill_notes[delete_key]
- db.update_ill_notes(ill_id, ill_notes)
-
- elif library_notes:
- if db.get_ill_notes(ill_id):
- if looks_like_dictionary(db.get_ill_notes(ill_id)):
- ill_notes = eval(db.get_ill_notes(ill_id))
- else:
- ill_notes = {}
- else:
- ill_notes = {}
-
- ill_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(library_notes)
- db.update_ill_notes(ill_id, ill_notes)
-
- ill_notes = db.get_ill_notes(ill_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_ill_notes(ill_notes=ill_notes,
- ill_id=ill_id,
- ln=ln)
- return page(title=_("ILL notes"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def list_ill_request(req, status, ln=CFG_SITE_LANG):
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- ill_req = db.get_ill_requests(status)
-
- body = bc_templates.tmpl_list_ill(ill_req=ill_req, ln=ln)
-
- return page(title=_("List of ILL requests"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def list_purchase(req, status, recid=None, ln=CFG_SITE_LANG):
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if recid:
- # Purchases of a particular item to be displayed in the item info page.
- purchase_reqs = db.get_item_purchases(status, recid)
- else:
- purchase_reqs = db.get_purchases(status)
-
- body = bc_templates.tmpl_list_purchase(purchase_reqs, ln=ln)
-
- return page(title=_("List of purchase requests"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def list_proposal(req, status, ln=CFG_SITE_LANG):
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if status == "requests-putaside":
- requests = db.get_requests_on_put_aside_proposals()
- body = bc_templates.tmpl_list_requests_on_put_aside_proposals(requests, ln=ln)
- title=_("List of requests on put aside proposals")
- else:
- proposals = db.get_proposals(status)
- body = bc_templates.tmpl_list_proposal(proposals, ln=ln)
- title=_("List of proposals")
-
- return page(title=title,
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-def ill_search(req, ln=CFG_SITE_LANG):
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_ill_search(infos=infos, ln=ln)
-
- return page(title=_("ILL search"),
- uid=id_user,
- req=req,
- body=body,
- language=ln,
- metaheaderadd='' % CFG_SITE_SECURE_URL,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def ill_search_result(req, p, f, date_from, date_to, ln):
- """
- Search an item and return a list with all the possible results. To retrieve
- the information desired, we use the method 'perform_request_search' (from
- search_engine.py). In the case of BibCirculation, we are just looking for
- books (items) inside the collection 'Books'.
-
- @type p: string
- @param p: search pattern
-
- @type f: string
- @param f: search field
-
- @return: list of recids
- """
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- #id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if not has_date_format(date_from):
- date_from = '0000-00-00'
- if not has_date_format(date_to):
- date_to = '9999-12-31'
-
- if f == 'title':
- ill_req = db.search_ill_requests_title(p, date_from, date_to)
- body = bc_templates.tmpl_list_ill(ill_req=ill_req, ln=ln)
-
- elif f == 'ILL_request_ID':
- ill_req = db.search_ill_requests_id(p, date_from, date_to)
- body = bc_templates.tmpl_list_ill(ill_req=ill_req, ln=ln)
-
- elif f == 'cost':
- purchase_reqs = db.search_requests_cost(p, date_from, date_to)
- body = bc_templates.tmpl_list_purchase(purchase_reqs=purchase_reqs, ln=ln)
-
- elif f == 'notes':
- purchase_reqs = db.search_requests_notes(p, date_from, date_to)
- body = bc_templates.tmpl_list_purchase(purchase_reqs=purchase_reqs, ln=ln)
-
- return page(title=_("List of ILL requests"),
- req=req,
- body=body,
- language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-
-
-###
-### "Library" related templates ###
-###
-
-
-
-
-def get_library_details(req, library_id, ln=CFG_SITE_LANG):
- """
- Display the details of a library.
-
- @type library_id: integer.
- @param library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
-
- @return: library details.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- library_details = db.get_library_details(library_id)
-
- if library_details is None:
- _ = gettext_set_language(ln)
- infos = []
- infos.append(_('Library ID not found.'))
- return search_library_step1(req, infos, ln)
-
- library_items = db.get_library_items(library_id)
-
- body = bc_templates.tmpl_library_details(library_details=library_details,
- library_items=library_items,
- ln=ln)
-
- return page(title=_("Library details"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def merge_libraries_step1(req, library_id, f=None, p=None, ln=CFG_SITE_LANG):
- """
- Step 1/3 of library merging procedure
-
- @param library_id: ID of the library to be deleted
-
- @param p: search pattern.
-
- @param f: field
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- library_details = db.get_library_details(library_id)
- library_items = db.get_library_items(library_id)
-
- result = None
-
- if f is not None:
- if p in (None, '', '*'):
- result = db.get_all_libraries() #list of (id, name)
- elif f == 'name':
- result = db.search_library_by_name(p)
- elif f == 'email':
- result = db.search_library_by_email(p)
-
-
- body = bc_templates.tmpl_merge_libraries_step1(
- library_details=library_details,
- library_items=library_items,
- result=result,
- p=p,
- ln=ln)
-
- return page(title=_("Merge libraries"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def merge_libraries_step2(req, library_from, library_to, ln=CFG_SITE_LANG):
- """
- Step 2/3 of library merging procedure
- Confirm the libraries selected
-
- @param library_from: ID of the library to be deleted
-
- @param library_to: ID of the resulting library
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- library_from_details = db.get_library_details(library_from)
- library_from_items = db.get_library_items(library_from)
-
- library_to_details = db.get_library_details(library_to)
- library_to_items = db.get_library_items(library_to)
-
- body = bc_templates.tmpl_merge_libraries_step2(
- library_from_details=library_from_details,
- library_from_items=library_from_items,
- library_to_details=library_to_details,
- library_to_items=library_to_items,
- ln=ln)
-
- return page(title=_("Merge libraries"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def merge_libraries_step3(req, library_from, library_to, ln=CFG_SITE_LANG):
- """
- Step 3/3 of library merging procedure
- Perform the merge and display the details of the resulting library
-
- @param library_from: ID of the library to be deleted
-
- @param library_to: ID of the resulting library
- """
-
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- db.merge_libraries(library_from, library_to)
-
- return get_library_details(req, library_to, ln)
-
-def add_new_library_step1(req, ln=CFG_SITE_LANG):
- """
- Add a new Library.
- """
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_add_new_library_step1(ln=ln)
-
- return page(title=_("Add new library"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_library_step2(req, name, email, phone, address,
- lib_type, notes, ln=CFG_SITE_LANG):
-
- """
- Add a new Library.
- """
-
- tup_infos = (name, email, phone, address, lib_type, notes)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- _ = gettext_set_language(ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- body = bc_templates.tmpl_add_new_library_step2(tup_infos=tup_infos, ln=ln)
-
- return page(title=_("Add new library"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_library_step3(req, name, email, phone, address,
- lib_type, notes, ln=CFG_SITE_LANG):
- """
- Add a new Library.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- db.add_new_library(name, email, phone, address, lib_type, notes)
-
- body = bc_templates.tmpl_add_new_library_step3(ln=ln)
-
- return page(title=_("Add new library"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_library_info_step1(req, ln=CFG_SITE_LANG):
- """
- Update the library's information.
- """
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_update_library_info_step1(infos=infos, ln=ln)
-
- return page(title=_("Update library information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_library_info_step2(req, column, string, ln=CFG_SITE_LANG):
- """
- Update the library's information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if not string:
- infos = []
- infos.append(_("Empty string.") + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_update_library_info_step1(infos=infos, ln=ln)
- elif string == '*':
- result = db.get_all_libraries()
- body = bc_templates.tmpl_update_library_info_step2(result=result, ln=ln)
- else:
- if column == 'name':
- result = db.search_library_by_name(string)
- else:
- result = db.search_library_by_email(string)
-
- body = bc_templates.tmpl_update_library_info_step2(result=result, ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("Update library information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_library_info_step3(req, library_id, ln=CFG_SITE_LANG):
- """
- Update the library's information.
-
- library_id - identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- library_info = db.get_library_details(library_id)
-
- body = bc_templates.tmpl_update_library_info_step3(
- library_info=library_info,
- ln=ln)
-
- return page(title=_("Update library information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_library_info_step4(req, name, email, phone, address, lib_type,
- library_id, ln=CFG_SITE_LANG):
- """
- Update the library's information.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- tup_infos = (library_id, name, email, phone, address, lib_type)
-
- body = bc_templates.tmpl_update_library_info_step4(tup_infos=tup_infos,
- ln=ln)
-
- return page(title=_("Update library information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_library_info_step5(req, name, email, phone, address, lib_type,
- library_id, ln=CFG_SITE_LANG):
- """
- Update the library's information.
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- #(library_id, name, email, phone, address) = tup_infos
-
- db.update_library_info(library_id, name, email, phone, address, lib_type)
-
- body = bc_templates.tmpl_update_library_info_step5(ln=ln)
-
- return page(title=_("Update library information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_library_notes(req, library_id, delete_key,
- library_notes, ln=CFG_SITE_LANG):
- """
- Retrieve notes related with a library.
-
- library_id - identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if delete_key and library_id:
- if looks_like_dictionary(db.get_library_notes(library_id)):
- lib_notes = eval(db.get_library_notes(library_id))
- if delete_key in lib_notes.keys():
- del lib_notes[delete_key]
- db.update_library_notes(library_id, lib_notes)
-
- elif library_notes:
- if db.get_library_notes(library_id):
- if looks_like_dictionary(db.get_library_notes(library_id)):
- lib_notes = eval(db.get_library_notes(library_id))
- else:
- lib_notes = {}
- else:
- lib_notes = {}
-
- lib_notes[time.strftime("%Y-%m-%d %H:%M:%S")] = str(library_notes)
- db.update_library_notes(library_id, lib_notes)
-
- lib_notes = db.get_library_notes(library_id)
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- body = bc_templates.tmpl_library_notes(library_notes=lib_notes,
- library_id=library_id,
- ln=ln)
- return page(title=_("Library notes"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def search_library_step1(req, infos=[], ln=CFG_SITE_LANG):
- """
- Display the form where we can search a library (by name or email).
- """
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_search_library_step1(infos=infos,
- ln=ln)
-
- return page(title=_("Search library"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def search_library_step2(req, column, string, ln=CFG_SITE_LANG):
- """
- Search a library and return a list with all the possible results, using the
- parameters received from the previous step.
-
- column - identify the column, of the table crcLIBRARY, that will be
- considered during the search. Can be 'name' or 'email'.
-
- str - string used for the search process.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if not string:
- infos = []
- infos.append(_("Emptry string.") + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_search_library_step1(infos=infos, ln=ln)
- elif string == '*':
- result = db.get_all_libraries()
- body = bc_templates.tmpl_search_library_step2(result=result, ln=ln)
- else:
- if column == 'name':
- result = db.search_library_by_name(string)
- else:
- result = db.search_library_by_email(string)
-
- body = bc_templates.tmpl_search_library_step2(result=result, ln=ln)
-
-
- navtrail_previous_links = 'Admin Area' \
- ' > '\
- 'Circulation Management' \
- ' ' % (CFG_SITE_SECURE_URL, CFG_SITE_SECURE_URL, ln)
-
- return page(title=_("Search library"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-
-
-
-
-###
-### "Vendor" related templates ###
-###
-
-
-
-
-def get_vendor_details(req, vendor_id, ln=CFG_SITE_LANG):
- """
- Display the details of a vendor.
-
- @type vendor_id: integer.
- @param vendor_id: identify the vendor. It is also the primary key of
- the table crcVENDOR.
-
- @return: vendor details.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- vendor_details = db.get_vendor_details(vendor_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_vendor_details(vendor_details=vendor_details,
- ln=ln)
-
- return page(title=_("Vendor details"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_vendor_step1(req, ln=CFG_SITE_LANG):
- """
- Add a new Vendor.
- """
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- body = bc_templates.tmpl_add_new_vendor_step1(ln=ln)
-
- return page(title=_("Add new vendor"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_vendor_step2(req, name, email, phone, address,
- notes, ln=CFG_SITE_LANG):
-
- """
- Add a new Vendor.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- tup_infos = (name, email, phone, address, notes)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_add_new_vendor_step2(tup_infos=tup_infos, ln=ln)
-
- return page(title=_("Add new vendor"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def add_new_vendor_step3(req, name, email, phone, address,
- notes, ln=CFG_SITE_LANG):
- """
- Add a new Vendor.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- db.add_new_vendor(name, email, phone, address, notes)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_add_new_vendor_step3(ln=ln)
-
- return page(title=_("Add new vendor"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_vendor_info_step1(req, ln=CFG_SITE_LANG):
- """
- Update the vendor's information.
- """
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- _ = gettext_set_language(ln)
-
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- body = bc_templates.tmpl_update_vendor_info_step1(infos=infos, ln=ln)
-
- return page(title=_("Update vendor information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_vendor_info_step2(req, column, string, ln=CFG_SITE_LANG):
- """
- Update the vendor's information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if not string:
- infos = []
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_update_vendor_info_step1(infos=infos, ln=ln)
-
- elif string == '*':
- result = db.get_all_vendors()
- body = bc_templates.tmpl_update_vendor_info_step2(result=result, ln=ln)
-
- else:
- if column == 'name':
- result = db.search_vendor_by_name(string)
- else:
- result = db.search_vendor_by_email(string)
- body = bc_templates.tmpl_update_vendor_info_step2(result=result, ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_update_vendor_info_step2(result=result, ln=ln)
-
- return page(title=_("Update vendor information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_vendor_info_step3(req, vendor_id, ln=CFG_SITE_LANG):
- """
- Update the library's information.
-
- vendor_id - identify the vendor. It is also the primary key of
- the table crcVENDOR.
-
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- vendor_info = db.get_vendor_details(vendor_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_update_vendor_info_step3(vendor_info=vendor_info,
- ln=ln)
-
- return page(title=_("Update vendor information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_vendor_info_step4(req, name, email, phone, address,
- vendor_id, ln=CFG_SITE_LANG):
- """
- Update the vendor's information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- tup_infos = (vendor_id, name, email, phone, address)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_update_vendor_info_step4(tup_infos=tup_infos,
- ln=ln)
-
- return page(title=_("Update vendor information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def update_vendor_info_step5(req, name, email, phone, address,
- vendor_id, ln=CFG_SITE_LANG):
- """
- Update the library's information.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- db.update_vendor_info(vendor_id, name, email, phone, address)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_update_vendor_info_step5(ln=ln)
-
- return page(title=_("Update vendor information"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def get_vendor_notes(req, vendor_id, add_notes, new_note, ln=CFG_SITE_LANG):
- """
- Retrieve notes related with a vendor.
-
- vendor_id - identify the vendor. It is also the primary key of
- the table crcVENDOR.
-
- @param add_notes: display the textarea where will be written a new notes.
-
- @param new_notes: note that will be added to the others vendor's notes.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if new_note:
- date = '[' + time.ctime() + '] '
- new_line = '\n'
- new_note = date + new_note + new_line
- db.add_new_vendor_note(new_note, vendor_id)
-
- vendor_notes = db.get_vendor_notes(vendor_id)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_vendor_notes(vendor_notes=vendor_notes,
- vendor_id=vendor_id,
- add_notes=add_notes,
- ln=ln)
- return page(title=_("Vendor notes"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def search_vendor_step1(req, ln=CFG_SITE_LANG):
- """
- Display the form where we can search a vendor (by name or email).
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- body = bc_templates.tmpl_search_vendor_step1(infos=infos,
- ln=ln)
-
- return page(title=_("Search vendor"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
-
-def search_vendor_step2(req, column, string, ln=CFG_SITE_LANG):
- """
- Search a vendor and return a list with all the possible results, using the
- parameters received from the previous step.
-
- column - identify the column, of the table crcVENDOR, that will be
- considered during the search. Can be 'name' or 'email'.
-
- str - string used for the search process.
- """
- id_user = getUid(req)
- (auth_code, auth_message) = is_adminuser(req)
- if auth_code != 0:
- return mustloginpage(req, auth_message)
-
- _ = gettext_set_language(ln)
-
- if not string:
- infos = []
- infos.append(_('Empty string.') + ' ' + _('Please, try again.'))
- body = bc_templates.tmpl_search_vendor_step1(infos=infos,
- ln=ln)
- elif string == '*':
- result = db.get_all_vendors()
- body = bc_templates.tmpl_search_vendor_step2(result=result, ln=ln)
-
- else:
- if column == 'name':
- result = db.search_vendor_by_name(string)
- else:
- result = db.search_vendor_by_email(string)
- body = bc_templates.tmpl_search_vendor_step2(result=result, ln=ln)
-
- navtrail_previous_links = 'Admin Area' \
- '' % (CFG_SITE_SECURE_URL,)
-
- return page(title=_("Search vendor"),
- uid=id_user,
- req=req,
- body=body, language=ln,
- navtrail=navtrail_previous_links,
- lastupdated=__lastupdated__)
diff --git a/invenio/legacy/bibcirculation/api.py b/invenio/legacy/bibcirculation/api.py
deleted file mode 100644
index fd3851ed4..000000000
--- a/invenio/legacy/bibcirculation/api.py
+++ /dev/null
@@ -1,799 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011, 2013 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-"""
- Invenio Bibcirculation User.
- When applicable, methods should be renamed, refactored and
- appropriate documentation added.
-"""
-
-__revision__ = "$Id$"
-
-import datetime, time
-
-# Invenio imports
-from invenio.config import \
- CFG_SITE_LANG, \
- CFG_CERN_SITE, \
- CFG_SITE_URL
-from invenio.legacy.webuser import collect_user_info
-from invenio.ext.email import send_email
-from invenio.base.i18n import gettext_set_language
-from invenio.legacy.bibrecord import record_get_field_value
-from invenio.legacy.search_engine import get_record
-
-# Bibcirculation imports
-import invenio.legacy.bibcirculation.db_layer as db
-from invenio.legacy.bibcirculation.adminlib import load_template
-from invenio.legacy.bibcirculation.utils import book_title_from_MARC, \
- book_information_from_MARC, \
- create_ill_record, \
- tag_all_requests_as_done, \
- generate_tmp_barcode, \
- generate_new_due_date, \
- update_requests_statuses, \
- search_user
-from invenio.legacy.bibcirculation.cern_ldap import get_user_info_from_ldap
-from invenio.legacy.bibcirculation.config import CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, \
- CFG_BIBCIRCULATION_LOANS_EMAIL, \
- CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED, \
- CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW, \
- AMZ_BOOK_PUBLICATION_DATE_TAG, \
- CFG_BIBCIRCULATION_DEFAULT_LIBRARY_ID
-import invenio.legacy.template
-bc_templates = invenio.legacy.template.load('bibcirculation')
-
-
-def perform_borrower_loans(uid, barcode, borrower_id,
- request_id, action, ln=CFG_SITE_LANG):
- """
- Display all the loans and the requests of a given borrower.
-
- @param barcode: identify the item. Primary key of crcITEM.
- @type barcode: string
-
- @param borrower_id: identify the borrower. Primary key of crcBORROWER.
- @type borrower_id: int
-
- @param request_id: identify the request: Primary key of crcLOANREQUEST
- @type request_id: int
-
- @return body(html)
- """
-
- _ = gettext_set_language(ln)
-
- infos = []
-
- borrower_id = db.get_borrower_id_by_email(db.get_invenio_user_email(uid))
-
- new_due_date = generate_new_due_date(30)
-
- #renew loan
- if action == 'renew':
- recid = db.get_id_bibrec(barcode)
- item_description = db.get_item_description(barcode)
- queue = db.get_queue_request(recid, item_description)
-
- if len(queue) != 0 and queue[0][0] != borrower_id:
- message = "It is not possible to renew your loan for %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s" % {'x_title': book_title_from_MARC(recid), 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
- message += ' ' + _("Another user is waiting for this book.")
- infos.append(message)
-
- else:
- loan_id = db.get_current_loan_id(barcode)
- db.renew_loan(loan_id, new_due_date)
- #update_status_if_expired(loan_id)
- tag_all_requests_as_done(barcode, borrower_id)
- infos.append(_("Your loan has been renewed with success."))
-
- #cancel request
- elif action == 'cancel':
- db.cancel_request(request_id)
- barcode_requested = db.get_requested_barcode(request_id)
- update_requests_statuses(barcode_requested)
-
- #renew all loans
- elif action == 'renew_all':
- list_of_barcodes = db.get_borrower_loans_barcodes(borrower_id)
- for bc in list_of_barcodes:
- bc_recid = db.get_id_bibrec(bc)
- item_description = db.get_item_description(bc)
- queue = db.get_queue_request(bc_recid, item_description)
-
- #check if there are requests
- if len(queue) != 0 and queue[0][0] != borrower_id:
- message = "It is not possible to renew your loan for %(x_strong_tag_open)s%(x_title)s%(x_strong_tag_close)s" % {'x_title': book_title_from_MARC(bc_recid), 'x_strong_tag_open': '', 'x_strong_tag_close': ''}
- message += ' ' + _("Another user is waiting for this book.")
- infos.append(message)
- else:
- loan_id = db.get_current_loan_id(bc)
- db.renew_loan(loan_id, new_due_date)
- #update_status_if_expired(loan_id)
- tag_all_requests_as_done(barcode, borrower_id)
-
- if infos == []:
- infos.append(_("All loans have been renewed with success."))
-
- loans = db.get_borrower_loans(borrower_id)
- requests = db.get_borrower_requests(borrower_id)
- proposals = db.get_borrower_proposals(borrower_id)
-
- body = bc_templates.tmpl_yourloans(loans=loans, requests=requests, proposals=proposals,
- borrower_id=borrower_id, infos=infos, ln=ln)
- return body
-
-def perform_loanshistoricaloverview(uid, ln=CFG_SITE_LANG):
- """
- Display Loans historical overview for user uid.
-
- @param uid: user id
- @param ln: language of the page
-
- @return body(html)
- """
- invenio_user_email = db.get_invenio_user_email(uid)
- borrower_id = db.get_borrower_id_by_email(invenio_user_email)
- result = db.get_historical_overview(borrower_id)
-
- body = bc_templates.tmpl_loanshistoricaloverview(result=result, ln=ln)
-
- return body
-
-def perform_get_holdings_information(recid, req, action="borrowal", ln=CFG_SITE_LANG):
- """
- Display all the copies of an item. If the parameter action is 'proposal', display
- appropriate information to the user.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param action: Specifies whether the current record is put up to solicit acquisition
- proposals(if "proposal") or not("borrowal").
- @type proposal: string
-
- @return body(html)
- """
- _ = gettext_set_language(ln)
-
- if action == "proposal":
- tag = AMZ_BOOK_PUBLICATION_DATE_TAG
- publication_date = record_get_field_value(get_record(recid), tag[:3],
- ind1=tag[3], ind2=tag[4],
- code=tag[5])
- msg = ''
- if publication_date:
- cur_date = datetime.date.today()
- try:
- pub_date = time.strptime(publication_date, '%d %b %Y')
- pub_date = datetime.date(pub_date[0], pub_date[1], pub_date[2])
- if cur_date < pub_date:
- msg += _("The publication date of this book is %(x_date)s.", x_date=(publication_date))
- msg += "
"
- else:
- msg += _("This book has no copies in the library. ")
- except:
- msg += _("This book has no copies in the library. ")
-
- msg += _("If you think this book is interesting, suggest it and tell us why you consider this \
- book is important. The library will consider your opinion and if we decide to buy the \
- book, we will issue a loan for you as soon as it arrives and send it by internal mail.")
- msg += "
"
- msg += _("In case we decide not to buy the book, we will offer you an interlibrary loan")
-
- body = bc_templates.tmpl_book_proposal_information(recid, msg, ln=ln)
- else:
- holdings_information = db.get_holdings_information(recid, False)
- body = bc_templates.tmpl_holdings_information(recid=recid,
- req=req,
- holdings_info=holdings_information,
- ln=ln)
-
- return body
-
-def perform_new_request(recid, barcode, action="borrowal", ln=CFG_SITE_LANG):
- """
- Display form to be filled by the user.
-
- @param uid: user id
- @type: int
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param barcode: identify the item. Primary key of crcITEM.
- @type barcode: string
-
- @return request form
- """
-
- body = bc_templates.tmpl_new_request(recid=recid, barcode=barcode, action=action, ln=ln)
-
- return body
-
-def perform_book_proposal_send(uid, recid, period_from, period_to,
- remarks, ln=CFG_SITE_LANG):
- """
- The subfield containing the information about the source of importation
- of the record acts as the marker for the records put up for acquisition
- proposals.
-
- Register the user's book proposal, his period of interest and his remarks
- in the 'ILLREQUEST' table. Add a new 'dummy' copy for the proposed book.
-
- Create a loan(hold) request on behalf of the user for that copy and send
- a confirmation e-mail to her/him.
- """
- _ = gettext_set_language(ln)
-
- user = collect_user_info(uid)
-
- if CFG_CERN_SITE:
- try:
- borrower = search_user('ccid', user['external_personid'])
- except:
- borrower = ()
- else:
- borrower = search_user('email', user['email'])
-
- if borrower != ():
- if not db.has_copies(recid):
- tmp_barcode = generate_tmp_barcode()
- ill_register_request_with_recid(recid, uid, period_from, period_to, remarks,
- conditions='register_acquisition_suggestion',
- only_edition='False', barcode=tmp_barcode, ln=CFG_SITE_LANG)
-
- db.add_new_copy(tmp_barcode, recid, library_id=CFG_BIBCIRCULATION_DEFAULT_LIBRARY_ID,
- collection='', location='',
- description=_("This book was suggested for acquisition"), loan_period='',
- status=CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW, expected_arrival_date='')
-
- db.delete_brief_format_cache(recid)
-
- return perform_new_request_send_message(uid, recid, period_from, period_to, tmp_barcode,
- status=CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED,
- mail_subject='Acquisition Suggestion',
- mail_template='proposal_notification',
- mail_remarks=remarks, ln=CFG_SITE_LANG)
- return _("This item already has copies.")
- else:
- if CFG_CERN_SITE:
- message = bc_templates.tmpl_message_request_send_fail_cern("Borrower ID not found.")
- else:
- message = bc_templates.tmpl_message_request_send_fail_other("Borrower ID not found.")
-
- body = bc_templates.tmpl_new_request_send(message=message, ln=ln)
-
- return body
-
-def perform_new_request_send(uid, recid, period_from, period_to,
- barcode, ln=CFG_SITE_LANG):
-
- """
- @param recid: recID - Invenio record identifier
- @param ln: language of the page
- """
-
- nb_requests = 0
- all_copies_on_loan = True
- description = db.get_item_description(barcode)
- copies = db.get_barcodes(recid, description)
- for bc in copies:
- nb_requests += db.get_number_requests_per_copy(bc)
- if db.is_item_on_loan(bc) is None:
- all_copies_on_loan = False
-
- if nb_requests == 0:
- if all_copies_on_loan:
- status = CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING
- else:
- status = CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING
- else:
- status = CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING
-
- return perform_new_request_send_message(uid, recid, period_from, period_to, barcode,
- status, mail_subject='New request',
- mail_template='notification',
- mail_remarks='', ln=ln)
-
-def perform_new_request_send_message(uid, recid, period_from, period_to, barcode,
- status, mail_subject, mail_template,
- mail_remarks='', ln=CFG_SITE_LANG):
-
- user = collect_user_info(uid)
-
- if CFG_CERN_SITE:
- try:
- borrower = search_user('ccid', user['external_personid'])
- except:
- borrower = ()
- else:
- borrower = search_user('email', user['email'])
-
- if borrower != ():
- borrower_id = borrower[0][0]
- if db.is_doc_already_requested(recid, barcode, borrower_id):
- message = bc_templates.tmpl_message_send_already_requested()
- return bc_templates.tmpl_new_request_send(message=message, ln=ln)
-
- borrower_details = db.get_borrower_details(borrower_id)
- (_id, ccid, name, email, _phone, address, mailbox) = borrower_details
-
- (title, year, author,
- isbn, publisher) = book_information_from_MARC(recid)
-
- req_id = db.new_hold_request(borrower_id, recid, barcode,
- period_from, period_to, status)
-
-
- location = '-'
- library = ''
- request_date = ''
- if status != CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED:
- details = db.get_loan_request_details(req_id)
- if details:
- library = details[3]
- location = details[4]
- request_date = details[7]
-
- message_template = load_template(mail_template)
-
- # A message to be sent to the user detailing his loan request
- # or his new book proposal.
- if status == CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED:
- message_for_user = message_template % (title)
- else:
- link_to_holdings_details = CFG_SITE_URL + \
- '/record/%s/holdings' % str(recid)
- message_for_user = message_template % (name, ccid, email, address,
- mailbox, title, author, publisher,
- year, isbn, location, library,
- link_to_holdings_details, request_date)
-
- send_email(fromaddr = CFG_BIBCIRCULATION_LOANS_EMAIL,
- toaddr = email,
- subject = mail_subject,
- content = message_for_user,
- header = '',
- footer = '',
- attempt_times=1,
- attempt_sleeptime=10
- )
-
- if status == CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING:
- # A message to be sent to the librarian about the pending status.
- link_to_item_request_details = CFG_SITE_URL + \
- "/admin2/bibcirculation/get_item_requests_details?ln=%s&recid=%s" \
- % (ln, str(recid))
- message_for_librarian = message_template % (name, ccid, email, address,
- mailbox, title, author, publisher,
- year, isbn, location, library,
- link_to_item_request_details,
- request_date)
- send_email(fromaddr = CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
- toaddr = CFG_BIBCIRCULATION_LOANS_EMAIL,
- subject = mail_subject,
- content = message_for_librarian,
- header = '',
- footer = '',
- attempt_times=1,
- attempt_sleeptime=10
- )
-
- if CFG_CERN_SITE:
- if status == CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED:
- message = bc_templates.tmpl_message_proposal_send_ok_cern()
- else:
- message = bc_templates.tmpl_message_request_send_ok_cern()
- else:
- if status == CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED:
- message = bc_templates.tmpl_message_proposal_send_ok_other()
- else:
- message = bc_templates.tmpl_message_request_send_ok_other()
-
- else:
- if CFG_CERN_SITE:
- message = bc_templates.tmpl_message_request_send_fail_cern("Borrower ID not found")
- else:
- message = bc_templates.tmpl_message_request_send_fail_other("Borrower ID not found")
-
- body = bc_templates.tmpl_new_request_send(message=message, ln=ln)
-
- return body
-
-
-def display_ill_form(ln=CFG_SITE_LANG):
- """
- Display ILL form
-
- @param uid: user id
- @type: int
- """
-
- body = bc_templates.tmpl_display_ill_form(infos=[], ln=ln)
-
- return body
-
-def ill_request_with_recid(recid, ln=CFG_SITE_LANG):
- """
- Display ILL form.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param uid: user id
- @type: int
- """
-
- body = bc_templates.tmpl_ill_request_with_recid(recid=recid,
- infos=[],
- ln=ln)
-
-
- return body
-
-def ill_register_request_with_recid(recid, uid, period_of_interest_from,
- period_of_interest_to, additional_comments,
- conditions, only_edition, barcode='',
- ln=CFG_SITE_LANG):
- """
- Register a new ILL request.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param uid: user id
- @type: int
-
- @param period_of_interest_from: period of interest - from(date)
- @type period_of_interest_from: string
-
- @param period_of_interest_to: period of interest - to(date)
- @type period_of_interest_to: string
- """
-
- _ = gettext_set_language(ln)
-
- # Create a dictionary.
- book_info = "{'recid': " + str(recid) + "}"
-
- user = collect_user_info(uid)
- borrower_id = db.get_borrower_id_by_email(user['email'])
-
- if borrower_id is None:
- if CFG_CERN_SITE == 1:
- result = get_user_info_from_ldap(email=user['email'])
-
- try:
- name = result['cn'][0]
- except KeyError:
- name = None
-
- try:
- email = result['mail'][0]
- except KeyError:
- email = None
-
- try:
- phone = result['telephoneNumber'][0]
- except KeyError:
- phone = None
-
- try:
- address = result['physicalDeliveryOfficeName'][0]
- except KeyError:
- address = None
-
- try:
- mailbox = result['postOfficeBox'][0]
- except KeyError:
- mailbox = None
-
- try:
- ccid = result['employeeID'][0]
- except KeyError:
- ccid = ''
-
- if address is not None:
- db.new_borrower(ccid, name, email, phone, address, mailbox, '')
- else:
- message = bc_templates.tmpl_message_request_send_fail_cern("Office address not available.")
- else:
- message = bc_templates.tmpl_message_request_send_fail_other("Office address not available.")
-
- return bc_templates.tmpl_ill_register_request_with_recid(
- message=message,
- ln=ln)
-
- address = db.get_borrower_address(user['email'])
- if not address:
- if CFG_CERN_SITE == 1:
- email = user['email']
- result = get_user_info_from_ldap(email)
-
- try:
- address = result['physicalDeliveryOfficeName'][0]
- except KeyError:
- address = None
-
- if address is not None:
- db.add_borrower_address(address, email)
- else:
- message = bc_templates.tmpl_message_request_send_fail_cern("Office address not available.")
- else:
- message = bc_templates.tmpl_message_request_send_fail_other("Office address not available.")
-
- return bc_templates.tmpl_ill_register_request_with_recid(
- message=message,
- ln=ln)
-
- if not conditions:
- infos = []
- infos.append(_("You didn't accept the ILL conditions."))
- return bc_templates.tmpl_ill_request_with_recid(recid,
- infos=infos,
- ln=ln)
-
- elif conditions == 'register_acquisition_suggestion':
- # This ILL request entry is a book proposal.
- db.ill_register_request(book_info, borrower_id,
- period_of_interest_from, period_of_interest_to,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW,
- additional_comments,
- only_edition or 'False','proposal-book', barcode=barcode)
-
- else:
- db.ill_register_request(book_info, borrower_id,
- period_of_interest_from, period_of_interest_to,
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- additional_comments,
- only_edition or 'False','book', barcode=barcode)
-
- if CFG_CERN_SITE == 1:
- message = bc_templates.tmpl_message_request_send_ok_cern()
- else:
- message = bc_templates.tmpl_message_request_send_ok_other()
-
- #Notify librarian about new ILL request.
- send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
- toaddr=CFG_BIBCIRCULATION_LOANS_EMAIL,
- subject='ILL request for books confirmation',
- content='',
- #hold_request_mail(recid=recid, borrower_id=borrower_id),
- attempt_times=1,
- attempt_sleeptime=10)
-
- return bc_templates.tmpl_ill_register_request_with_recid(
- message=message,
- ln=ln)
-
-def ill_register_request(uid, title, authors, place, publisher, year, edition,
- isbn, period_of_interest_from, period_of_interest_to,
- additional_comments, conditions, only_edition, request_type,
- barcode='', ln=CFG_SITE_LANG):
- """
- Register new ILL request. Create new record (collection: ILL Books)
-
- @param uid: user id
- @type: int
-
- @param authors: book's authors
- @type authors: string
-
- @param place: place of publication
- @type place: string
-
- @param publisher: book's publisher
- @type publisher: string
-
- @param year: year of publication
- @type year: string
-
- @param edition: book's edition
- @type edition: string
-
- @param isbn: book's isbn
- @type isbn: string
-
- @param period_of_interest_from: period of interest - from(date)
- @type period_of_interest_from: string
-
- @param period_of_interest_to: period of interest - to(date)
- @type period_of_interest_to: string
-
- @param additional_comments: comments given by the user
- @type additional_comments: string
-
- @param conditions: ILL conditions
- @type conditions: boolean
-
- @param only_edition: borrower wants only the given edition
- @type only_edition: boolean
- """
-
- _ = gettext_set_language(ln)
-
- item_info = (title, authors, place, publisher, year, edition, isbn)
- create_ill_record(item_info)
-
- book_info = {'title': title, 'authors': authors, 'place': place,
- 'publisher': publisher, 'year': year, 'edition': edition,
- 'isbn': isbn}
-
- user = collect_user_info(uid)
- borrower_id = db.get_borrower_id_by_email(user['email'])
-
- #Check if borrower is on DB.
- if borrower_id != 0:
- address = db.get_borrower_address(user['email'])
-
- #Check if borrower has an address.
- if address != 0:
-
- #Check if borrower has accepted ILL conditions.
- if conditions:
-
- #Register ILL request on crcILLREQUEST.
- db.ill_register_request(book_info, borrower_id,
- period_of_interest_from,
- period_of_interest_to,
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- additional_comments,
- only_edition or 'False', request_type,
- budget_code='', barcode=barcode)
-
- #Display confirmation message.
- message = _("Your ILL request has been registered and the " \
- "document will be sent to you via internal mail.")
-
- #Notify librarian about new ILL request.
- send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
- toaddr=CFG_BIBCIRCULATION_LOANS_EMAIL,
- subject=_('ILL request for books confirmation'),
- content="",
- attempt_times=1,
- attempt_sleeptime=10
- )
-
- #Borrower did not accept ILL conditions.
- else:
- infos = []
- infos.append(_("You didn't accept the ILL conditions."))
- body = bc_templates.tmpl_display_ill_form(infos=infos, ln=ln)
-
- #Borrower doesn't have an address.
- else:
-
- #If BibCirculation at CERN, use LDAP.
- if CFG_CERN_SITE == 1:
-
- email = user['email']
- result = get_user_info_from_ldap(email)
-
- try:
- ldap_address = result['physicalDeliveryOfficeName'][0]
- except KeyError:
- ldap_address = None
-
- # verify address
- if ldap_address is not None:
- db.add_borrower_address(ldap_address, email)
-
- db.ill_register_request(book_info, borrower_id,
- period_of_interest_from,
- period_of_interest_to,
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- additional_comments,
- only_edition or 'False',
- request_type, budget_code='', barcode=barcode)
-
- message = _("Your ILL request has been registered and" \
- " the document will be sent to you via" \
- " internal mail.")
-
-
- send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
- toaddr=CFG_BIBCIRCULATION_LOANS_EMAIL,
- subject=_('ILL request for books confirmation'),
- content="",
- attempt_times=1,
- attempt_sleeptime=10
- )
- else:
- message = _("It is not possible to validate your request.")
- message += ' ' + _("Your office address is not available.")
- message += ' ' + _("Please contact %(contact_email)s") % \
- {'contact_email': CFG_BIBCIRCULATION_LIBRARIAN_EMAIL}
-
- else:
-
- # Get information from CERN LDAP
- if CFG_CERN_SITE == 1:
- result = get_user_info_from_ldap(email=user['email'])
-
- try:
- name = result['cn'][0]
- except KeyError:
- name = None
-
- try:
- email = result['mail'][0]
- except KeyError:
- email = None
-
- try:
- phone = result['telephoneNumber'][0]
- except KeyError:
- phone = None
-
- try:
- address = result['physicalDeliveryOfficeName'][0]
- except KeyError:
- address = None
-
- try:
- mailbox = result['postOfficeBox'][0]
- except KeyError:
- mailbox = None
-
- try:
- ccid = result['employeeID'][0]
- except KeyError:
- ccid = ''
-
- # verify address
- if address is not None:
- db.new_borrower(ccid, name, email, phone, address, mailbox, '')
-
- borrower_id = db.get_borrower_id_by_email(email)
-
- db.ill_register_request(book_info, borrower_id,
- period_of_interest_from,
- period_of_interest_to,
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- additional_comments,
- only_edition or 'False',
- request_type, budget_code='', barcode=barcode)
-
- message = _("Your ILL request has been registered and" \
- " the document will be sent to you via" \
- " internal mail.")
-
- send_email(fromaddr=CFG_BIBCIRCULATION_LIBRARIAN_EMAIL,
- toaddr=CFG_BIBCIRCULATION_LOANS_EMAIL,
- subject='ILL request for books confirmation',
- content="",
- attempt_times=1,
- attempt_sleeptime=10
- )
-
- else:
- message = _("It is not possible to validate your request.")
- message += ' ' + _("Your office address is not available.")
- message += ' ' + _("Please contact %(contact_email)s") % \
- {'contact_email': CFG_BIBCIRCULATION_LIBRARIAN_EMAIL}
-
- body = bc_templates.tmpl__with_recid(message=message,
- ln=ln)
-
- return body
diff --git a/invenio/legacy/bibcirculation/cern_ldap.py b/invenio/legacy/bibcirculation/cern_ldap.py
deleted file mode 100644
index 3bc6919cf..000000000
--- a/invenio/legacy/bibcirculation/cern_ldap.py
+++ /dev/null
@@ -1,102 +0,0 @@
-# This file is part of Invenio.
-# Copyright (C) 2009, 2010, 2011, 2014 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-"""Invenio LDAP interface for BibCirculation at CERN. """
-
-from time import sleep
-from thread import get_ident
-
-from invenio.config import CFG_CERN_SITE
-try:
- import ldap
- import ldap.filter
- #from invenio.legacy.external_authentication.cern_wrapper import _cern_nice_soap_auth
- CFG_BIBCIRCULATION_HAS_LDAP = CFG_CERN_SITE
-except (ImportError, IOError):
- CFG_BIBCIRCULATION_HAS_LDAP = False
-
-# from base64 import decodestring
-
-# This is the old configuration
-# CFG_CERN_LDAP_URI = "ldaps://ldap.cern.ch:636"
-# CFG_CERN_LDAP_BIND = "n=%s,ou=users,o=cern,c=ch"
-# CFG_CERN_LDAP_BASE = "O=CERN,C=CH"
-
-CFG_CERN_LDAP_URI = "ldap://xldap.cern.ch:389"
-#CFG_CERN_LDAP_BASE = "ou=users,ou=organic units,dc=cern,dc=ch"
-
-CFG_CERN_LDAP_BASE = "dc=cern,dc=ch"
-
-# This one also works but the previous one is recommended
-# CFG_CERN_LDAP_URI = "ldap://ldap.cern.ch"
-# CFG_CERN_LDAP_BIND = "cn=%s,ou=users,ou=organic units,dc=cern,dc=ch"
-# CFG_CERN_LDAP_BASE = "O=CERN,C=CH"
-
-_ldap_connection_pool = {}
-
-def _cern_ldap_login():
- #user, password = decodestring(_cern_nice_soap_auth).split(':', 1)
- connection = ldap.initialize(CFG_CERN_LDAP_URI)
- #connection.simple_bind(CFG_CERN_LDAP_BIND % user, password)
- return connection
-
-
-def get_user_info_from_ldap(nickname="", email="", ccid=""):
- """Query the CERN LDAP server for information about a user.
- Return a dictionary of information"""
-
- try:
- connection = _ldap_connection_pool[get_ident()]
- except KeyError:
- connection = _ldap_connection_pool[get_ident()] = _cern_ldap_login()
-
- if nickname:
- query = '(displayName=%s)' % ldap.filter.escape_filter_chars(nickname)
- elif email:
- query = '(mail=%s)' % ldap.filter.escape_filter_chars(email)
- elif ccid:
- query = '(employeeID=%s)' % ldap.filter.escape_filter_chars(str(ccid))
- else:
- return {}
-
- query_filter = "(& %s (| (employeetype=primary) (employeetype=external) (employeetype=ExCern) ) )" % query
- try:
- results = connection.search_st(CFG_CERN_LDAP_BASE, ldap.SCOPE_SUBTREE,
- query_filter, timeout=5)
- except ldap.LDAPError:
- ## Mmh.. connection error? Let's reconnect at least once just in case
- sleep(1)
- connection = _ldap_connection_pool[get_ident()] = _cern_ldap_login()
- results = connection.search_st(CFG_CERN_LDAP_BASE, ldap.SCOPE_SUBTREE,
- query_filter, timeout=5)
-
- if len(results) > 1:
- ## Maybe one ExCern and primary at the same time. In this case let's give precedence to ExCern
- types = {}
- for result in results:
- if result[1]['employeeType'][0] == 'Primary' and result[1]['userAccountControl'][0] == '512':
- return result[1]
- types[result[1]['employeeType'][0]] = result[1]
- if 'ExCern' in types and 'Primary' in types:
- return types['ExCern']
- if 'Primary' in types:
- return types['Primary']
- ## Ok otherwise we just pick up something :-)
- if results:
- return results[0][1]
- else:
- return {}
diff --git a/invenio/legacy/bibcirculation/config.py b/invenio/legacy/bibcirculation/config.py
deleted file mode 100644
index 51c89b082..000000000
--- a/invenio/legacy/bibcirculation/config.py
+++ /dev/null
@@ -1,468 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011, 2013 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-"""
-bibcirculation config file
-"""
-
-from __future__ import unicode_literals
-
-__revision__ = "$Id$"
-
-from invenio.config import CFG_CERN_SITE, \
- CFG_SITE_URL
-
-from invenio.config import \
- CFG_BIBCIRCULATION_ITEM_STATUS_OPTIONAL, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, \
- CFG_BIBCIRCULATION_ITEM_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS, \
- CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW, \
- CFG_BIBCIRCULATION_ITEM_STATUS_NOT_ARRIVED, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_ITEM_STATUS_CLAIMED, \
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, \
- CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
- CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED, \
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_ILL_STATUS_RETURNED, \
- CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_INTERNAL, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_EXTERNAL, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN, \
- CFG_BIBCIRCULATION_ACQ_STATUS_NEW, \
- CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT, \
- CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED
-
-# templates used to notify borrowers
-if CFG_CERN_SITE == 1:
- CFG_BIBCIRCULATION_TEMPLATES = {
- 'OVERDUE': 'Overdue letter template (write some text)',
- 'REMINDER': 'Reminder letter template (write some text)',
- 'NOTIFICATION': 'Hello,\n'\
- 'This is an automatic email for confirming the request for a book on behalf of:\n'\
- '%s (ccid: %s, email: %s)\n'\
- '%s (%s)\n\n'\
- '\tTitle: %s\n'\
- '\tAuthor: %s\n'\
- '\tPublisher: %s\n'\
- '\tYear: %s\n'\
- '\tIsbn: %s\n\n'\
- '\tLocation: %s\n'\
- '\tLibrary: %s\n'\
- '\t%s\n\n'\
- '\tRequest date: %s\n\n'\
- 'The document will be sent to you via internal mail.\n\n'\
- 'Best regards\n',
- #user_name, ccid, user_email, address,department, mailbox, title,
- #author, publisher, year, isbn, location, library,
- #link_to_holdings_details, request_date
-
- 'ILL_RECEIVED': 'Dear colleague,\n\n'\
- 'The document you requested has been received. '\
- 'Do you want to come to the Library desk to pick it up or do you prefer we send it to you by internal mail?\n\n'\
- 'Best regards,\nCERN Library team\n',
-
- 'ILL_RECALL1': 'Dear Colleague,\n\n'\
- 'The loan period has now expired for the following document which has been borrowed for you '\
- 'from another Library.\n\n'\
- 'Please return it to the Library (either personally or by internal mail). Failure to do that could result in the library being fined. '\
- 'If you have already returned the document, please ignore this message.\n'\
- 'If you still need this title, please let us know by answering this email and we will check '\
- 'with the external library if the loan can be extended or if we can find another copy for you.\n\n'\
- 'Thank you for using our services,\n'\
- 'CERN Library Staff',
-
- 'ILL_RECALL2': 'Dear Colleague,\n\n'\
- 'The return date for the following document which has been borrowed for you from another '\
- 'library is now well past.\n\n'\
- 'According to our records you have not responded to our first recall message, so we now ask '\
- 'you to return the document to the Library without delay (either personally or by internal '\
- 'mail). Failure to do that could result in the library being fined. '\
- 'If you have already returned the document, please ignore this message.\n'\
- 'If you still need this title, please let us know by answering this email and we will check '\
- 'with the external library if the loan can be extended or if we can find another copy for you.\n\n'\
- 'Thank you for using our services,\n'\
- 'CERN Library Staff',
-
- 'ILL_RECALL3': 'Dear Colleague,\n\n'\
- 'We have already sent you two messages about the following document borrowed for you from '\
- 'another Library.\n\n'\
- 'According to our records, you have not responded to either of them. Please return the '\
- 'document to the library without delay (either personally or by internal mail) or reply to '\
- 'this mail giving any comments.'\
- 'Failure to do that could result in the Library being fined. If you have already returned the document, please ignore this message.\n\n'\
- 'Thank you for using our services,\n'\
- 'Jens Vigen, Head of CERN Library',
-
- 'PROPOSAL_NOTIFICATION': 'Dear colleague,\n\n'\
- 'We thank you for your suggestion for the Library collection: \n'\
- '\tTitle: %s\n\n'\
- 'Our team will review your proposal and will get back to you soon to inform you of our decision.\n\n'\
- 'Best regards,\nCERN Library team\n',
-
- 'PROPOSAL_ACCEPTANCE_NOTIFICATION': 'Dear colleague,\n\n'\
- 'Following your suggestion, our team has decided to acquire the book for the Library collection. '\
- 'As soon as we receive the book, we will send it on loan to you via internal mail. \n\n'\
- 'Best regards,\nCERN Library team\n',
-
- 'PROPOSAL_REFUSAL_NOTIFICATION': 'Dear colleague,\n\n'\
- 'Concerning your suggestion, we regret to inform you that our team has decided not to acquire the book '\
- 'for the Library collection for the following reason(s): \n\n'\
- 'However, if you need this document for your work, we will be able to get it on loan from another Library. '\
- 'Please let us know if this solution suits you.\n\n'\
- 'Best regards,\nCERN Library team\n',
-
- 'PURCHASE_NOTIFICATION': 'Dear colleague,\n\n'\
- 'We have received your request.\n'\
- '\tTitle: %s\n\n'\
- 'We will process your order of the document immediately and will contact you as soon as it is delivered.\n\n'\
- 'Best regards,\nCERN Library team\n',
-
- 'PURCHASE_RECEIVED_TID': 'Dear colleague,\n\n'\
- 'The document you requested has been received. '\
- 'The price is %s'\
- 'A TID will be issued for the payment. \n\n'\
- 'Do you want to come to the Library desk to pick it up or do you prefer we send it to you by internal mail?\n\n'\
- 'Best regards,\nCERN Library team\n',
-
- 'PURCHASE_RECEIVED_CASH': 'Dear colleague,\n\n'\
- 'The document you requested has been received. '\
- 'The price is %s\n\n'\
- 'Please come to the library desk to pay and pick up the document.\n\n'\
- 'Best regards,\nCERN Library team\n',
-
- 'SEND_RECALL': 'Dear Colleague,\n\n'\
- 'The loan for the document(s)\n\n'\
- 'Item information:\n\n'\
- '\t title: %s \n'\
- '\t year: %s \n'\
- '\t author(s): %s \n'\
- '\t isbn: %s \n'\
- '\t publisher: %s \n\n'\
- 'is overdue and another reader(s) is/are waiting for the document(s). '\
- 'Please return them to the Library as soon as possible.'\
- '\n\nBest regards',
- 'RECALL1': 'Dear Colleague,\n\n'\
- 'The loan period has now expired for the following Library item which you '\
- ' borrowed. Please return it to the Library (either personally or by '\
- ' internal mail) or extend the loan at:\n\n'\
- '%s/yourloans/display \n\n' % CFG_SITE_URL +
- 'If you have already done so, please ignore this message.\n\n'\
- 'Item information:\n\n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n\n'\
- 'Thank you for using our services, Library Staff \n\n\n\n'\
- 'If you are not able to update your loans via WWW or for any other '\
- 'matter concerning circulation of library material, please simply '\
- 'reply to this mail.',
- 'RECALL2': 'Dear Colleague\n\n'\
- 'The return date for the following Library item which you borrowed is now '\
- 'well past. According to our records you have not responded to our first '\
- 'recall message, so we now ask you to return the item to the Library '\
- 'without delay (either personally or by internal mail) or extend the loan at:\n\n'\
- '%s/yourloans/display \n\n' % CFG_SITE_URL +
- 'If you have already done so, please ignore this message. To send any comments, '\
- 'reply to this mail.\n\n' \
- 'Item information:\n\n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n\n'\
- 'Thank you in advance for your cooperation, CERN Library Staff',
- 'RECALL3': 'Dear Colleague,\n\n'\
- 'We have already sent you two messages about the following Library item, '\
- 'which should have been returned a long time ago. According to our records, '\
- 'you have not responded to either of them. Please return the item to the '\
- 'Library without delay (either personally or by internal mail) or reply to '\
- 'this mail giving any comments or extend the loan at:\n\n'\
- '%s/yourloans/display \n\n' % CFG_SITE_URL +
- 'If you have already returned the item, please ignore this message.\n\n'\
- 'Item information:\n\n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n\n'\
- 'Thank you in advance for your cooperation, CERN Library Staff',
- 'EMPTY': 'Please choose one template'
- }
-
-else:
- CFG_BIBCIRCULATION_TEMPLATES = {
- 'OVERDUE': 'Overdue letter template (write some text)',
- 'REMINDER': 'Reminder letter template (write some text)',
- 'NOTIFICATION': 'Hello,\n'\
- 'This is an automatic email for confirming the request for a book on behalf of:\n'\
- '%s (ccid: %s, email: %s)\n'\
- '%s (%s)\n\n'\
- '\tTitle: %s\n'\
- '\tAuthor: %s\n'\
- '\tPublisher: %s\n'\
- '\tYear: %s\n'\
- '\tIsbn: %s\n\n'\
- '\tLocation: %s\n'\
- '\tLibrary: %s\n'\
- '\t%s\n\n'\
- '\tRequest date: %s\n\n'\
- 'Best regards\n',
-
- 'ILL_RECEIVED': 'Dear colleague,\n\n'\
- 'The document you requested has been received. '\
- 'Do you want to come to the Library desk to pick it up or do you prefer we send it to you by internal mail?\n\n'\
- 'Best regards,\nLibrary team\n',
-
- 'ILL_RECALL1': 'Dear Colleague,\n\n'\
- 'The loan period has now expired for the following document which has been borrowed for you '\
- 'from another Library.\n\n'\
- 'Please return it to the Library (either personally or by internal mail). Failure to do that could result in the library being fined. '\
- 'If you have already returned the document, please ignore this message.\n'\
- 'If you still need this title, please let us know by answering this email and we will check '\
- 'with the external library if the loan can be extended or if we can find another copy for you.\n\n'\
- 'Thank you for using our services,\n'\
- 'Library Staff',
-
- 'ILL_RECALL2': 'Dear Colleague,\n\n'\
- 'The return date for the following document which has been borrowed for you from another '\
- 'library is now well past.\n\n'\
- 'According to our records you have not responded to our first recall message, so we now ask '\
- 'you to return the document to the Library without delay (either personally or by internal '\
- 'mail). Failure to do that could result in the library being fined. '\
- 'If you have already returned the document, please ignore this message.\n'\
- 'If you still need this title, please let us know by answering this email and we will check '\
- 'with the external library if the loan can be extended or if we can find another copy for you.\n\n'\
- 'Thank you for using our services,\n'\
- 'Library Staff',
-
- 'ILL_RECALL3': 'Dear Colleague,\n\n'\
- 'We have already sent you two messages about the following document borrowed for you from '\
- 'another Library.\n\n'\
- 'According to our records, you have not responded to either of them. Please return the '\
- 'document to the library without delay (either personally or by internal mail) or reply to '\
- 'this mail giving any comments. '\
- 'Failure to do that could result in the Library being fined. If you have already returned the document, please ignore this message.\n\n'\
- 'Thank you for using our services,\n\n'\
- 'Jens Vigen, Head of Library',
-
- 'PURCHASE_NOTIFICATION': 'Dear colleague,\n\n'\
- 'We have received your request.\n'\
- '\tTitle: %s\n\n'\
- 'We will process your order of the document immediately and will contact you as soon as it is delivered.\n\n'\
- 'Best regards,\nLibrary team\n',
-
- 'PURCHASE_RECEIVED_TID': 'Dear colleague,\n\n'\
- 'The document you requested has been received. '\
- 'The price is %s\n\n'\
- 'A TID will be issued for the payment. \n\n'\
- 'Do you want to come to the Library desk to pick it up or do you prefer we send it to you by internal mail?\n\n'\
- 'Best regards,\nLibrary team\n',
-
- 'PURCHASE_RECEIVED_CASH': 'Dear colleague,\n\n'\
- 'The document you requested has been received. '\
- 'The price is %s\n\n'\
- 'Please come to the library desk to pay and pick up the document.\n\n'\
- 'Best regards,\nLibrary team\n',
-
- 'PROPOSAL_NOTIFICATION': 'Dear colleague,\n\n'\
- 'We thank you for your suggestion for the Library collection: \n'\
- '\tTitle: %s\n\n'\
- 'Our team will review your proposal and will get back to you soon to inform you of our decision.\n\n'\
- 'Best regards,\nLibrary team\n',
-
- 'PROPOSAL_ACCEPTANCE_NOTIFICATION': 'Dear colleague,\n\n'\
- 'Following your suggestion, our team has decided to acquire the book for the Library collection. '\
- 'As soon as we receive the book, we will send it on loan to you via internal mail. \n\n'\
- 'Best regards,\nLibrary team\n',
-
- 'PROPOSAL_REFUSAL_NOTIFICATION': 'Dear colleague,\n\n'\
- 'Concerning your suggestion, we regret to inform you that our team has decided not to acquire the book '\
- 'for the Library collection for the following reason(s): \n\n'\
- 'However, if you need this document for your work, we will be able to get it on loan from another Library. '\
- 'Please let us know if this solution suits you.\n\n'\
- 'Best regards,\nLibrary team\n',
-
- 'SEND_RECALL': 'Dear Colleague,\n\n'\
- 'The loan for the document(s)\n\n'\
- 'Item information:\n\n'\
- '\t title: %s \n'\
- '\t year: %s \n'\
- '\t author(s): %s \n'\
- '\t isbn: %s \n'\
- '\t publisher: %s \n\n'\
- 'is overdue and another reader(s) is/are waiting for the document(s). '\
- 'Please return them to the Library as soon as possible.'\
- '\n\nBest regards',
- 'RECALL1': 'Dear Colleague,\n\n'\
- 'The loan period has now expired for the following Library item which you '\
- ' borrowed. Please return it to the Library (either personally or by '\
- ' internal mail) or extend the loan at:\n\n'\
- '%s/yourloans/display \n\n' % CFG_SITE_URL +
- 'If you have already done so, please ignore this message.\n\n'\
- 'Item information:\n\n'\
- '\t title: %s \n'\
- '\t year: %s \n'\
- '\t author(s): %s \n'\
- '\t isbn: %s \n'\
- '\t publisher: %s \n\n'\
- 'Thank you for using our services, Library Staff \n\n\n\n'\
- 'If you are not able to update your loans via WWW or for any other ' \
- 'matter concerning circulation of library material, please simply ' \
- 'reply to this mail.',
- 'RECALL2': 'Dear Colleague\n\n'\
- 'The return date for the following Library item which you borrowed is now ' \
- 'well past. According to our records you have not responded to our first ' \
- 'recall message, so we now ask you to return the item to the Library '\
- 'without delay (either personally or by internal mail) or extend the loan at:\n\n'\
- '%s/yourloans/display \n\n' % CFG_SITE_URL +
- 'If you have already done so, please ignore this message. To send any comments, '\
- 'reply to this mail. \n' \
- 'Item information:\n\n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n\n'\
- 'Thank you in advance for your cooperation, Library Staff',
- 'RECALL3': 'Dear Colleague,\n\n'\
- 'We have already sent you two messages about the following Library item, '\
- 'which should have been returned a long time ago. According to our records, '\
- 'you have not responded to either of them. Please return the item to the '\
- 'Library without delay (either personally or by internal mail) or reply to '\
- 'this mail giving any comments or extend the loan at:\n\n'\
- '%s/yourloans/display \n\n' % CFG_SITE_URL +
- 'If you have already returned the item, please ignore this message.\n\n'\
- 'Item information:\n\n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n'\
- '%s \n\n'\
- 'Thank you in advance for your cooperation, Library Staff',
- 'EMPTY': 'Please choose one template'
- }
-
-if CFG_CERN_SITE == 1:
- CFG_BIBCIRCULATION_ILLS_EMAIL = 'CERN External loans'
- CFG_BIBCIRCULATION_LIBRARIAN_EMAIL = 'CERN Library Desk'
- CFG_BIBCIRCULATION_LOANS_EMAIL = 'CERN Lib loans'
-else:
- CFG_BIBCIRCULATION_ILLS_EMAIL = 'Atlantis Library'
- CFG_BIBCIRCULATION_LIBRARIAN_EMAIL = 'Atlantis Library'
- CFG_BIBCIRCULATION_LOANS_EMAIL = CFG_BIBCIRCULATION_LIBRARIAN_EMAIL
-
-if CFG_CERN_SITE:
- CFG_BIBCIRCULATION_HOLIDAYS = ['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
- '2013-03-29', '2013-04-01', '2013-05-01', '2013-05-09',
- '2013-05-20', '2013-09-05', '2013-12-23', '2013-12-24',
- '2013-12-25', '2013-12-26', '2013-12-27', '2013-12-30',
- '2013-12-31', '2014-01-01', '2014-01-02', '2014-01-03']
-
-else:
- CFG_BIBCIRCULATION_HOLIDAYS = []
-
-CFG_BIBCIRCULATION_WORKING_DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
-
-# You can edit this variable if you want to have customized statuses
-
-
-CFG_BIBCIRCULATION_ITEM_STATUS = CFG_BIBCIRCULATION_ITEM_STATUS_OPTIONAL + \
- [CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF,
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_ITEM_STATUS_IN_PROCESS,
- CFG_BIBCIRCULATION_ITEM_STATUS_UNDER_REVIEW,
- CFG_BIBCIRCULATION_ITEM_STATUS_CANCELLED,
- CFG_BIBCIRCULATION_ITEM_STATUS_NOT_ARRIVED,
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER,
- CFG_BIBCIRCULATION_ITEM_STATUS_CLAIMED]
-
-CFG_BIBCIRCULATION_LOAN_STATUS = [CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED,
- CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED]
-
-CFG_BIBCIRCULATION_REQUEST_STATUS = [CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED,
- CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED]
-
-CFG_BIBCIRCULATION_ILL_STATUS = [CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED,
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_ILL_STATUS_RETURNED,
- CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED,
- CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED]
-
-CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD = ['4 weeks', '1 week', 'Reference']
-
-CFG_BIBCIRCULATION_ACQ_TYPE = ['acq-book', 'acq-standard']
-
-CFG_BIBCIRCULATION_PROPOSAL_TYPE = ['proposal-book']
-
-CFG_BIBCIRCULATION_COLLECTION = ['Monograph', 'Reference', 'Archives',
- 'Library', 'Conference', 'LSL Depot',
- 'Oversize', 'Official', 'Pamphlet', 'CDROM',
- 'Standards', 'Video & Trainings', 'Periodical']
-
-AMZ_ACQUISITION_IDENTIFIER_TAG = '595__a'
-
-AMZ_BOOK_PUBLICATION_DATE_TAG = '269__c'
-
-#The library whose id will be used by default at the time inserting a
-#dummy/temporary item.
-CFG_BIBCIRCULATION_DEFAULT_LIBRARY_ID = 6
-
-CFG_BIBCIRCULATION_PROPOSAL_STATUS = [CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED]
-
-# move these 2 to local config file and delete from here
-#CFG_BIBCIRCULATION_AMAZON_ACCESS_KEY = 1T6P3M3TDMW9HWJ212R2
-#CFG_BIBCIRCULATION_ITEM_STATUS_OPTIONAL = missing, out of print, in binding, untraceable, order delayed, not published, claimed
-
-CFG_BIBCIRCULATION_LIBRARY_TYPE = [CFG_BIBCIRCULATION_LIBRARY_TYPE_INTERNAL,
- CFG_BIBCIRCULATION_LIBRARY_TYPE_EXTERNAL,
- CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN,
- CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN]
-
-CFG_BIBCIRCULATION_ACQ_STATUS = [CFG_BIBCIRCULATION_ACQ_STATUS_NEW,
- CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER,
- CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT,
- CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED,
- CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED]
diff --git a/invenio/legacy/bibcirculation/daemon.py b/invenio/legacy/bibcirculation/daemon.py
deleted file mode 100644
index a124763c4..000000000
--- a/invenio/legacy/bibcirculation/daemon.py
+++ /dev/null
@@ -1,272 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011, 2013 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-"""
-BibCirculation daemon.
-"""
-
-__revision__ = "$Id$"
-
-import sys
-import time
-from invenio.legacy.dbquery import run_sql
-from invenio.legacy.bibsched.bibtask import task_init, \
- task_sleep_now_if_required, \
- task_update_progress, \
- task_set_option, \
- task_get_option, \
- write_message
-from invenio.ext.email import send_email
-import invenio.legacy.bibcirculation.db_layer as db
-from invenio.legacy.bibcirculation.config import CFG_BIBCIRCULATION_TEMPLATES, \
- CFG_BIBCIRCULATION_LOANS_EMAIL, \
- CFG_BIBCIRCULATION_ILLS_EMAIL, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED
-
-from invenio.legacy.bibcirculation.utils import generate_email_body, \
- book_title_from_MARC, \
- update_user_info_from_ldap, \
- update_requests_statuses, \
- looks_like_dictionary
-import datetime
-
-def task_submit_elaborate_specific_parameter(key, value, opts, args):
- """ Given the string key, checks its meaning and returns True if
- has elaborated the key.
- Possible keys:
- """
- write_message(key)
- if key in ('-o', '--overdue-letters'):
- task_set_option('overdue-letters', True)
- elif key in ('-b', '--update-borrowers'):
- task_set_option('update-borrowers', True)
- elif key in ('-r', '--update-requests'):
- task_set_option('update-requests', True)
- else:
- return False
- return True
-
-def update_expired_loan(loan_id, ill=0):
- """
- Update status, number of overdue letters and the date of overdue letter
-
- @param loan_id: identify the loan. Primary key of crcLOAN.
- @type loan_id: int
- """
-
- if ill:
- run_sql("""update crcILLREQUEST
- set overdue_letter_number=overdue_letter_number+1,
- overdue_letter_date=NOW()
- where id=%s
- """, (loan_id,))
- else:
- run_sql("""update crcLOAN
- set overdue_letter_number=overdue_letter_number+1,
- status=%s,
- overdue_letter_date=NOW()
- where id=%s
- """, (CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED,
- loan_id))
-
-def send_overdue_letter(borrower_id, from_address, subject, content):
- """
- Send an overdue letter
-
- @param borrower_id: identify the borrower. Primary key of crcBORROWER.
- @type borrower_id: int
-
- @param subject: subject of the overdue letter
- @type subject: string
- """
-
- to_borrower = db.get_borrower_email(borrower_id)
-
- send_email(fromaddr=from_address,
- toaddr=to_borrower,
- subject=subject,
- content=content,
- header='',
- footer='',
- attempt_times=1,
- attempt_sleeptime=10
- )
- return 1
-
-def must_send_second_recall(date_letters):
- """
- @param date_letters: date of the last letter.
- @type date_letters: string
-
- @return boolean
- """
- today = datetime.date.today()
-
- time_tuple = time.strptime(date_letters, "%Y-%m-%d")
- #datetime.strptime(date_letters, "%Y-%m-%d") doesn't work (only on 2.5).
- tmp_date = datetime.datetime(*time_tuple[0:3]) + datetime.timedelta(weeks=1)
-
- try:
- if tmp_date.strftime("%Y-%m-%d") <= today.strftime("%Y-%m-%d"):
- return True
- else:
- return False
- except ValueError:
- return False
-
-def must_send_third_recall(date_letters):
- """
- @param date_letters: date of the last letter.
- @type date_letters: string
-
- @return boolean
- """
- today = datetime.date.today()
-
- time_tuple = time.strptime(date_letters, "%Y-%m-%d")
- #datetime.strptime(date_letters, "%Y-%m-%d") doesn't work (only on Python 2.5)
- tmp_date = datetime.datetime(*time_tuple[0:3]) + datetime.timedelta(days=3)
-
- try:
- if tmp_date.strftime("%Y-%m-%d") <= today.strftime("%Y-%m-%d"):
- return True
- else:
- return False
- except ValueError:
- return False
-
-def task_run_core():
- """
- Run daemon
- """
- write_message("Starting...")
- if task_get_option("update-borrowers"):
- write_message("Started update-borrowers")
- list_of_borrowers = db.get_all_borrowers()
- total_borrowers = len(list_of_borrowers)
-
- for done, borrower in enumerate(list_of_borrowers):
- user_id = borrower[0]
- update_user_info_from_ldap(user_id)
- if done % 10 == 0:
- task_update_progress("Borrower: updated %d out of %d." % (done, total_borrowers))
- task_sleep_now_if_required(can_stop_too=True)
- task_update_progress("Borrower: updated %d out of %d." % (done+1, total_borrowers))
- write_message("Updated %d out of %d total borrowers" % (done+1, total_borrowers))
-
- if task_get_option("update-requests"):
- write_message("Started update-requests")
- list_of_reqs = db.get_loan_request_by_status(CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
-
- for (_request_id, recid, bc, _name, borrower_id, _library, _location,
- _date_from, _date_to, _request_date) in list_of_reqs:
- description = db.get_item_description(bc)
- list_of_barcodes = db.get_barcodes(recid, description)
- for barcode in list_of_barcodes:
- update_requests_statuses(barcode)
- task_sleep_now_if_required(can_stop_too=True)
- task_update_progress("Requests due updated from 'waiting' to 'pending'.")
- write_message("Requests due updated from 'waiting' to 'pending'.")
-
- if task_get_option("overdue-letters"):
- write_message("Started overdue-letters")
- expired_loans = db.get_all_expired_loans()
- total_expired_loans = len(expired_loans)
-
- for done, (borrower_id, _bor_name, recid, _barcode, _loaned_on,
- _due_date, _number_of_renewals, number_of_letters,
- date_letters, _notes, loan_id) in enumerate(expired_loans):
-
- number_of_letters=int(number_of_letters)
-
- content = ''
- if number_of_letters == 0:
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL1'], loan_id)
- elif number_of_letters == 1 and must_send_second_recall(date_letters):
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL2'], loan_id)
- elif number_of_letters == 2 and must_send_third_recall(date_letters):
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL3'], loan_id)
- elif number_of_letters >= 3 and must_send_third_recall(date_letters):
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['RECALL3'], loan_id)
-
- if content != '':
- title = book_title_from_MARC(recid)
- subject = "LOAN RECALL: " + title
-
- update_expired_loan(loan_id)
- send_overdue_letter(borrower_id, CFG_BIBCIRCULATION_LOANS_EMAIL, subject, content)
-
- if done % 10 == 0:
- task_update_progress("Loan recall: sent %d out of %d." % (done, total_expired_loans))
- task_sleep_now_if_required(can_stop_too=True)
- task_update_progress("Loan recall: processed %d out of %d expires loans." % (done+1, total_expired_loans))
- write_message("Processed %d out of %d expired loans." % (done+1, total_expired_loans))
-
- # Recalls for expired ILLs
- write_message("Started overdue-letters for Inter Library Loans")
- expired_ills = db.get_all_expired_ills()
- total_expired_ills = len(expired_ills)
-
- for done, (ill_id, borrower_id, item_info, number_of_letters,
- date_letters) in enumerate(expired_ills):
-
- number_of_letters=int(number_of_letters)
-
- content = ''
- if number_of_letters == 0:
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['ILL_RECALL1'], ill_id, ill=1)
- elif number_of_letters == 1 and must_send_second_recall(date_letters):
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['ILL_RECALL2'], ill_id, ill=1)
- elif number_of_letters == 2 and must_send_third_recall(date_letters):
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['ILL_RECALL3'], ill_id, ill=1)
- elif number_of_letters >= 3 and must_send_third_recall(date_letters):
- content = generate_email_body(CFG_BIBCIRCULATION_TEMPLATES['ILL_RECALL3'], ill_id, ill=1)
-
- if content != '' and looks_like_dictionary(item_info):
- item_info = eval(item_info)
- if 'title' in item_info:
- book_title = item_info['title']
- subject = "ILL RECALL: " + str(book_title)
- update_expired_loan(loan_id=ill_id, ill=1)
- send_overdue_letter(borrower_id, CFG_BIBCIRCULATION_ILLS_EMAIL, subject, content)
- if done % 10 == 0:
- task_update_progress("ILL recall: sent %d out of %d." % (done, total_expired_ills))
- task_sleep_now_if_required(can_stop_too=True)
- task_update_progress("ILL recall: processed %d out of %d expired ills." % (done+1, total_expired_ills))
- write_message("Processed %d out of %d expired ills." % (done+1, total_expired_ills))
-
- return 1
-
-def main():
-
- task_init(authorization_action='runbibcircd',
- authorization_msg="BibCirculation Task Submission",
- help_specific_usage="""-o, --overdue-letters\tCheck overdue loans and send recall emails if necessary.\n
--b, --update-borrowers\tUpdate borrowers information from ldap.\n
--r, --update-requests\tUpdate pending requests of users\n\n""",
- description="""Example: %s -u admin \n\n""" % (sys.argv[0]),
- specific_params=("obr", ["overdue-letters", "update-borrowers", "update-requests"]),
- task_submit_elaborate_specific_parameter_fnc=task_submit_elaborate_specific_parameter,
- version=__revision__,
- task_run_fnc = task_run_core
- )
-
-if __name__ == '__main__':
- main()
diff --git a/invenio/legacy/bibcirculation/db_layer.py b/invenio/legacy/bibcirculation/db_layer.py
deleted file mode 100644
index a4239c6d7..000000000
--- a/invenio/legacy/bibcirculation/db_layer.py
+++ /dev/null
@@ -1,2921 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011, 2013 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-"""
- Every db-related function of the bibcirculation module.
- The methods are positioned by grouping into logical
- categories ('Loans', 'Returns', 'Loan requests', 'ILLs',
- 'Libraries', 'Vendors' ...)
- This positioning should be maintained and when necessary,
- improved for readability, as and when additional methods are
- added. When applicable, methods should be renamed, refactored
- and appropriate documentation added.
-
- Currently, the same table 'crcILLREQUEST' is used for the ILLs,
- purchases as well as proposals.
-
-"""
-
-__revision__ = "$Id$"
-
-from invenio.legacy.dbquery import run_sql
-from invenio.legacy.bibcirculation.config import \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, \
- CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_DONE, \
- CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
- CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED, \
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_ILL_STATUS_RETURNED, \
- CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_ACQ_STATUS_NEW, \
- CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT, \
- CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_INTERNAL, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_EXTERNAL, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN
-
-
-
-
-###
-### Loan Requests related functions ###
-###
-
-
-
-
-def new_hold_request(borrower_id, recid, barcode, date_from, date_to, status):
- """
- Create a new hold request.
-
- @param borrower_id: identify the borrower. Primary key of crcBORROWER.
- @type borrower_id: int
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param barcode: identify the item. Primary key of crcITEM.
- @type barcode: string
-
- @param date_from: begining of the period of interest.
- @type date_from: string
-
- @param date_to: end of the period of interest.
- @type date_to: string
-
- @param status: hold request status.
- @type status: string
- """
- res = run_sql("""INSERT INTO crcLOANREQUEST(id_crcBORROWER,
- id_bibrec,
- barcode,
- period_of_interest_from,
- period_of_interest_to,
- status,
- request_date)
- VALUES (%s, %s, %s, %s, %s, %s, NOW())
- """, (borrower_id, recid, barcode, date_from,
- date_to, status))
-
- return res
-
-def has_loan_request(borrower_id, recid, ill=0):
-
- from invenio.legacy.bibcirculation.utils import looks_like_dictionary
-
- if ill == 0:
- return run_sql("""
- SELECT id
- FROM crcLOANREQUEST
- WHERE id_crcBORROWER=%s and
- id_bibrec=%s and
- status in (%s, %s, %s)""",
- (borrower_id, recid,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED
- )) != ()
- else:
- res = run_sql("""
- SELECT item_info
- FROM crcILLREQUEST
- WHERE id_crcBORROWER=%s and
- request_type=%s and
- status in (%s, %s, %s)""",
- (borrower_id, 'book',
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED,
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN
- ))
- for record in res:
- if looks_like_dictionary(record[0]):
- item_info = eval(record[0])
- try:
- if str(recid) == str(item_info['recid']): return True
- except KeyError:
- continue
- return False
-
-def is_requested(barcode):
-
- res = run_sql("""SELECT id
- FROM crcLOANREQUEST
- WHERE barcode=%s
- AND (status = %s or status = %s)
- """, (barcode,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING))
-
- try:
- return res
- except IndexError:
- return None
-
-def is_doc_already_requested(recid, barcode, borrower_id):
- """
- Check if the borrower already has a waiting/pending loan request or
- a proposal, or a loan on some item of the record.
- """
- multi_volume_book = False
- if get_item_description(barcode).strip() not in ('', '-'):
- multi_volume_book = True
-
- reqs_on_rec = run_sql("""SELECT id, barcode
- FROM crcLOANREQUEST
- WHERE id_bibrec=%s
- AND id_crcBORROWER = %s
- AND status in (%s, %s, %s)
- """, (recid, borrower_id,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED,
- ))
- if reqs_on_rec != () and not multi_volume_book: return True
- for req in reqs_on_rec:
- if req[1] == barcode: return True
-
- loans_on_rec = run_sql("""SELECT id, barcode
- FROM crcLOAN
- WHERE id_bibrec=%s
- AND id_crcBORROWER = %s
- AND status in (%s, %s)
- """, (recid, borrower_id,
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED
- ))
- if loans_on_rec != () and not multi_volume_book: return True
- for loan in loans_on_rec:
- if loan[1] == barcode: return True
-
- return False
-
-def cancel_request(request_id, borrower_id=None, recid=None):
- """
- Cancel a hold request identified with the request_id. If it is None,
- cancel the hold request identified with (borrower_id, recid), if both
- are not None.
- """
- if request_id:
- run_sql("""UPDATE crcLOANREQUEST
- SET status=%s
- WHERE id=%s
- """, (CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED, request_id))
-
- elif borrower_id and recid:
- run_sql("""UPDATE crcLOANREQUEST
- SET status=%s
- WHERE id_crcBORROWER=%s and
- id_bibrec=%s and
- status in (%s, %s, %s)""",
- (CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED,
- borrower_id, recid,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING
- ))
-
-def tag_requests_as_done(user_id, barcode=None, recid=None):
-
- if barcode:
- run_sql("""UPDATE crcLOANREQUEST
- SET status=%s
- WHERE barcode=%s
- and id_crcBORROWER=%s
- """, (CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
- barcode, user_id))
-
- elif recid:
- run_sql("""UPDATE crcLOANREQUEST
- SET status=%s
- WHERE id_bibrec=%s
- and id_crcBORROWER=%s
- """, (CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
- recid, user_id))
-
-
-def get_requests(recid, description, status):
- """
- Get the number of requests of a record.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param status: identify the status.
- @type status: string
-
- @return number of requests (int)
- """
- # Get all the barcodes of the items belonging to the same record and with the same description.
- barcodes = tuple(rec[0] for rec in run_sql("""SELECT barcode FROM crcITEM WHERE description=%s
- AND id_bibrec=%s""", (description, recid)))
-
- query = """SELECT id, DATE_FORMAT(period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(request_date,'%%Y-%%m-%%d')
- FROM crcLOANREQUEST
- WHERE period_of_interest_from <= NOW()
- AND period_of_interest_to >= NOW()
- AND id_bibrec=%s
- AND status='%s' """% (recid, status)
-
-
- if len(barcodes) == 1:
- query += """AND barcode='%s' ORDER BY request_date""" % barcodes[0]
- elif len(barcodes) > 1:
- query += """AND barcode in %s ORDER BY request_date""" % (barcodes,)
- else:
- query += """ORDER BY request_date"""
-
- return run_sql(query)
-
-def get_all_requests():
- """
- Retrieve all requests.
- """
- res = run_sql("""SELECT lr.id,
- bor.id,
- bor.name,
- lr.id_bibrec,
- lr.status,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr,
- crcBORROWER bor
- WHERE bor.id = lr.id_crcBORROWER
- AND (lr.status=%s OR lr.status=%s)
- AND lr.period_of_interest_to >= CURDATE()
- ORDER BY lr.request_date
- """, (CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING))
-
- return res
-
-def get_loan_request_details(req_id):
-
- res = run_sql("""SELECT lr.id_bibrec,
- bor.name,
- bor.id,
- lib.name,
- it.location,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr,
- crcBORROWER bor,
- crcITEM it,
- crcLIBRARY lib
- WHERE lr.id_crcBORROWER=bor.id AND it.barcode=lr.barcode
- AND lib.id = it.id_crcLIBRARY
- AND lr.id=%s
- """, (req_id, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def get_loan_request_by_status(status):
-
- query = """SELECT DISTINCT
- lr.id,
- lr.id_bibrec,
- lr.barcode,
- bor.name,
- bor.id,
- lib.name,
- it.location,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr,
- crcBORROWER bor,
- crcITEM it,
- crcLIBRARY lib
- WHERE lr.id_crcBORROWER=bor.id AND it.barcode=lr.barcode AND
- lib.id = it.id_crcLIBRARY AND lr.status=%s
- AND lr.period_of_interest_from <= NOW()
- AND lr.period_of_interest_to >= NOW()
- ORDER BY lr.request_date"""
-
- res = run_sql(query , (status, ))
- return res
-
-def get_requested_barcode(request_id):
- """
- request_id: identify the hold request. It is also the primary key
- of the table crcLOANREQUEST.
- """
-
- res = run_sql("""SELECT barcode
- FROM crcLOANREQUEST
- WHERE id=%s""",
- (request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_loan_request_status(new_status, request_id=None,
- barcode=None, borrower_id=None):
- """
- Update the hold request(s) status(es) for an item with the request_id/barcode.
- If the status of the hold request on an item with a particular barcode and
- by a particular borrrower is to be modified, specify the borrower_id too.
- """
-
- if request_id:
- return int(run_sql("""UPDATE crcLOANREQUEST
- SET status=%s
- WHERE id=%s""",
- (new_status, request_id)))
-
- elif barcode and borrower_id:
- return int(run_sql("""UPDATE crcLOANREQUEST
- SET status=%s
- WHERE barcode=%s
- AND id_crcBORROWER=%s""",
- (new_status, barcode, borrower_id)))
-
- elif barcode:
- return int(run_sql("""UPDATE crcLOANREQUEST
- SET status=%s
- WHERE barcode=%s""",
- (new_status, barcode)))
-
-def update_request_barcode(barcode, request_id):
- """
- Update the barcode of a hold request.
- barcode: new barcode (after update). It is also the
- primary key of the crcITEM table.
- request_id: identify the hold request who will be
- cancelled. It is also the primary key of
- the crcLOANREQUEST table.
- """
-
- run_sql("""UPDATE crcLOANREQUEST
- set barcode = %s
- WHERE id = %s
- """, (barcode, request_id))
-
-def get_pending_loan_request(recid, description):
- """
- Get the pending request for a given recid.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param description: Gives the details like volume(if any), etc... of a particular
- item in the record.
- @type description: string
-
- @return list with request_id, borrower_name, recid, status,
- period_of_interest (FROM and to) and request_date.
- """
-
- # Get all the barcodes of the items belonging to the same record and with the same description.
- barcodes = tuple(rec[0] for rec in run_sql("""SELECT barcode FROM crcITEM WHERE description=%s
- AND id_bibrec=%s""", (description, recid)))
-
- query = """SELECT lr.id,
- bor.name,
- lr.id_bibrec,
- lr.status,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr,
- crcBORROWER bor
- WHERE lr.id_crcBORROWER=bor.id
- AND lr.status='%s'
- AND lr.id_bibrec=%s
- AND lr.period_of_interest_from <= NOW()
- AND lr.period_of_interest_to >= NOW() """% \
- (CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING, recid)
-
-
- if len(barcodes) == 1:
- query += """AND lr.barcode='%s' ORDER BY lr.request_date""" % barcodes[0]
- elif len(barcodes) > 1:
- query += """AND lr.barcode in %s ORDER BY lr.request_date""" % (barcodes,)
- else:
- query += """ORDER BY lr.request_date"""
-
- return run_sql(query)
-
-def get_queue_request(recid, item_description):
- """
- recid: identify the record. It is also the primary key of
- the table bibrec.
- item_description: Gives the details like volume(if any), etc... of a particular
- item in the record.
- """
-
- # Get all the barcodes of the items belonging to the same record and with the same description.
- barcodes = tuple(rec[0] for rec in run_sql("""SELECT barcode FROM crcITEM WHERE description=%s
- AND id_bibrec=%s""", (item_description, recid)))
-
- query = """SELECT id_crcBORROWER,
- status,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d')
- FROM crcLOANREQUEST
- WHERE id_bibrec=%s
- AND (status='%s' or status='%s')
- AND period_of_interest_from <= NOW()
- AND period_of_interest_to >= NOW() """% \
- (recid, CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,\
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING)
-
-
- if len(barcodes) == 1:
- query += """AND barcode='%s' ORDER BY request_date""" % barcodes[0]
- elif len(barcodes) > 1:
- query += """AND barcode in %s ORDER BY request_date""" % (barcodes,)
- else:
- query += """ORDER BY request_date"""
-
- return run_sql(query)
-
-def get_request_recid(request_id):
- """
- Get the recid of a given request_id
-
- @param request_id: identify the (hold) request. Primary key of crcLOANREQUEST.
- @type request_id: int
-
- @return recid
- """
- res = run_sql(""" SELECT id_bibrec
- FROM crcLOANREQUEST
- WHERE id=%s
- """, (request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_request_barcode(request_id):
- """
- Get the barcode of a given request_id
-
- @param request_id: identify the (hold) request. Primary key of crcLOANREQUEST.
- @type request_id: int
-
- @return barcode
- """
- res = run_sql(""" SELECT barcode
- FROM crcLOANREQUEST
- WHERE id=%s
- """, (request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_request_borrower_id(request_id):
- """
- Get the borrower_id of a given request_id
-
- @param request_id: identify the (hold) request. Primary key of crcLOANREQUEST.
- @type request_id: int
-
- @return borrower_id
- """
-
- res = run_sql(""" SELECT id_crcBORROWER
- FROM crcLOANREQUEST
- WHERE id=%s
- """, (request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_number_requests_per_copy(barcode):
- """
- barcode: identify the item. It is the primary key of the table
- crcITEM.
- """
-
- res = run_sql("""SELECT count(barcode)
- FROM crcLOANREQUEST
- WHERE barcode=%s and
- (status != %s and status != %s)""",
- (barcode, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
- CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED))
-
- return res[0][0]
-
-def get_pdf_request_data(status):
- """
- status: request status.
- """
- res = run_sql("""SELECT DISTINCT
- lr.id_bibrec,
- bor.name,
- lib.name,
- it.location,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr,
- crcBORROWER bor,
- crcITEM it,
- crcLIBRARY lib
- WHERE lr.id_crcBORROWER=bor.id AND
- it.id_bibrec=lr.id_bibrec AND
- lib.id = it.id_crcLIBRARY AND
- lr.status=%s;
- """, (status,))
- return res
-
-
-
-
-###
-### Loans related functions ###
-###
-
-
-
-
-def loan_on_desk_confirm(barcode, borrower_id):
- """
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- res = run_sql("""SELECT it.id_bibrec, bor.name
- FROM crcITEM it, crcBORROWER bor
- WHERE it.barcode=%s and bor.id=%s
- """, (barcode, borrower_id))
-
- return res
-
-def is_on_loan(barcode):
-
- res = run_sql("""SELECT id
- FROM crcLOAN
- WHERE barcode=%s
- AND (status=%s or status=%s)
- """, (barcode,
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
-
- if res:
- return True
- else:
- return False
-
-def is_item_on_loan(barcode):
- """
- Check if an item is on loan.
-
- @param barcode: identify the item. It is the primary key of the table crcITEM.
- """
-
- res = run_sql("""SELECT id
- FROM crcLOAN
- WHERE (status=%s or status=%s)
- and barcode=%s""",
- (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, barcode))
-
- try:
- return res[0][0]
- except IndexError:
- return None
-
-def get_loan_infos(loan_id):
- """
- loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
- """
-
- res = run_sql("""SELECT l.id_bibrec,
- l.barcode,
- DATE_FORMAT(l.loaned_on, '%%Y-%%m-%%d'),
- DATE_FORMAT(l.due_date, '%%Y-%%m-%%d'),
- l.status,
- it.loan_period,
- it.status
- FROM crcLOAN l, crcITEM it, crcLOANREQUEST lr
- WHERE l.barcode=it.barcode and
- l.id=%s""",
- (loan_id, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def get_borrower_id(barcode):
- """
- Get the borrower id who is associated to a loan.
-
- @param barcode: identify the item. Primary key of crcITEM.
- @type barcode: string
-
- @return borrower_id or None
- """
- res = run_sql(""" SELECT id_crcBORROWER
- FROM crcLOAN
- WHERE barcode=%s and
- (status=%s or status=%s)""",
- (barcode, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
- try:
- return res[0][0]
- except IndexError:
- return None
-
-def get_borrower_loans_barcodes(borrower_id):
- """
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
-
- res = run_sql("""SELECT barcode
- FROM crcLOAN
- WHERE id_crcBORROWER=%s
- AND (status=%s OR status=%s)
- """,
- (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
-
- list_of_barcodes = []
- for bc in res:
- list_of_barcodes.append(bc[0])
-
- return list_of_barcodes
-
-def new_loan(borrower_id, recid, barcode,
- due_date, status, loan_type, notes):
- """
- Create a new loan.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- recid: identify the record. It is also the primary key of
- the table bibrec.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- loaned_on: loan date.
-
- due_date: due date.
-
- status: loan status.
-
- loan_type: loan type(normal, ILL, etc...)
-
- notes: loan notes.
- """
-
- res = run_sql(""" insert into crcLOAN (id_crcBORROWER, id_bibrec,
- barcode, loaned_on, due_date,
- status, type, notes)
- values(%s, %s, %s, NOW(), %s, %s ,%s, %s)
- """, (borrower_id, recid, barcode, due_date,
- status, loan_type, str(notes)))
-
- res = run_sql(""" UPDATE crcITEM
- SET status=%s
- WHERE barcode=%s""", (status, barcode))
-
- return res
-
-def update_due_date(loan_id, new_due_date):
- """
- loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
-
- new_due_date: new due date.
- """
- return int(run_sql("""UPDATE crcLOAN
- SET due_date=%s,
- number_of_renewals = number_of_renewals + 1
- WHERE id=%s""",
- (new_due_date, loan_id)))
-
-def update_loan_status(status, loan_id):
- """
- Update the status of a loan.
- status: new status (after update)
- loan_id: identify the loan who will be updated.
- It is also the primary key of the table
- crcLOAN.
- """
- run_sql("""UPDATE crcLOAN
- set status = %s
- WHERE id = %s""",
- (status, loan_id))
-
-def get_loan_status(loan_id):
- """
- Get loan's status
-
- loan_id: identify a loan. It is the primery key of the table
- crcLOAN.
- """
-
- res = run_sql("""SELECT status
- FROM crcLOAN
- WHERE id=%s""",
- (loan_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_all_loans(limit):
- """
- Get all loans.
- """
-
- res = run_sql("""
- SELECT bor.id,
- bor.name,
- it.id_bibrec,
- l.barcode,
- DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d %%T'),
- DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
- l.number_of_renewals,
- l.overdue_letter_number,
- DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
- l.notes,
- l.id
- FROM crcLOAN l, crcBORROWER bor, crcITEM it
- WHERE l.id_crcBORROWER = bor.id
- AND l.barcode = it.barcode
- AND l.status = %s
- ORDER BY 5 DESC
- LIMIT 0,%s
- """, (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN, limit))
-
- return res
-
-def get_all_expired_loans():
- """
- Get all expired(overdue) loans.
- """
- res = run_sql(
- """
- SELECT bor.id,
- bor.name,
- it.id_bibrec,
- l.barcode,
- DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
- DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
- l.number_of_renewals,
- l.overdue_letter_number,
- DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
- l.notes,
- l.id
- FROM crcLOAN l, crcBORROWER bor, crcITEM it
- WHERE l.id_crcBORROWER = bor.id
- and l.barcode = it.barcode
- and ((l.status = %s and l.due_date < CURDATE())
- or l.status = %s )
- """, (CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
-
- return res
-
-def get_expired_loans_with_waiting_requests():
-
- res = run_sql("""SELECT DISTINCT
- lr.id,
- lr.id_bibrec,
- lr.id_crcBORROWER,
- it.id_crcLIBRARY,
- it.location,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr,
- crcITEM it,
- crcLOAN l
- WHERE it.barcode=l.barcode
- AND lr.id_bibrec=it.id_bibrec
- AND (lr.status=%s or lr.status=%s)
- AND (l.status=%s or (l.status=%s
- AND l.due_date < CURDATE()))
- AND lr.period_of_interest_from <= NOW()
- AND lr.period_of_interest_to >= NOW()
- ORDER BY lr.request_date;
- """, ( CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED,
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN))
- return res
-
-def get_current_loan_id(barcode):
- res = run_sql(""" SELECT id
- FROM crcLOAN
- WHERE barcode=%s
- AND (status=%s OR status=%s)
- """, (barcode, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED))
-
- if res:
- return res[0][0]
-
-def get_last_loan():
- """
- Get the recid, the borrower_id and the due date of
- the last loan who was registered on the crcLOAN table.
- """
-
- res = run_sql("""SELECT id_bibrec,
- id_crcBORROWER,
- DATE_FORMAT(due_date, '%Y-%m-%d')
- FROM crcLOAN ORDER BY id DESC LIMIT 1""")
-
- if res:
- return res[0]
- else:
- return None
-
-def get_loan_recid(loan_id):
-
- res = run_sql("""SELECT id_bibrec
- FROM crcLOAN
- WHERE id=%s""",
- (loan_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_loan_notes(loan_id):
-
- res = run_sql("""SELECT notes
- FROM crcLOAN
- WHERE id=%s""",
- (loan_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_loan_notes(loan_id, loan_notes):
- """
- """
- run_sql("""UPDATE crcLOAN
- SET notes=%s
- WHERE id=%s """, (str(loan_notes), loan_id))
-
-def add_new_loan_note(new_note, loan_id):
- """
- Add a new loan's note.
- new_note: note who will be added.
- loan_id: identify the loan. A new note will
- added to this loan. It is also the
- primary key of the table crcLOAN.
- """
- run_sql("""UPDATE crcLOAN
- set notes=concat(notes,%s)
- WHERE id=%s;
- """, (new_note, loan_id))
-
-def renew_loan(loan_id, new_due_date):
- run_sql("""UPDATE crcLOAN
- SET due_date=%s,
- number_of_renewals=number_of_renewals+1,
- overdue_letter_number=0,
- status=%s
- WHERE id=%s""", (new_due_date,
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- loan_id))
-
-###
-### Loan Returns related functions ###
-###
-
-
-
-def return_loan(barcode):
- """
- Update loan information when a copy is returned.
-
- @param returned_on: return date.
- @type returned_on: string
-
- @param status: new loan status.
- @type status: string
-
- @param barcode: identify the item. Primary key of crcITEM.
- @type barcode: string
- """
-
- return int(run_sql("""UPDATE crcLOAN
- SET returned_on=NOW(), status=%s, due_date=NULL
- WHERE barcode=%s and (status=%s or status=%s)
- """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED,
- barcode,
- CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED)))
-
-
-
-###
-### 'Item' related functions ###
-###
-
-
-
-def get_id_bibrec(barcode):
- """
- Get the id of the bibrec (recid).
-
- @param barcode: identify the item. Primary key of crcITEM.
- @type barcode: string
-
- @return recid or None
- """
-
- res = run_sql("""SELECT id_bibrec
- FROM crcITEM
- WHERE barcode=%s
- """, (barcode, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_item_info(barcode):
- """
- Get item's information.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
- """
-
- res = run_sql("""SELECT it.barcode,
- it.id_crcLIBRARY,
- lib.name,
- it.collection,
- it.location,
- it.description,
- it.loan_period,
- it.status
- FROM crcITEM it,
- crcLIBRARY lib
- WHERE it.barcode=%s and it.id_crcLIBRARY = lib.id""",
- (barcode, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def get_loan_period(barcode):
- """
- Retrieve the loan period of a book.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
- """
-
- res = run_sql("""SELECT loan_period
- FROM crcITEM
- WHERE barcode=%s""",
- (barcode, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_item_info(barcode, library_id, collection, location, description,
- loan_period, status, expected_arrival_date):
- """
- Update item's information.
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
-
- int(run_sql("""UPDATE crcITEM
- set barcode=%s,
- id_crcLIBRARY=%s,
- collection=%s,
- location=%s,
- description=%s,
- loan_period=%s,
- status=%s,
- expected_arrival_date=%s,
- modification_date=NOW()
- WHERE barcode=%s""",
- (barcode, library_id, collection, location, description,
- loan_period, status, expected_arrival_date, barcode)))
-
-def update_barcode(old_barcode, barcode):
-
- res = run_sql("""UPDATE crcITEM
- SET barcode=%s
- WHERE barcode=%s
- """, (barcode, old_barcode))
-
- run_sql("""UPDATE crcLOAN
- SET barcode=%s
- WHERE barcode=%s
- """, (barcode, old_barcode))
-
- run_sql("""UPDATE crcLOANREQUEST
- SET barcode=%s
- WHERE barcode=%s
- """, (barcode, old_barcode))
-
- run_sql("""UPDATE crcILLREQUEST
- SET barcode=%s
- WHERE barcode=%s
- """, (barcode, old_barcode))
-
- return res > 0
-
-def get_item_loans(recid):
- """
- recid: identify the record. It is also the primary key of
- the table bibrec.
- """
-
- res = run_sql(
- """
- SELECT bor.id,
- bor.name,
- l.barcode,
- DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
- DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
- l.number_of_renewals,
- l.overdue_letter_number,
- DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
- l.status,
- l.notes,
- l.id
- FROM crcLOAN l, crcBORROWER bor, crcITEM it
- WHERE l.id_crcBORROWER = bor.id
- and l.barcode=it.barcode
- and l.id_bibrec=%s
- and l.status!=%s
- """, (recid, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
-
- return res
-
-def get_item_requests(recid):
- """
- recid: identify the record. It is also the primary key of
- the table bibrec.
- """
- res = run_sql("""SELECT bor.id,
- bor.name,
- lr.id_bibrec,
- lr.barcode,
- lr.status,
- lib.name,
- it.location,
- it.description,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.id,
- lr.request_date
- FROM crcLOANREQUEST lr,
- crcBORROWER bor,
- crcITEM it,
- crcLIBRARY lib
- WHERE bor.id = lr.id_crcBORROWER and lr.id_bibrec=%s
- and lr.status!=%s and lr.status!=%s and lr.status!=%s
- and lr.barcode = it.barcode and lib.id = it.id_crcLIBRARY
- """, (recid,
- CFG_BIBCIRCULATION_REQUEST_STATUS_DONE,
- CFG_BIBCIRCULATION_REQUEST_STATUS_CANCELLED,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED))
-
- return res
-
-def get_item_purchases(status, recid):
- """
- Purchases of a particular item to be displayed in the item info page.
- """
-
- from invenio.legacy.bibcirculation.utils import looks_like_dictionary
-
- status1 = ''
- status2 = ''
-
- if status == CFG_BIBCIRCULATION_ACQ_STATUS_NEW:
- status1 = CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER
- status2 = CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER
- elif status == CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED:
- status1 = CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT
- status2 = CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED
-
- res = run_sql("""SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
- ill.item_info, ill.cost, ill.request_type, ''
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id
- AND ill.request_type in (%s, %s, %s)
- AND ill.status in (%s, %s, %s)
- ORDER BY ill.id desc""", ('acq-book', 'acq-standard',
- 'proposal-book', status, status1, status2))
-
- purchases = []
- for record in res:
- if looks_like_dictionary(record[8]):
- item_info = eval(record[8])
- try:
- if str(recid) == str(item_info['recid']): purchases.append(record)
- except KeyError:
- continue
- return tuple(purchases)
-
-def get_item_loans_historical_overview(recid):
- """
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
- """
- res = run_sql("""SELECT bor.name,
- bor.id,
- l.barcode,
- lib.name,
- it.location,
- DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
- DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
- l.returned_on,
- l.number_of_renewals,
- l.overdue_letter_number
- FROM crcLOAN l, crcBORROWER bor, crcITEM it, crcLIBRARY lib
- WHERE l.id_crcBORROWER=bor.id and
- lib.id = it.id_crcLIBRARY and
- it.barcode = l.barcode and
- l.id_bibrec = %s and
- l.status = %s """
- , (recid, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
-
- return res
-
-def get_item_requests_historical_overview(recid):
- """
- recid: identify the record. It is also the primary key of
- the table bibrec.
- """
-
- res = run_sql("""
- SELECT bor.name,
- bor.id,
- lr.barcode,
- lib.name,
- it.location,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr, crcBORROWER bor, crcITEM it, crcLIBRARY lib
- WHERE lr.id_crcBORROWER=bor.id and
- lib.id = it.id_crcLIBRARY and
- it.barcode = lr.barcode and
- lr.id_bibrec = %s and
- lr.status = %s
- """, (recid, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
-
- return res
-
-def get_nb_copies_on_loan(recid):
- """
- Get the number of copies on loan for a recid.
- recid: Invenio record identifier. The number of copies
- of this record will be retrieved.
- """
-
- res = run_sql("""SELECT count(barcode)
- FROM crcITEM
- WHERE id_bibrec=%s and status=%s;
- """, (recid, CFG_BIBCIRCULATION_LOAN_STATUS_ON_LOAN))
-
- return res[0][0]
-
-def get_item_copies_details(recid):
- """
- Get copies details of a given recid.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @return list with barcode, loan_period, library_name, library_id,
- location, number_of_requests, status, collection,
- description and due_date.
- """
- res = run_sql("""SELECT it.barcode, it.loan_period, lib.name,
- lib.id, it.location, it.number_of_requests,
- it.status, it.collection, it.description,
- DATE_FORMAT(ln.due_date,'%%Y-%%m-%%d')
- FROM crcITEM it
- left join crcLOAN ln
- on it.barcode = ln.barcode and ln.status != %s
- left join crcLIBRARY lib
- on lib.id = it.id_crcLIBRARY
- WHERE it.id_bibrec=%s
- ORDER BY it.creation_date
- """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, recid))
-
- return res
-
-def get_copy_details(barcode):
-
- res = run_sql(""" SELECT *
- FROM crcITEM it
- WHERE barcode=%s""",
- (barcode, ))
-
- if res is not None:
- return res[0]
- else:
- return None
-
-def get_copies_status(recid, description='-'):
- """
- @param description: Gives the details like volume(if any), etc... of a particular
- item in the record.
- """
- if description.strip() in ('', '-'):
- res = run_sql("""SELECT status
- FROM crcITEM
- WHERE id_bibrec=%s""", (recid, ))
- else:
- res = run_sql("""SELECT status
- FROM crcITEM
- WHERE id_bibrec=%s
- AND description=%s
- """, (recid, description))
-
- list_of_statuses = []
- for status in res:
- list_of_statuses.append(status[0])
-
- if list_of_statuses == []:
- return None
- else:
- return list_of_statuses
-
-def update_item_status(status, barcode):
- """
- Update the status of an item (using the barcode).
-
- @param status: status of the item.
- @type status: string
-
- @param barcode: identify the item. Primary key of crcITEM.
- @type barcode: string
-
- @return
- """
- if status == CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN:
- return int(run_sql("""UPDATE crcITEM
- SET status=%s,
- number_of_requests = number_of_requests + 1
- WHERE barcode=%s""", (status, barcode)))
- else:
- return int(run_sql("""UPDATE crcITEM
- SET status=%s
- WHERE barcode=%s""", (status, barcode)))
-
-def get_item_description(barcode):
- res = run_sql(""" SELECT description
- FROM crcITEM
- WHERE barcode=%s
- """, (barcode, ))
-
- #When no description:
- #Don't return NULL, in order not to pose problems if checked for equality.
- if res and res[0][0]:
- return res[0][0]
- else:
- return ''
-
-def set_item_description(barcode, description):
- return int(run_sql("""UPDATE crcITEM
- SET description=%s
- WHERE barcode=%s""", (description or '-', barcode)))
-
-def get_holdings_information(recid, include_hidden_libraries=True):
- """
- Get information about holdings, using recid.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @return holdings information
- """
-
- if include_hidden_libraries:
- res = run_sql("""SELECT it.barcode,
- lib.name,
- it.collection,
- it.location,
- it.description,
- it.loan_period,
- it.status,
- DATE_FORMAT(ln.due_date, '%%Y-%%m-%%d')
- FROM crcITEM it
- left join crcLOAN ln
- on it.barcode = ln.barcode and ln.status != %s
- left join crcLIBRARY lib
- on lib.id = it.id_crcLIBRARY
- WHERE it.id_bibrec=%s
- """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, recid))
-
- else:
- res = run_sql("""SELECT it.barcode,
- lib.name,
- it.collection,
- it.location,
- it.description,
- it.loan_period,
- it.status,
- DATE_FORMAT(ln.due_date, '%%Y-%%m-%%d')
- FROM crcITEM it
- left join crcLOAN ln
- on it.barcode = ln.barcode and ln.status != %s
- left join crcLIBRARY lib
- on lib.id = it.id_crcLIBRARY
- WHERE it.id_bibrec=%s
- AND lib.type<>%s
- """, (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED, recid,
- CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN))
-
- return res
-
-def get_number_copies(recid):
- """
- Get the number of copies of a given recid.
- This function is used by the 'BibEdit' module to display the
- number of copies for the record being edited.
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @return number_of_copies
- """
- try:
- recid = int(recid)
- except ValueError:
- return 0
-
- res = run_sql("""SELECT count(barcode)
- FROM crcITEM
- WHERE id_bibrec=%s
- """, (recid, ))
-
- return res[0][0]
-
-def has_copies(recid):
- """
- Indicate if there are any physical copies of a document described
- by the record
-
- @param recid: The identifier of the record
- @type recid: int
-
- @return True or False according to the state
- """
- return (get_number_copies(recid) != 0)
-
-def add_new_copy(barcode, recid, library_id, collection, location, description,
- loan_period, status, expected_arrival_date):
-
- """
- Add a new copy
-
- barcode: identify the item. It is the primary key of the table
- crcITEM.
-
- recid: identify the record. It is also the primary key of
- the table bibrec.
-
- library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
-
- run_sql("""insert into crcITEM (barcode, id_bibrec, id_crcLIBRARY,
- collection, location, description, loan_period,
- status, expected_arrival_date, creation_date,
- modification_date)
- values (%s, %s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW())""",
- (barcode, recid, library_id, collection, location, description or '-',
- loan_period, status, expected_arrival_date))
-
-def delete_copy(barcode):
- res = run_sql("""delete FROM crcITEM WHERE barcode=%s""", (barcode, ))
- return res
-
-def get_expected_arrival_date(barcode):
- res = run_sql("""SELECT expected_arrival_date
- FROM crcITEM
- WHERE barcode=%s """, (barcode,))
- if res:
- return res[0][0]
- else:
- return ''
-
-def get_barcodes(recid, description='-'):
- """
- @param description: Gives the details like volume(if any), etc... of a particular
- item in the record.
- """
-
- if description.strip() in ('', '-'):
- res = run_sql("""SELECT barcode
- FROM crcITEM
- WHERE id_bibrec=%s""",
- (recid, ))
- else:
- res = run_sql("""SELECT barcode
- FROM crcITEM
- WHERE id_bibrec=%s
- AND description=%s""",
- (recid, description))
-
- barcodes = []
- for i in range(len(res)):
- barcodes.append(res[i][0])
-
- return barcodes
-
-def barcode_in_use(barcode):
-
- res = run_sql("""SELECT id_bibrec
- FROM crcITEM
- WHERE barcode=%s""",
- (barcode, ))
-
- if len(res)>0:
- return True
- else:
- return False
-
-
-
-
-###
-### "Borrower" related functions ###
-###
-
-
-
-
-def new_borrower(ccid, name, email, phone, address, mailbox, notes):
- """
- Add/Register a new borrower on the crcBORROWER table.
- name: borrower's name.
- email: borrower's email.
- phone: borrower's phone.
- address: borrower's address.
- """
-
- return run_sql("""insert into crcBORROWER ( ccid,
- name,
- email,
- phone,
- address,
- mailbox,
- borrower_since,
- borrower_until,
- notes)
- values(%s, %s, %s, %s, %s, %s, NOW(), '0000-00-00 00:00:00', %s)""",
- (ccid, name, email, phone, address, mailbox, str(notes)))
- # IntegrityError: (1062, "Duplicate entry '665119' for key 2")
-
-def get_borrower_details(borrower_id):
- """
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- res = run_sql("""SELECT id, ccid, name, email, phone, address, mailbox
- FROM crcBORROWER WHERE id=%s""", (borrower_id, ))
- if res:
- return clean_data(res[0])
- else:
- return None
-
-
-def clean_data(data):
- final_res = list(data)
- for i in range(0, len(final_res)):
- if isinstance(final_res[i], str):
- final_res[i] = final_res[i].replace(",", " ")
- return final_res
-
-
-def update_borrower_info(borrower_id, name, email, phone, address, mailbox):
- """
- Update borrower info.
-
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- return int(run_sql("""UPDATE crcBORROWER
- set name=%s,
- email=%s,
- phone=%s,
- address=%s,
- mailbox=%s
- WHERE id=%s""",
- (name, email, phone, address, mailbox, borrower_id)))
-
-def get_borrower_data(borrower_id):
- """
- Get the borrower's information (name, address and email).
- borrower_id: identify the borrower. The data associate
- to this borrower will be retrieved. It is also
- the primary key of the crcBORROWER table.
- """
-
- res = run_sql("""SELECT name,
- address,
- mailbox,
- email
- FROM crcBORROWER
- WHERE id=%s""",
- (borrower_id, ))
-
- if res:
- return clean_data(res[0])
- else:
- return None
-
-def get_borrower_data_by_id(borrower_id):
- """
- Retrieve borrower's data by borrower_id.
- """
-
- res = run_sql("""SELECT id, ccid, name, email, phone,
- address, mailbox
- FROM crcBORROWER
- WHERE id=%s""", (borrower_id, ))
-
- if res:
- return clean_data(res[0])
- else:
- return None
-
-def get_borrower_ccid(user_id):
-
- res = run_sql("""SELECT ccid
- FROM crcBORROWER
- WHERE id=%s""", (user_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_all_borrowers():
- res = run_sql("""SELECT id, ccid
- FROM crcBORROWER""")
-
- return res
-
-def get_borrower_name(borrower_id):
- """
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
- res = run_sql("""SELECT name
- FROM crcBORROWER
- WHERE id=%s
- """, (borrower_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_borrower_email(borrower_id):
- """
- Get the email of a borrower.
-
- @param borrower_id: identify the borrower. Primary key of crcBORROWER.
- @type borrower_id: int
-
- @return borrower's email (string).
- """
- res = run_sql("""SELECT email
- FROM crcBORROWER
- WHERE id=%s""", (borrower_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_borrower_id_by_email(email):
- """
- Retrieve borrower's id by email.
- """
-
- res = run_sql("""SELECT id
- FROM crcBORROWER
- WHERE email=%s""",
- (email, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_borrower_address(email):
- """
- Get the address of a borrower using the email.
- email: borrower's email.
- """
-
- res = run_sql("""SELECT address
- FROM crcBORROWER
- WHERE email=%s""", (email, ))
-
- if len(res[0][0]) > 0:
- return res[0][0].replace(",", " ")
- else:
- return 0
-
-def add_borrower_address(address, email):
- """
- Add the email and the address of a borrower.
- address: borrower's address.
- email: borrower's email.
- """
-
- run_sql("""UPDATE crcBORROWER
- set address=%s
- WHERE email=%s""", (address, email))
-
-def get_invenio_user_email(uid):
- """
- Get the email of an invenio's user.
- uid: identify an invenio's user.
- """
-
- res = run_sql("""SELECT email
- FROM user
- WHERE id=%s""",
- (uid, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def search_borrower_by_name(string):
- """
- string: search pattern.
- """
- string = string.replace("'", "\\'")
-
- res = run_sql("""SELECT id, name
- FROM crcBORROWER
- WHERE upper(name) like upper('%%%s%%')
- ORDER BY name
- """ % (string))
-
- return res
-
-def search_borrower_by_email(string):
- """
- string: search pattern.
- """
-
- res = run_sql("""SELECT id, name
- FROM crcBORROWER
- WHERE email regexp %s
- """, (string, ))
-
- return res
-
-def search_borrower_by_id(string):
- """
- string: search pattern.
- """
-
- res = run_sql("""SELECT id, name
- FROM crcBORROWER
- WHERE id=%s
- """, (string, ))
-
- return res
-
-def search_borrower_by_ccid(string):
- """
- string: search pattern.
- """
-
- res = run_sql("""SELECT id, name
- FROM crcBORROWER
- WHERE ccid regexp %s
- """, (string, ))
-
- return res
-
-def update_borrower(user_id, name, email, phone, address, mailbox):
- return run_sql(""" UPDATE crcBORROWER
- SET name=%s,
- email=%s,
- phone=%s,
- address=%s,
- mailbox=%s
- WHERE id=%s
- """, (name, email, phone, address, mailbox, user_id))
-
-def get_borrower_loans(borrower_id):
- """
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
-
- res = run_sql(""" SELECT id_bibrec,
- barcode,
- DATE_FORMAT(loaned_on,'%%Y-%%m-%%d'),
- DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
- type
- FROM crcLOAN
- WHERE id_crcBORROWER=%s and status != %s
- """, (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
-
- return res
-
-def get_recid_borrower_loans(borrower_id):
- """
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
- """
-
- res = run_sql(""" SELECT id, id_bibrec, barcode
- FROM crcLOAN
- WHERE id_crcBORROWER=%s
- AND status != %s
- AND type != 'ill'
- """, (borrower_id, CFG_BIBCIRCULATION_ILL_STATUS_RETURNED))
-
-
- return res
-
-def get_borrower_loan_details(borrower_id):
- """
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- This function is also used by the Aleph Service for the display of loans
- of the user for the termination sheet.
- """
-
- res = run_sql("""
- SELECT it.id_bibrec,
- l.barcode,
- DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
- DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
- l.number_of_renewals,
- l.overdue_letter_number,
- DATE_FORMAT(l.overdue_letter_date,'%%Y-%%m-%%d'),
- l.type,
- l.notes,
- l.id,
- l.status
- FROM crcLOAN l, crcITEM it
- WHERE l.barcode=it.barcode
- AND id_crcBORROWER=%s
- AND l.status!=%s
- """, (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
-
- return res
-
-def get_borrower_request_details(borrower_id):
- """
- borrower_id: identify the borrower. It is also the primary key of
- the table crcBORROWER.
-
- This function is also used by the Aleph Service for the display of loan
- requests of the user for the termination sheet.
- """
-
- res = run_sql("""SELECT lr.id_bibrec,
- lr.status,
- lib.name,
- it.location,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date,
- lr.id
- FROM crcLOANREQUEST lr,
- crcITEM it,
- crcLIBRARY lib
- WHERE lr.id_crcBORROWER=%s
- AND (lr.status=%s OR lr.status=%s)
- and lib.id = it.id_crcLIBRARY and lr.barcode = it.barcode
- """, (borrower_id,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING))
-
- return res
-
-def get_borrower_requests(borrower_id):
- """
- Get the hold requests of a borrower.
- borrower_id: identify the borrower. All the hold requests
- associate to this borrower will be retrieved.
- It is also the primary key of the crcBORROWER table.
- """
- res = run_sql("""
- SELECT id,
- id_bibrec,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
- status
- FROM crcLOANREQUEST
- WHERE id_crcBORROWER=%s and
- (status=%s or status=%s)""",
- (borrower_id, CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING))
-
- return res
-
-def get_borrower_proposals(borrower_id):
- """
- Get the proposals of a borrower.
- borrower_id: identify the borrower. All the proposals
- associated to this borrower will be retrieved.
- It is also the primary key of the crcBORROWER table.
- """
- res = run_sql("""
- SELECT id,
- id_bibrec,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
- status
- FROM crcLOANREQUEST
- WHERE id_crcBORROWER=%s and
- status=%s""",
- (borrower_id, CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED))
- return res
-
-def bor_loans_historical_overview(borrower_id):
- """
- Get loans historical overview of a given borrower_id.
-
- @param borrower_id: identify the borrower. Primary key of crcBORROWER.
- @type borrower_id: int
-
- @return list with loans historical overview.
- """
- res = run_sql("""SELECT l.id_bibrec,
- l.barcode,
- lib.name,
- it.location,
- DATE_FORMAT(l.loaned_on,'%%Y-%%m-%%d'),
- DATE_FORMAT(l.due_date,'%%Y-%%m-%%d'),
- l.returned_on,
- l.number_of_renewals,
- l.overdue_letter_number
- FROM crcLOAN l, crcITEM it, crcLIBRARY lib
- WHERE l.id_crcBORROWER=%s and
- lib.id = it.id_crcLIBRARY and
- it.barcode = l.barcode and
- l.status = %s
- """, (borrower_id, CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
- return res
-
-def bor_requests_historical_overview(borrower_id):
- """
- Get requests historical overview of a given borrower_id.
-
- @param borrower_id: identify the borrower. Primary key of crcBORROWER.
- @type borrower_id: int
-
- @return list with requests historical overview.
- """
- res = run_sql("""SELECT lr.id_bibrec,
- lr.barcode,
- lib.name,
- it.location,
- DATE_FORMAT(lr.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(lr.period_of_interest_to,'%%Y-%%m-%%d'),
- lr.request_date
- FROM crcLOANREQUEST lr, crcITEM it, crcLIBRARY lib
- WHERE lr.id_crcBORROWER=%s and
- lib.id = it.id_crcLIBRARY and
- it.barcode = lr.barcode and
- lr.status =%s
- """, (borrower_id, CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
- return res
-
-def get_historical_overview(borrower_id):
- """
- Get historical information overview (recid, loan date, return date
- and number of renewals).
- borrower_id: identify the borrower. All the old (returned) loans
- associated to this borrower will be retrieved.
- It is also the primary key of the crcBORROWER table.
- """
-
- res = run_sql("""SELECT id_bibrec,
- DATE_FORMAT(loaned_on,'%%Y-%%m-%%d'),
- returned_on,
- number_of_renewals
- FROM crcLOAN
- WHERE id_crcBORROWER=%s and status=%s;
- """, (borrower_id,
- CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED))
-
- return res
-
-def get_borrower_notes(borrower_id):
- """The data associated to this borrower will be retrieved."""
-
- res = run_sql("""SELECT notes
- FROM crcBORROWER
- WHERE id=%s""",
- (borrower_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_borrower_notes(borrower_id, borrower_notes):
-
- run_sql("""UPDATE crcBORROWER
- SET notes=%s
- WHERE id=%s """, (str(borrower_notes), borrower_id))
-
-
-
-
-###
-### "Library" related functions ###
-###
-
-
-
-
-def get_all_libraries():
-
- res = run_sql("""SELECT id, name
- FROM crcLIBRARY
- ORDER BY name""")
-
- return res
-
-def get_main_libraries():
-
- res = run_sql("""SELECT id, name
- FROM crcLIBRARY
- WHERE type=%s
- """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN, ))
-
- if res:
- return res
- else:
- return None
-
-def get_internal_libraries():
-
- res = run_sql("""SELECT id, name
- FROM crcLIBRARY
- WHERE (type=%s OR type=%s)
- ORDER BY name
- """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_INTERNAL,
- CFG_BIBCIRCULATION_LIBRARY_TYPE_MAIN))
-
- return res
-
-def get_external_libraries():
-
- res = run_sql("""SELECT id, name
- FROM crcLIBRARY
- WHERE type=%s
- """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_EXTERNAL, ))
-
- return res
-
-def get_hidden_libraries():
-
- res = run_sql("""SELECT id, name
- FROM crcLIBRARY
- WHERE type=%s
- ORDER BY name
- """, (CFG_BIBCIRCULATION_LIBRARY_TYPE_HIDDEN, ))
-
- return res
-
-def merge_libraries(library_from, library_to):
-
- run_sql("""UPDATE crcITEM
- SET id_crcLIBRARY=%s
- WHERE id_crcLIBRARY=%s
- """, (library_to, library_from))
-
- run_sql("""UPDATE crcILLREQUEST
- SET id_crcLIBRARY=%s
- WHERE id_crcLIBRARY=%s
- """, (library_to, library_from))
-
- run_sql("""DELETE FROM crcLIBRARY
- WHERE id=%s
- """, (library_from,))
-
-def get_library_items(library_id):
- """
- Get all items which belong to a library.
-
- library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
- res = run_sql("""SELECT barcode, id_bibrec, collection,
- location, description, loan_period, status, number_of_requests
- FROM crcITEM
- WHERE id_crcLIBRARY=%s""",
- (library_id, ))
-
- return res
-
-def get_library_details(library_id):
- """
- library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
- res = run_sql("""SELECT id, name, address, email, phone, type, notes
- FROM crcLIBRARY
- WHERE id=%s;
- """, (library_id, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def get_library_type(library_id):
- """
- library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
-
- res = run_sql("""SELECT type
- FROM crcLIBRARY
- WHERE id=%s""",
- (library_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_library_name(library_id):
- """
- library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
-
- res = run_sql("""SELECT name
- FROM crcLIBRARY
- WHERE id=%s""",
- (library_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_lib_location(barcode):
-
- res = run_sql("""SELECT id_crcLIBRARY, location
- FROM crcITEM
- WHERE barcode=%s""",
- (barcode, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def get_library_notes(library_id):
- """ The data associated to this library will be retrieved."""
- res = run_sql("""SELECT notes
- FROM crcLIBRARY
- WHERE id=%s""",
- (library_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_library_notes(library_id, library_notes):
-
- run_sql("""UPDATE crcLIBRARY
- SET notes=%s
- WHERE id=%s """, (str(library_notes), library_id))
-
-def add_new_library(name, email, phone, address, lib_type, notes):
-
- run_sql("""insert into crcLIBRARY (name, email, phone,
- address, type, notes)
- values (%s, %s, %s, %s, %s, %s)""",
- (name, email, phone, address, lib_type, notes))
-
-def update_library_info(library_id, name, email, phone, address, lib_type):
- """
- library_id: identify the library. It is also the primary key of
- the table crcLIBRARY.
- """
-
- return int(run_sql("""UPDATE crcLIBRARY
- set name=%s,
- email=%s,
- phone=%s,
- address=%s,
- type=%s
- WHERE id=%s""",
- (name, email, phone, address, lib_type, library_id)))
-
-def search_library_by_name(string):
-
- string = string.replace("'", "\\'")
-
- res = run_sql("""SELECT id, name
- FROM crcLIBRARY
- WHERE upper(name) like upper('%%%s%%')
- ORDER BY name
- """ % (string))
-
- return res
-
-def search_library_by_email(string):
-
- res = run_sql("""SELECT id, name
- FROM crcLIBRARY
- WHERE email regexp %s
- ORDER BY name
- """, (string, ))
- return res
-
-
-
-
-###
-### "Vendor" related functions ###
-###
-
-
-
-
-def get_all_vendors():
-
- res = run_sql("""SELECT id, name
- FROM crcVENDOR""")
- return res
-
-def get_vendor_details(vendor_id):
- """
- vendor_id: identify the vendor. It is also the primary key of
- the table crcVENDOR.
- """
- res = run_sql("""SELECT id, name, address, email, phone, notes
- FROM crcVENDOR
- WHERE id=%s;
- """, (vendor_id, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def get_vendor_name(vendor_id):
- """
- vendor_id: identify the vendor. It is also the primary key of
- the table crcVENDOR.
- """
- res = run_sql("""SELECT name
- FROM crcVENDOR
- WHERE id=%s""",
- (vendor_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_vendor_notes(vendor_id):
- """ The data associated to this vendor will be retrieved."""
-
- res = run_sql("""SELECT notes
- FROM crcVENDOR
- WHERE id=%s""",
- (vendor_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def add_new_vendor_note(new_note, vendor_id):
-
- run_sql("""UPDATE crcVENDOR
- SET notes=concat(notes,%s)
- WHERE id=%s;
- """, (new_note, vendor_id))
-
-def add_new_vendor(name, email, phone, address, notes):
-
- run_sql("""insert into crcVENDOR (name, email, phone,
- address, notes)
- values (%s, %s, %s, %s, %s)""",
- (name, email, phone, address, notes))
-
-def update_vendor_info(vendor_id, name, email, phone, address):
- """
- vendor_id: identify the vendor. It is also the primary key of
- the table crcVENDOR.
- """
- return int(run_sql("""UPDATE crcVENDOR
- SET name=%s,
- email=%s,
- phone=%s,
- address=%s
- WHERE id=%s""",
- (name, email, phone, address, vendor_id)))
-
-def search_vendor_by_name(string):
-
- res = run_sql("""SELECT id, name
- FROM crcVENDOR
- WHERE name regexp %s
- """, (string, ))
-
- return res
-
-def search_vendor_by_email(string):
-
- res = run_sql("""SELECT id, name
- FROM crcVENDOR
- WHERE email regexp %s
- """, (string, ))
-
- return res
-
-
-
-
-###
-### ILL/Proposals/Purchases related functions ###
-###
-
-
-
-
-def get_ill_request_type(ill_request_id):
-
- res = run_sql("""SELECT request_type
- FROM crcILLREQUEST
- WHERE id=%s""", (ill_request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def ill_register_request(item_info, borrower_id, period_of_interest_from,
- period_of_interest_to, status, additional_comments,
- only_edition, request_type, budget_code='', barcode=''):
-
- run_sql("""insert into crcILLREQUEST(id_crcBORROWER, barcode,
- period_of_interest_from,
- period_of_interest_to, status, item_info,
- borrower_comments, only_this_edition,
- request_type, budget_code)
- values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
- (borrower_id, barcode, period_of_interest_from,
- period_of_interest_to, status, str(item_info),
- additional_comments, only_edition,
- request_type, budget_code))
-
-def ill_register_request_on_desk(borrower_id, item_info,
- period_of_interest_from,
- period_of_interest_to,
- status, notes, only_edition, request_type,
- budget_code=''):
-
- run_sql("""insert into crcILLREQUEST(id_crcBORROWER,
- period_of_interest_from, period_of_interest_to,
- status, item_info, only_this_edition,
- library_notes, request_type, budget_code)
- values (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
- (borrower_id, period_of_interest_from, period_of_interest_to,
- status, str(item_info), only_edition, notes, request_type,
- budget_code))
-
-def get_ill_request_details(ill_request_id):
-
- res = run_sql("""SELECT id_crcLIBRARY,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(return_date,'%%Y-%%m-%%d'),
- cost,
- barcode,
- library_notes,
- status
- FROM crcILLREQUEST
- WHERE id=%s""", (ill_request_id, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def register_ill_from_proposal(ill_request_id, bid=None, library_notes=''):
- """
- Register an ILL request created from an existing proposal.
- (Used in cases where proposals are 'put aside')
- """
-
- if not bid:
- bid = run_sql("""SELECT id_crcBORROWER
- FROM crcILLREQUEST
- WHERE id = %s
- """, (ill_request_id))[0][0]
-
- run_sql("""insert into crcILLREQUEST(id_crcBORROWER,
- period_of_interest_from, period_of_interest_to,
- status, item_info, only_this_edition,
- request_type, budget_code, library_notes)
- SELECT %s, period_of_interest_from, period_of_interest_to,
- %s, item_info, only_this_edition,
- %s, budget_code, %s
- FROM crcILLREQUEST
- WHERE id = %s
- """,(bid, CFG_BIBCIRCULATION_ILL_STATUS_NEW, 'book',
- str(library_notes), ill_request_id))
-
-def get_ill_requests(status):
-
- if status == None:
- res = run_sql("""
- SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
- ill.item_info, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id
- AND (ill.request_type=%s OR ill.request_type=%s)
- ORDER BY ill.id desc
- """, ('article', 'book'))
- else:
- res = run_sql("""
- SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
- ill.item_info, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id
- AND (ill.request_type=%s OR ill.request_type=%s)
- AND ill.status=%s
- ORDER BY ill.id desc
- """, ('article', 'book', status))
-
- return res
-
-def get_all_expired_ills():
- """
- Get all expired(overdue) ills.
- """
- res = run_sql(
- """
- SELECT id,
- id_crcBORROWER,
- item_info,
- overdue_letter_number,
- DATE_FORMAT(overdue_letter_date,'%%Y-%%m-%%d')
- FROM crcILLREQUEST
- WHERE status = %s and due_date < CURDATE()
- AND request_type in (%s, %s)
- """, (CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN,
- 'article', 'book'))
-
- return res
-
-def get_proposals(proposal_status):
-
- res = run_sql("""SELECT temp.*, count(req.barcode)
- FROM (SELECT ill.id, ill.id_crcBORROWER, bor.name, ill.id_crcLIBRARY,
- ill.status, ill.barcode,
- ill.period_of_interest_from,
- ill.period_of_interest_to,
- ill.item_info, ill.cost, ill.request_type
- FROM crcILLREQUEST as ill, crcBORROWER as bor
- WHERE ill.request_type=%s
- AND ill.status=%s
- AND ill.barcode!=''
- AND ill.id_crcBORROWER=bor.id) AS temp
- LEFT JOIN (SELECT barcode
- FROM crcLOANREQUEST
- WHERE barcode!=''
- AND status in (%s, %s, %s, %s)) AS req
- ON temp.barcode=req.barcode
- GROUP BY req.barcode
- ORDER BY temp.id desc""", ('proposal-book', proposal_status,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PROPOSED,
- CFG_BIBCIRCULATION_REQUEST_STATUS_PENDING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING,
- CFG_BIBCIRCULATION_REQUEST_STATUS_DONE))
- return res
-
-def get_requests_on_put_aside_proposals():
- """
- @return Requests on proposed books that are 'put aside'.
- """
-
- res = run_sql("""SELECT ill.id, req.id, bor.id, bor.name, req.period_of_interest_from,
- req.period_of_interest_to, ill.item_info, ill.cost
- FROM crcILLREQUEST as ill, crcLOANREQUEST as req, crcBORROWER as bor
- WHERE ill.barcode!='' AND req.barcode!=''
- AND ill.barcode=req.barcode
- AND req.id_crcBORROWER = bor.id
- AND ill.request_type=%s
- AND ill.status=%s
- AND req.status=%s
- ORDER BY req.id desc""", ('proposal-book', CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE,
- CFG_BIBCIRCULATION_REQUEST_STATUS_WAITING))
- return res
-
-def get_purchases(status):
-
- if status in (CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER):
- #Include proposals with status 'on order' since they are
- #purchases too and thus, is helpful if both the categories are
- #displayed in the same 'purchase-on order' list in the menu.
- res = run_sql("""SELECT ill_data.*, ill_cnt.cnt FROM
- (SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
- ill.item_info, ill.cost, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id
- AND ill.request_type in (%s, %s, %s)
- AND ill.status in (%s, %s)) AS ill_data
- LEFT JOIN (SELECT item_info, count(item_info) AS cnt
- FROM crcILLREQUEST
- WHERE request_type in (%s, %s, %s)
- AND status not in (%s, %s, %s)
- GROUP BY item_info) AS ill_cnt
- ON ill_data.item_info = ill_cnt.item_info
- ORDER BY ill_data.id desc""", ('acq-standard', 'acq-book',
- 'proposal-book',
- CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER,
- 'acq-standard', 'acq-book',
- 'proposal-book',
- CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE))
-
- else:
- res = run_sql("""SELECT ill_data.*, ill_cnt.cnt FROM
- (SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
- ill.item_info, ill.cost, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id
- AND ill.request_type in (%s, %s)
- AND ill.status=%s) AS ill_data
- LEFT JOIN (SELECT item_info, count(item_info) AS cnt
- FROM crcILLREQUEST
- WHERE request_type in (%s, %s)
- AND status!=%s
- GROUP BY item_info) AS ill_cnt
- ON ill_data.item_info = ill_cnt.item_info
- ORDER BY ill_data.id desc""", ('acq-standard', 'acq-book', status,
- 'acq-standard', 'acq-book',
- CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED))
-
- return res
-
-def search_ill_requests_title(title, date_from, date_to):
-
- title = title.replace("'", "\\'")
- date_from = date_from.replace("'", "\\'")
- date_to = date_to.replace("'", "\\'")
-
- tokens = title.split()
- tokens_query = ""
- for token in tokens:
- tokens_query += " AND ill.item_info like '%%%s%%' " % token
-
-
- query = """SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%Y-%m-%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%Y-%m-%d'),
- DATE_FORMAT(ill.due_date,'%Y-%m-%d'),
- ill.item_info, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id """
- query += tokens_query
- query += """ AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >= '%s'
- AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <= '%s'
- ORDER BY ill.id desc""" % (date_from, date_to)
-
- return run_sql(query)
-
-def search_ill_requests_id(reqid, date_from, date_to):
-
- res = run_sql("""
- SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
- ill.item_info, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id
- AND ill.id = %s
- AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >=%s
- AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <=%s
- ORDER BY ill.id desc""", (reqid, date_from, date_to))
-
- return res
-
-def search_requests_cost(cost, date_from, date_to):
-
- cost = cost.replace("'", "\\'")
-
- res = run_sql("""
- SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.due_date,'%%Y-%%m-%%d'),
- ill.item_info, ill.cost, ill.request_type, ''
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id
- AND ill.cost like upper('%%%s%%')
- AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >= %s
- AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <= %s
- ORDER BY ill.id desc
- """ % (cost.upper(), date_from, date_to))
-
- return res
-
-def search_requests_notes(notes, date_from, date_to):
-
- notes = notes.replace("'", "\\'")
- date_from = date_from.replace("'", "\\'")
- date_to = date_to.replace("'", "\\'")
-
- tokens = notes.split()
- tokens_query = ""
- for token in tokens:
- tokens_query += " AND library_notes like '%%%s%%' " % token
-
- query = """
- SELECT ill.id, ill.id_crcBORROWER, bor.name,
- ill.id_crcLIBRARY, ill.status,
- DATE_FORMAT(ill.period_of_interest_from,'%Y-%m-%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%Y-%m-%d'),
- DATE_FORMAT(ill.due_date,'%Y-%m-%d'),
- ill.item_info, ill.cost, ill.request_type, ''
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id """
- query += tokens_query
- query += """ AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') >= %s
- AND DATE_FORMAT(ill.request_date,'%%Y-%%m-%%d') <= %s
- ORDER BY ill.id desc
- """ % (date_from, date_to)
-
- return run_sql(query)
-
-def get_ill_request_borrower_details(ill_request_id):
-
- res = run_sql("""
- SELECT ill.id_crcBORROWER, bor.name, bor.email, bor.mailbox,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- ill.item_info, ill.borrower_comments,
- ill.only_this_edition, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id and ill.id=%s""", (ill_request_id, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def get_purchase_request_borrower_details(ill_request_id):
-
- res = run_sql("""
- SELECT ill.id_crcBORROWER, bor.name, bor.email, bor.mailbox,
- DATE_FORMAT(ill.period_of_interest_from,'%%Y-%%m-%%d'),
- DATE_FORMAT(ill.period_of_interest_to,'%%Y-%%m-%%d'),
- ill.item_info, ill.borrower_comments,
- ill.only_this_edition, ill.budget_code, ill.request_type
- FROM crcILLREQUEST ill, crcBORROWER bor
- WHERE ill.id_crcBORROWER=bor.id and ill.id=%s""", (ill_request_id, ))
-
- if res:
- return res[0]
- else:
- return None
-
-def update_ill_request(ill_request_id, library_id, request_date,
- expected_date, arrival_date, due_date, return_date,
- status, cost, barcode, library_notes):
-
- run_sql("""UPDATE crcILLREQUEST
- SET id_crcLIBRARY=%s,
- request_date=%s,
- expected_date=%s,
- arrival_date=%s,
- due_date=%s,
- return_date=%s,
- status=%s,
- cost=%s,
- barcode=%s,
- library_notes=%s
- WHERE id=%s""",
- (library_id, request_date, expected_date,
- arrival_date, due_date, return_date, status, cost,
- barcode, library_notes, ill_request_id))
-
-def update_purchase_request(ill_request_id, library_id, request_date,
- expected_date, arrival_date, due_date, return_date,
- status, cost, budget_code, library_notes):
-
- run_sql("""UPDATE crcILLREQUEST
- SET id_crcLIBRARY=%s,
- request_date=%s,
- expected_date=%s,
- arrival_date=%s,
- due_date=%s,
- return_date=%s,
- status=%s,
- cost=%s,
- budget_code=%s,
- library_notes=%s
- WHERE id=%s""",
- (library_id, request_date, expected_date,
- arrival_date, due_date, return_date, status, cost,
- budget_code, library_notes, ill_request_id))
-
-def update_ill_request_status(ill_request_id, new_status):
-
- run_sql("""UPDATE crcILLREQUEST
- SET status=%s
- WHERE id=%s""", (new_status, ill_request_id))
-
-def get_ill_request_notes(ill_request_id):
-
- res = run_sql("""SELECT library_notes
- FROM crcILLREQUEST
- WHERE id=%s""",
- (ill_request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_ill_request_notes(ill_request_id, library_notes):
-
- run_sql("""UPDATE crcILLREQUEST
- SET library_notes=%s
- WHERE id=%s""", (str(library_notes), ill_request_id))
-
-def update_ill_request_item_info(ill_request_id, item_info):
-
- run_sql("""UPDATE crcILLREQUEST
- SET item_info=%s
- WHERE id=%s""", (str(item_info), ill_request_id))
-
-def get_ill_borrower(ill_request_id):
-
- res = run_sql("""SELECT id_crcBORROWER
- FROM crcILLREQUEST
- WHERE id=%s""", (ill_request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def get_ill_barcode(ill_request_id):
-
- res = run_sql("""SELECT barcode
- FROM crcILLREQUEST
- WHERE id=%s""", (ill_request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_ill_loan_status(borrower_id, barcode, return_date, loan_type):
-
- run_sql("""UPDATE crcLOAN
- SET status = %s,
- returned_on = %s
- WHERE id_crcBORROWER = %s
- AND barcode = %s
- AND type = %s """,
- (CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED,
- return_date, borrower_id, barcode, loan_type))
-
-def get_ill_requests_details(borrower_id):
- """
- This function is also used by the Aleph Service for the display of ILLs
- of the user for termination sheet.
- """
-
- res = run_sql("""SELECT id, item_info, id_crcLIBRARY,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
- status, library_notes, request_type
- FROM crcILLREQUEST
- WHERE id_crcBORROWER=%s
- AND status in (%s, %s, %s)
- AND request_type in (%s, %s)
- ORDER BY FIELD(status, %s, %s, %s)
- """, (borrower_id, CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED,
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN,
- 'article', 'book',
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN,
- CFG_BIBCIRCULATION_ILL_STATUS_NEW,
- CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED))
-
- return res
-
-def get_proposal_requests_details(borrower_id):
-
- res = run_sql("""SELECT id, item_info, id_crcLIBRARY,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
- status, library_notes, request_type
- FROM crcILLREQUEST
- WHERE id_crcBORROWER=%s
- AND status in (%s, %s)
- AND request_type = %s
- """, (borrower_id, CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE,
- 'proposal-book'))
-
- return res
-
-def bor_ill_historical_overview(borrower_id):
-
- res = run_sql("""SELECT id, item_info, id_crcLIBRARY,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
- status, library_notes, request_type
- FROM crcILLREQUEST
- WHERE id_crcBORROWER=%s
- AND (status=%s OR status=%s)
- AND request_type in (%s, %s)
- """, (borrower_id, CFG_BIBCIRCULATION_ILL_STATUS_RETURNED,
- CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED,
- 'article', 'book'))
-
- return res
-
-def bor_proposal_historical_overview(borrower_id):
-
- res = run_sql("""SELECT id, item_info, id_crcLIBRARY,
- DATE_FORMAT(request_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(expected_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(arrival_date,'%%Y-%%m-%%d'),
- DATE_FORMAT(due_date,'%%Y-%%m-%%d'),
- status, library_notes, request_type
- FROM crcILLREQUEST
- WHERE id_crcBORROWER=%s
- AND (status=%s OR status=%s)
- AND request_type = %s
- """, (borrower_id, CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER,
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED,
- 'proposal-book'))
-
- return res
-
-def get_ill_notes(ill_id):
-
- res = run_sql("""SELECT library_notes
- FROM crcILLREQUEST
- WHERE id=%s""",
- (ill_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def update_ill_notes(ill_id, ill_notes):
-
- run_sql("""UPDATE crcILLREQUEST
- SET library_notes=%s
- WHERE id=%s """, (str(ill_notes), ill_id))
-
-def get_ill_book_info(ill_request_id):
-
- res = run_sql("""SELECT item_info
- FROM crcILLREQUEST
- WHERE id=%s""",
- (ill_request_id, ))
-
- if res:
- return res[0][0]
- else:
- return None
-
-def delete_brief_format_cache(recid):
-
- run_sql("""DELETE FROM bibfmt
- WHERE format='HB'
- AND id_bibrec=%s""", (recid,))
diff --git a/invenio/legacy/bibcirculation/doc/admin/bibcirculation-admin-guide.webdoc b/invenio/legacy/bibcirculation/doc/admin/bibcirculation-admin-guide.webdoc
deleted file mode 100644
index 3ba18d7c0..000000000
--- a/invenio/legacy/bibcirculation/doc/admin/bibcirculation-admin-guide.webdoc
+++ /dev/null
@@ -1,64 +0,0 @@
-# -*- mode: html; coding: utf-8; -*-
-
-# This file is part of Invenio.
-# Copyright (C) 2008, 2010, 2011, 2013 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-
-
-
-
-
BibCirculation enables you to manage the circulation of books (and other
-items) in a traditional library. BibCirculation has 2 sides: the user (borrower)
-interface and the admin (librarian) interface. In order to being able to use the
-librarian interface you need to have the correspondent rights as Invenio user.
-
-
-
If you have rights to run BibCirculation, click on the "Administration"
-tab and select "Run Bibcirculation". You will see the so called "main menu",
-that will be present almost in every page in the librarian interface.
-
-
-
2. Items
-
-
The first you need to circulate books are books. "Item" refers to anything
-that can have a barcode. In the case of books, an item is a copy of a book. The
-first thing you need is adding copies to the system. If you already have
-digitalized data about your copies, it is recommended to write a script to add
-the copies to the database. Otherwise, you need to add them one by one.
-To do this, search the book record in Invenio, go to the 'Detailed record' view,
-then the 'Holdings' tab. If you have BibCirculation rights, you will see a link.
-This link will let you add the first copy for that record (in case it has none)
-or it will take you to the record details in the librarian interface (in case it
-already has copies) where you can find a "Add new copy" button.
-
-
You can get to the "Item details" page clicking in the book title link that
-can be found in many places around the module. You can also get to this page
-by searching a record using the "Items" in the main menu. In the "Item details"
-page the actions and the information diplayed will be different fot Periodicals
-and other records.
-
-FIXME
diff --git a/invenio/legacy/bibcirculation/scripts/__init__.py b/invenio/legacy/bibcirculation/scripts/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/invenio/legacy/bibcirculation/scripts/bibcircd.py b/invenio/legacy/bibcirculation/scripts/bibcircd.py
deleted file mode 100644
index 5f7b8aa89..000000000
--- a/invenio/legacy/bibcirculation/scripts/bibcircd.py
+++ /dev/null
@@ -1,37 +0,0 @@
-#!@PYTHON@
-# -*- mode: python; coding: utf-8; -*-
-#
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-
-__revision__ = "$Id$"
-
-# try:
-# from invenio.legacy.bibcirculation.daemon import main
-# except ImportError as e:
-# print "Error: %s" % e
-# import sys
-# sys.exit(1)
-
-from invenio.base.factory import with_app_context
-
-
-@with_app_context()
-def main():
- from invenio.legacy.bibcirculation.daemon import main as bibcirc_main
- bibcirc_main()
diff --git a/invenio/legacy/bibcirculation/templates.py b/invenio/legacy/bibcirculation/templates.py
deleted file mode 100644
index f8068335e..000000000
--- a/invenio/legacy/bibcirculation/templates.py
+++ /dev/null
@@ -1,16108 +0,0 @@
-# -*- coding: utf-8 -*-
-#
-# This file is part of Invenio.
-# Copyright (C) 2008, 2009, 2010, 2011, 2012, 2014 CERN.
-#
-# Invenio is free software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License as
-# published by the Free Software Foundation; either version 2 of the
-# License, or (at your option) any later version.
-#
-# Invenio is distributed in the hope that it will be useful, but
-# WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with Invenio; if not, write to the Free Software Foundation, Inc.,
-# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
-
-""" Templates for the bibcirculation module """
-
-__revision__ = "$Id$"
-
-import datetime
-import cgi
-from time import localtime
-import invenio.utils.date as dateutils
-from invenio.utils.url import create_html_link
-from invenio.base.i18n import gettext_set_language
-from invenio.legacy.search_engine import get_fieldvalues
-from invenio.config import CFG_SITE_URL, CFG_SITE_LANG, \
- CFG_CERN_SITE, CFG_SITE_SECURE_URL, CFG_SITE_RECORD, \
- CFG_SITE_NAME
-from invenio.base.i18n import gettext_set_language
-
-import invenio.legacy.bibcirculation.db_layer as db
-from invenio.legacy.bibcirculation.utils import get_book_cover, \
- book_information_from_MARC, \
- book_title_from_MARC, \
- renew_loan_for_X_days, \
- get_item_info_for_search_result, \
- all_copies_are_missing, \
- is_periodical, \
- looks_like_dictionary
-from invenio.legacy.bibcirculation.config import \
- CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD, \
- CFG_BIBCIRCULATION_COLLECTION, \
- CFG_BIBCIRCULATION_LIBRARY_TYPE, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_LIBRARIAN_EMAIL, \
- CFG_BIBCIRCULATION_LOANS_EMAIL, \
- CFG_BIBCIRCULATION_ILLS_EMAIL, \
- CFG_BIBCIRCULATION_ITEM_STATUS, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_SHELF, \
- CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_LOAN_STATUS_EXPIRED, \
- CFG_BIBCIRCULATION_ILL_STATUS_NEW, \
- CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED, \
- CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN, \
- CFG_BIBCIRCULATION_ILL_STATUS_RETURNED, \
- CFG_BIBCIRCULATION_ILL_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_ILL_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_ITEM_LOAN_PERIOD, \
- CFG_BIBCIRCULATION_ACQ_STATUS_NEW, \
- CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_ACQ_STATUS_PARTIAL_RECEIPT, \
- CFG_BIBCIRCULATION_ACQ_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_ACQ_STATUS_CANCELLED, \
- CFG_BIBCIRCULATION_ACQ_TYPE, \
- CFG_BIBCIRCULATION_ACQ_STATUS, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_ON_ORDER, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS_RECEIVED, \
- CFG_BIBCIRCULATION_PROPOSAL_TYPE, \
- CFG_BIBCIRCULATION_PROPOSAL_STATUS
-
-
-JQUERY_TABLESORTER_BASE = "vendors/jquery-tablesorter"
-JQUERY_TABLESORTER = JQUERY_TABLESORTER_BASE + "/jquery.tablesorter.min.js"
-
-
-def load_menu(ln=CFG_SITE_LANG):
-
- _ = gettext_set_language(ln)
-
- _MENU_ = """
-
-
-
-
- """ % {'url': CFG_SITE_URL, 'ILL': _("ILL"),
- 'Register_Book_request': _("Register Book request"),
- 'Register_Article': _("Register Article"),
- 'Register_Purchase_request': _("Register purchase request"),
- 'Search': _("Search"),
- 'Lists': _("ILL Lists"),
- 'Purchase': _("Purchase"),
- 'Proposal': _("Proposal"),
- 'ill-new': _(CFG_BIBCIRCULATION_ILL_STATUS_NEW),
- 'acq-new': _(CFG_BIBCIRCULATION_ACQ_STATUS_NEW),
- 'on_order': _(CFG_BIBCIRCULATION_ACQ_STATUS_ON_ORDER),
- 'Requested': _(CFG_BIBCIRCULATION_ILL_STATUS_REQUESTED),
- 'On_loan': _(CFG_BIBCIRCULATION_ILL_STATUS_ON_LOAN),
- 'proposal-new': _(CFG_BIBCIRCULATION_PROPOSAL_STATUS_NEW),
- 'proposal-put_aside': _(CFG_BIBCIRCULATION_PROPOSAL_STATUS_PUT_ASIDE),
- 'requests-putaside': "requests-putaside",
- 'Help': _("Help"),
- 'Admin_guide': _("Admin guide"),
- 'Contact_Support': _("Contact Support"),
- 'ln': ln}
-
- return _MENU_
-
-
-class Template:
- """
- Templates for the BibCirculation module.
- The template methods are positioned by grouping into logical
- categories('User Pages', 'Loans, Returns and Loan requests',
- 'ILLs', 'Libraries', 'Vendors' ...)
- This is also true with the calling methods in bibcirculation
- and adminlib.
- These orders should be maintained and when necessary, improved
- for readability, as and when additional methods are added.
- When applicable, methods should be renamed, refactored and
- appropriate documentation added.
- """
-
- def tmpl_infobox(self, infos, ln=CFG_SITE_LANG):
- """
- Display len(infos) information fields
- @param infos: list of strings
- @param ln: language
- @return html output
- """
- _ = gettext_set_language(ln)
- if not((type(infos) is list) or (type(infos) is tuple)):
- infos = [infos]
- infobox = ""
- for info in infos:
- infobox += "
"
- lines = info.split("\n")
- for line in lines[0:-1]:
- infobox += line + " \n"
- infobox += lines[-1] + "
\n"
- return infobox
-
- def tmpl_display_infos(self, infos, ln=CFG_SITE_LANG):
- """
- Returns a page where the only content is infoboxes.
-
- @param infos: messages to be displayed
- @type infos: list
-
- @param ln: language
- """
-
- _ = gettext_set_language(ln)
-
- out = load_menu(ln)
- out += """ """
-
- if type(infos) is not list or len(infos) == 0:
- out += """
"""
- out += _("No messages to be displayed")
- out += """
"""
- else:
- for info in infos:
- out += """
"""
- out += info
- out += """
"""
-
- return out
-
- def tmpl_holdings_information(self, recid, req, holdings_info,
- ln=CFG_SITE_LANG):
- """
- This template is used in the user interface. In this template
- it is possible to see all details (loan period, number of copies, location, etc)
- about a book.
-
- @param recid: identify the record. Primary key of bibrec.
- @type recid: int
-
- @param holdings_info: book's information (all copies)
- @type holdings_info: list
- """
- from invenio.legacy.bibcirculation.adminlib import is_adminuser
-
- (auth_code, _auth_message) = is_adminuser(req)
-
- _ = gettext_set_language(ln)
-
- if not book_title_from_MARC(recid):
- out = """
%s
- """ % (_("This record does not exist."))
- return out
-
- elif not db.has_copies(recid):
- message = _("This record has no copies.")
-
-
- if auth_code == 0:
- new_copy_link = create_html_link(CFG_SITE_URL +
- '/admin2/bibcirculation/add_new_copy_step3',
- {'recid': recid, 'ln': ln},
- _("Add a new copy"))
- message += ' ' + new_copy_link
-
- out = """
%s
- """ % (message)
- return out
-
- # verify if all copies are missing
- elif all_copies_are_missing(recid):
-
- ill_link = """%(ILL_services)s
- """ % {'url': CFG_SITE_URL, 'ln': ln,
- 'ILL_services': _("ILL services")}
-
- out = """
%(message)s.
- """ % {'message': _('All the copies of %(strong_tag_open)s%(title)s%(strong_tag_close)s are missing. You can request a copy using %(strong_tag_open)s%(ill_link)s%(strong_tag_close)s') % {'strong_tag_open': '', 'strong_tag_close': '', 'title': book_title_from_MARC(recid), 'ill_link': ill_link}}
- return out
-
- # verify if there are no copies
- elif not holdings_info:
- out = """
%s
- """ % (_("This item has no holdings."))
- return out
-
- out = """
-
-
-
- """
- else:
- out += """
- $(document).ready(function(){
- $("#table_holdings")
- .tablesorter({sortList: [[6,1],[1,0]],
- widthFixed: true,
- widgets: ['zebra']})
- .bind("sortStart",function(){$("#overlay").show();})
- .bind("sortEnd",function(){$("#overlay").hide()})
- .tablesorterPager({container: $("#pager"), positionFixed: false});
- });
-
- """
-
- out += """
-
-
-
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
-
-
- """ % (_("Options"), _("Library"), _("Collection"),
- _("Location"), _("Description"), _("Loan period"),
- _("Status"), _("Due date"), _("Barcode"))
-
- for (barcode, library, collection, location, description,
- loan_period, status, due_date) in holdings_info:
-
- if loan_period == 'Reference':
- request_button = '-'
- else:
- request_button = """
-
- """ % (CFG_SITE_URL, CFG_SITE_RECORD, recid, barcode, ln, _("Request"))
-
- if status in (CFG_BIBCIRCULATION_ITEM_STATUS_ON_ORDER,
- 'claimed'):
- expected_arrival_date = db.get_expected_arrival_date(barcode)
- if expected_arrival_date != '':
- status = status + ' - ' + expected_arrival_date
-
- if status != 'missing':
- out += """
-
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
%s
-
- """ % (request_button, library, collection or '-', location,
- description, loan_period, status, due_date or '-', barcode)
-
- if auth_code != 0:
- bibcirc_link = ''
- else:
- bibcirc_link = create_html_link(CFG_SITE_URL +
- '/admin2/bibcirculation/get_item_details',
- {'recid': recid, 'ln': ln},
- _("See this book on BibCirculation"))
-
- out += """
-
-
-
-
-
-
-
-
-
-
%s
-
-
- """ % (bibcirc_link)
-
- return out
-
- def tmpl_book_proposal_information(self, recid, msg, ln=CFG_SITE_LANG):
- """
- This template is used in the user interface. It is used to display the
- message regarding a 'proposal' of a book when the corresponding metadata
- record has been extracted from Amazon and noone has yet suggested the
- book for acquisition(No copies of the book exist yet).
-
- @param msg: information about book proposal mechanism
- @type msg: string
- """
- _ = gettext_set_language(ln)
- out = """
- """ % (_("This item is not for loan."))
- return message
-
- def tmpl_message_send_already_requested(self, ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("You already have a request on, or are in possession of this document.")
- return message
-
- def tmpl_message_request_send_ok_cern(self, ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("Your request has been registered and the document will be sent to you via internal mail.")
- return message
-
- def tmpl_message_request_send_ok_other(self, ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("Your request has been registered.")
- return message
-
- def tmpl_message_request_send_fail_cern(self, custom_msg='', ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("It is not possible to validate your request. ")
- message += custom_msg
- message += _("Please contact %(librarian_email)s") \
- % {'librarian_email': CFG_BIBCIRCULATION_LIBRARIAN_EMAIL}
- return message
-
- def tmpl_message_request_send_fail_other(self, custom_msg='', ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("It is not possible to validate your request. ")
- message += custom_msg
- message += _("Please contact %(librarian_email)s") \
- % {'librarian_email': CFG_BIBCIRCULATION_LIBRARIAN_EMAIL}
- return message
-
- def tmpl_message_proposal_send_ok_cern(self, ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("Thank you for your suggestion. We will get back to you shortly.")
- return message
-
- def tmpl_message_proposal_send_ok_other(self, ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("Thank you for your suggestion. We will get back to you shortly.")
- return message
-
- def tmpl_message_purchase_request_send_ok_other(self, ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _("Your purchase request has been registered.")
- return message
-
- def tmpl_message_sever_busy(self, ln=CFG_SITE_LANG):
- _ = gettext_set_language(ln)
- message = _('Server busy. Please, try again in a few seconds.')
- return message
-
-
- ###
- ### The two template methods below correspond to the user pages of bibcirculation.
- ###
-
-
- def tmpl_yourloans(self, loans, requests, proposals, borrower_id,
- infos, ln=CFG_SITE_LANG):
- """
- When a user is logged in, in the section 'yourloans', it is
- possible to check his loans, loan requests and book proposals.
- It is also possible to renew a single loan or all loans.
-
- @param infos: additional information in the infobox
- @param ln: language
- """
- _ = gettext_set_language(ln)
-
- renew_all_link = create_html_link(CFG_SITE_SECURE_URL +
- '/yourloans/display',
- {'borrower_id': borrower_id, 'action': 'renew_all'},
- (_("Renew all loans")))
-
- loanshistoricaloverview_link = create_html_link(CFG_SITE_SECURE_URL +
- '/yourloans/loanshistoricaloverview',
- {'ln': ln},
- (_("Loans - historical overview")))
-
- out = self.tmpl_infobox(infos, ln)
-
- if len(loans) == 0:
- out += """
-
-
-
-
%s
-
-
- """ % (_("You don't have any book on loan."))
-
- else:
- out += """
-
-
-
-
-
- """ % (loanshistoricaloverview_link,
- CFG_SITE_URL,
- _("Back to home"))
-
- return out
-
- def tmpl_loanshistoricaloverview(self, result, ln=CFG_SITE_LANG):
- """
- In the section 'yourloans' it is possible to see the historical overview of the loans
- of the user who is logged in.
-
- @param result: All loans whose status = CFG_BIBCIRCULATION_LOAN_STATUS_RETURNED
- @param ln: language
- """
-
- _ = gettext_set_language(ln)
-
- out = """
- """ % (_("Back"))
-
- return out
-
-
- ###
- ### Loans, Loan Requests, Loan Returns related templates.
- ###
-
-
- def tmpl_new_request(self, recid, barcode, action="borrowal", ln=CFG_SITE_LANG):
- """
- This template is used when a user wants to request a copy of a book.
- If a copy is avaliable (action is 'borrowal'), the 'period of interest' is solicited.
- If not AND the book record is put up for proposal (action is 'proposal'),
- user's comments are solicited.
-
- @param recid: recID - Invenio record identifier
- @param barcode: book copy's barcode
- @param action: 'borrowal'/'proposal'
- @param ln: language
- """
-
- _ = gettext_set_language(ln)
-
- today = datetime.date.today()
- gap = datetime.timedelta(days=180)
- gap_1yr = datetime.timedelta(days=360)
- more_6_months = (today + gap).strftime('%Y-%m-%d')
- more_1_year = (today + gap_1yr).strftime('%Y-%m-%d')
-
- out = """
-
-
-
-
-
-
"""
return body, errors, warnings
def get_available_kbs():
"""
Return list of KBs that are available in the system to be used with
BibEdit
"""
kb_list = [CFG_BIBEDIT_KB_SUBJECTS]
available_kbs = [kb for kb in kb_list if kb_exists(kb)]
return available_kbs
def get_marcxml_of_revision_id(recid, revid):
"""
Return MARCXML string with corresponding to revision REVID
(=RECID.REVDATE) of a record. Return empty string if revision
does not exist.
"""
job_date = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(revid).groups()
tmp_res = get_marcxml_of_record_revision(recid, job_date)
if tmp_res:
for row in tmp_res:
xml = zlib.decompress(row[0]) + "\n"
# xml contains marcxml of record
# now we create a record object from this xml and sort fields and subfields
# and return marcxml
rec = create_record(xml)[0]
record_order_subfields(rec)
marcxml = record_xml_output(rec, order_fn="_order_by_tags")
return marcxml
def perform_request_compare(ln, recid, rev1, rev2):
"""Handle a request for comparing two records"""
body = ""
errors = []
warnings = []
person1 = ""
person2 = ""
if (not record_revision_exists(recid, rev1)) or \
(not record_revision_exists(recid, rev2)):
body = "The requested record revision does not exist !"
else:
xml1 = get_marcxml_of_revision_id(recid, rev1)
xml2 = get_marcxml_of_revision_id(recid, rev2)
# Create MARC representations of the records
marc1 = create_marc_record(create_record(xml1)[0], '', {"text-marc": 1, "aleph-marc": 0})
marc2 = create_marc_record(create_record(xml2)[0], '', {"text-marc": 1, "aleph-marc": 0})
comparison = show_diff(marc1,
marc2,
prefix="
", suffix="
",
prefix_removed='',
suffix_removed='',
prefix_added='',
suffix_added='')
job_date1 = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(rev1).groups()
job_date2 = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(rev2).groups()
# Geting the author of each revision
info1 = get_info_of_record_revision(recid, job_date1)
info2 = get_info_of_record_revision(recid, job_date2)
if info1:
person1 = info1[0][1]
if info2:
person2 = info2[0][1]
body += bibedit_templates.history_comparebox(ln, job_date1, job_date2,
person1, person2, comparison)
return body, errors, warnings
def perform_request_newticket(recid, uid):
"""create a new ticket with this record's number
@param recid: record id
@param uid: user id
@return: (error_msg, url)
"""
t_url = ""
errmsg = ""
if CFG_BIBCATALOG_SYSTEM is not None:
t_id = BIBCATALOG_SYSTEM.ticket_submit(uid, "", recid, "")
if t_id:
#get the ticket's URL
t_url = BIBCATALOG_SYSTEM.ticket_get_attribute(uid, t_id, 'url_modify')
else:
errmsg = "ticket_submit failed"
else:
errmsg = "No ticket system configured"
return (errmsg, t_url)
def perform_request_ajax(req, recid, uid, data, isBulk=False):
try:
return _perform_request_ajax(req, recid, uid, data, isBulk)
except: # pylint: disable=W0702
# Custom error exception for bibedit
# We have an action log that we want to display in full
bibedit_register_exception(data)
return {'resultCode': CFG_BIBEDIT_AJAX_RESULT_CODES_REV['server_error']}
def _perform_request_ajax(req, recid, uid, data, isBulk=False):
"""Handle Ajax requests by redirecting to appropriate function."""
response = {}
request_type = data['requestType']
undo_redo = None
if "undoRedo" in data:
undo_redo = data["undoRedo"]
# Call function based on request type.
if request_type == 'searchForRecord':
# Search request.
response.update(perform_request_bibedit_search(data, req))
elif request_type in ['changeTagFormat']:
# User related requests.
response.update(perform_request_user(req, request_type, recid, data))
elif request_type in ('getRecord', 'submit', 'cancel', 'newRecord',
'deleteRecord', 'deleteRecordCache', 'prepareRecordMerge', 'revert',
'updateCacheRef', 'submittextmarc'):
# 'Major' record related requests.
response.update(perform_request_record(req, request_type, recid, uid,
data))
elif request_type in ('addField', 'addSubfields',
'addFieldsSubfieldsOnPositions', 'modifyContent',
'modifySubfieldTag', 'modifyFieldTag',
'moveSubfield', 'deleteFields', 'moveField',
'modifyField', 'otherUpdateRequest',
'disableHpChange', 'deactivateHoldingPenChangeset'):
# Record updates.
cacheMTime = data['cacheMTime']
if 'hpChanges' in data:
hpChanges = data['hpChanges']
else:
hpChanges = {}
response.update(perform_request_update_record(request_type, recid,
uid, cacheMTime, data,
hpChanges, undo_redo,
isBulk))
elif request_type in ('autosuggest', 'autocomplete', 'autokeyword'):
response.update(perform_request_autocomplete(request_type, recid, uid,
data))
elif request_type in ('getTickets', 'closeTicket', 'openTicket', 'createTicket','getNewTicketRTInfo'):
# BibCatalog requests.
response.update(perform_request_bibcatalog(request_type, uid, data))
elif request_type in ('getHoldingPenUpdates', ):
response.update(perform_request_holdingpen(request_type, recid))
elif request_type in ('getHoldingPenUpdateDetails',
'deleteHoldingPenChangeset'):
updateId = data['changesetNumber']
response.update(perform_request_holdingpen(request_type, recid,
updateId))
elif request_type in ('applyBulkUpdates', ):
# a general version of a bulk request
changes = data['requestsData']
cacheMTime = data['cacheMTime']
response.update(perform_bulk_request_ajax(req, recid, uid, changes,
undo_redo, cacheMTime))
elif request_type in ('preview', ):
response.update(perform_request_preview_record(request_type, recid, uid, data))
elif request_type in ('get_pdf_url', ):
response.update(perform_request_get_pdf_url(recid))
elif request_type in ('refextract', ):
txt = None
if 'txt' in data:
txt = data["txt"]
response.update(perform_request_ref_extract(recid, uid, txt))
elif request_type in ('refextracturl', ):
response.update(perform_request_ref_extract_url(recid, uid, data['url']))
elif request_type == 'getTextMarc':
response.update(perform_request_get_textmarc(recid, uid))
elif request_type == "getTableView":
response.update(perform_request_get_tableview(recid, uid, data))
elif request_type == "DOISearch":
response.update(perform_doi_search(data['doi']))
elif request_type == "deactivateRecordCache":
deactivate_cache(recid, uid)
response.update({"cacheMTime": data['cacheMTime']})
elif request_type == "guessAffiliations":
response.update(perform_guess_affiliations(uid, data))
return response
def perform_bulk_request_ajax(req, recid, uid, reqsData, undoRedo, cacheMTime):
""" An AJAX handler used when treating bulk updates """
lastResult = {}
lastTime = cacheMTime
if get_cache_mtime(recid, uid) != cacheMTime:
return {"resultCode": 107}
isFirst = True
for data in reqsData:
assert data is not None
data['cacheMTime'] = lastTime
if isFirst and undoRedo is not None:
# we add the undo/redo handler to the first operation in order to
# save the handler on the server side !
data['undoRedo'] = undoRedo
isFirst = False
lastResult = _perform_request_ajax(req, recid, uid, data, isBulk=True)
lastTime = lastResult['cacheMTime']
return lastResult
def perform_request_bibedit_search(data, req):
"""Handle search requests."""
response = {}
searchType = data['searchType']
if searchType is None:
searchType = "anywhere"
searchPattern = data['searchPattern']
if searchType == 'anywhere':
pattern = searchPattern
else:
pattern = searchType + ':' + searchPattern
pattern = urllib.unquote(pattern)
result_set = list(perform_request_search(req=req, p=pattern))
response['resultCode'] = 1
response['resultSet'] = result_set[0:cfg['CFG_BIBEDIT_MAX_SEARCH_RESULTS']]
return response
def perform_request_user(req, request_type, recid, data):
"""Handle user related requests."""
response = {}
if request_type == 'changeTagFormat':
tagformat_settings = session_param_get(req, 'bibedit_tagformat', {})
tagformat_settings[recid] = data['tagFormat']
session_param_set(req, 'bibedit_tagformat', tagformat_settings)
response['resultCode'] = 2
return response
def perform_request_holdingpen(request_type, recId, changeId=None):
"""
A method performing the holdingPen ajax request. The following types of
requests can be made::
-getHoldingPenUpdates: retrieving the holding pen updates pending
for a given record
"""
response = {}
if request_type == 'getHoldingPenUpdates':
changeSet = get_related_hp_changesets(recId)
changes = []
for change in changeSet:
changes.append((str(change[0]), str(change[1])))
changes.reverse() # newest to older order
response["changes"] = changes
elif request_type == 'getHoldingPenUpdateDetails':
# returning the list of changes related to the holding pen update
# the format based on what the record difference xtool returns
assert(changeId is not None)
hpContent = get_hp_update_xml(changeId)
holdingPenRecord = create_record(hpContent[0], "xm")[0]
if not holdingPenRecord:
response['resultCode'] = 107
else:
template_to_merge = extend_record_with_template(recId)
if template_to_merge:
merged_record = merge_record_with_template(holdingPenRecord,
template_to_merge,
is_hp_record=True)
if merged_record:
holdingPenRecord = merged_record
# order subfields alphabetically
record_order_subfields(holdingPenRecord)
# databaseRecord = get_record(hpContent[1])
response['record'] = holdingPenRecord
response['changeset_number'] = changeId
elif request_type == 'deleteHoldingPenChangeset':
assert(changeId is not None)
delete_hp_change(changeId)
return response
def perform_request_record(req, request_type, recid, uid, data, ln=CFG_SITE_LANG):
"""Handle 'major' record related requests like fetching, submitting or
deleting a record, cancel editing or preparing a record for merging.
"""
response = {}
if request_type == 'newRecord':
# Create a new record.
new_recid = reserve_record_id()
new_type = data['newType']
if new_type == 'empty':
# Create a new empty record.
create_cache(recid, uid)
response['resultCode'], response['newRecID'] = 6, new_recid
elif new_type == 'template':
# Create a new record from XML record template.
template_filename = data['templateFilename']
template = get_record_template(template_filename)
if not template:
response['resultCode'] = 108
else:
record = create_record(template)[0]
if not record:
response['resultCode'] = 109
else:
record_add_field(record, '001',
controlfield_value=str(new_recid))
create_cache(new_recid, uid, record, True)
response['cacheMTime'] = get_cache_mtime(new_recid, uid)
response['resultCode'], response['newRecID'] = 7, new_recid
elif new_type == 'import':
# Import data from external source, using DOI
doi = data['doi']
if not doi:
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_no_doi_specified']
else:
try:
marcxml_template = get_marcxml_for_doi(doi)
except CrossrefError as inst:
response['resultCode'] = \
cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV'][inst.code]
else:
record = crossref_process_template(marcxml_template, CFG_INSPIRE_SITE)
if not record:
response['resultCode'] = 109
else:
record_add_field(record, '001',
controlfield_value=str(new_recid))
template_to_merge = extend_record_with_template(recstruct=record)
if template_to_merge:
merged_record = merge_record_with_template(record, template_to_merge)
if merged_record:
record = merged_record
create_cache(new_recid, uid, record, True)
response['cacheMTime'] = get_cache_mtime(new_recid, uid)
response['resultCode'], response['newRecID'] = 7, new_recid
elif new_type == 'clone':
# Clone an existing record (from the users cache).
existing_cache = cache_exists(recid, uid)
if existing_cache:
try:
cache = get_cache_contents(recid, uid)
record = cache[2]
except InvalidCache:
# if, for example, the cache format was wrong (outdated)
record = get_bibrecord(recid)
else:
# Cache missing. Fall back to using original version.
record = get_bibrecord(recid)
record_delete_field(record, '001')
record_delete_field(record, '005')
record_add_field(record, '001', controlfield_value=str(new_recid))
create_cache(new_recid, uid, record, True)
response['resultCode'], response['newRecID'] = 8, new_recid
elif request_type == 'getRecord':
# Fetch the record. Possible error situations:
# - Non-existing record
# - Deleted record
# - Record locked by other user
# - Record locked by queue
# A cache file will be created if it does not exist.
# If the cache is outdated (i.e., not based on the latest DB revision),
# cacheOutdated will be set to True in the response.
record_status = record_exists(recid)
existing_cache = cache_exists(recid, uid)
read_only_mode = False
if "inReadOnlyMode" in data:
read_only_mode = data['inReadOnlyMode']
if data.get('deleteRecordCache'):
delete_cache(recid, uid)
existing_cache = False
pending_changes = []
disabled_hp_changes = {}
if record_status == 0:
response['resultCode'] = 102
elif not read_only_mode and not existing_cache and \
record_locked_by_other_user(recid, uid):
name, email, locked_since = record_locked_by_user_details(recid, uid)
response['locked_details'] = {'name': name,
'email': email,
'locked_since': locked_since}
response['resultCode'] = 104
elif not read_only_mode and existing_cache and \
cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = 104
elif not read_only_mode and record_locked_by_queue(recid):
response['resultCode'] = 105
else:
if read_only_mode:
if 'recordRevision' in data and data['recordRevision'] != 'sampleValue':
record_revision_ts = data['recordRevision']
record_xml = get_marcxml_of_revision(recid,
record_revision_ts)
record = create_record(record_xml)[0]
record_revision = timestamp_to_revision(record_revision_ts)
pending_changes = []
disabled_hp_changes = {}
else:
# a normal cacheless retrieval of a record
record = get_bibrecord(recid)
record_revision = get_record_last_modification_date(recid)
if record_revision is None:
record_revision = datetime.now().timetuple()
pending_changes = []
disabled_hp_changes = {}
cache_dirty = False
mtime = 0
undo_list = []
redo_list = []
else:
try:
cache_dirty, record_revision, record, pending_changes, \
disabled_hp_changes, undo_list, redo_list = \
get_cache_contents(recid, uid)
except InvalidCache:
# No cache found in the DB
record_revision, record = create_cache(recid, uid)
if not record:
response['resultCode'] = 103
return response
pending_changes = []
disabled_hp_changes = {}
cache_dirty = False
undo_list = []
redo_list = []
else:
touch_cache(recid, uid)
if not latest_record_revision(recid, record_revision) and \
get_record_revisions(recid) != ():
# This sould prevent from using old cache in case of
# viewing old version. If there are no revisions,
# it means we should skip this step because this
# is a new record
response['cacheOutdated'] = True
mtime = get_cache_mtime(recid, uid)
if data.get('clonedRecord', ''):
response['resultCode'] = 9
else:
response['resultCode'] = 3
revision_author = get_record_revision_author(recid, record_revision)
latest_revision = get_record_last_modification_date(recid)
if latest_revision is None:
latest_revision = datetime.now().timetuple()
last_revision_ts = revision_to_timestamp(latest_revision)
revisions_history = get_record_revision_timestamps(recid)
revisions_authors = get_record_revision_authors(recid)
- number_of_physical_copies = get_number_copies(recid)
- bibcirc_details_URL = create_item_details_url(recid, ln)
+ number_of_physical_copies = 0
+ bibcirc_details_URL = None
can_have_copies = can_record_have_physical_copies(recid)
managed_DOIs = [doi for doi in record_extract_dois(record) if \
re.compile(CFG_BIBUPLOAD_INTERNAL_DOI_PATTERN).match(doi)]
# For some collections, merge template with record
template_to_merge = extend_record_with_template(recid)
if template_to_merge and not read_only_mode:
merged_record = merge_record_with_template(record, template_to_merge)
if merged_record:
record = merged_record
mtime = update_cache_contents(recid, uid, record_revision,
record, pending_changes,
disabled_hp_changes,
undo_list, redo_list)
if record_status == -1:
# The record was deleted
response['resultCode'] = 103
response['record_has_pdf'] = record_has_fulltext(recid)
response['record_hide_authors'] = check_hide_authors(record)
response['cacheDirty'], response['record'], \
response['cacheMTime'], response['recordRevision'], \
response['revisionAuthor'], response['lastRevision'], \
response['revisionsHistory'], response['revisionsAuthors'], \
response['inReadOnlyMode'], response['pendingHpChanges'], \
response['disabledHpChanges'], response['undoList'], \
response['redoList'] = cache_dirty, \
record, mtime, revision_to_timestamp(record_revision), \
revision_author, last_revision_ts, revisions_history, \
revisions_authors, read_only_mode, pending_changes, \
disabled_hp_changes, undo_list, redo_list
response['numberOfCopies'] = number_of_physical_copies
response['managed_DOIs'] = managed_DOIs
response['bibCirculationUrl'] = bibcirc_details_URL
response['canRecordHavePhysicalCopies'] = can_have_copies
# Set tag format from user's session settings.
tagformat_settings = session_param_get(req, 'bibedit_tagformat')
tagformat = (tagformat_settings is not None) and tagformat_settings.get(recid, cfg['CFG_BIBEDIT_TAG_FORMAT']) or cfg['CFG_BIBEDIT_TAG_FORMAT']
response['tagFormat'] = tagformat
# KB information
response['KBSubject'] = CFG_BIBEDIT_KB_SUBJECTS
# Autocomplete information
response['primaryCollection'] = guess_primary_collection_of_a_record(recid)
elif request_type == 'submit':
# Submit the record. Possible error situations:
# - Missing cache file
# - Cache file modified in other editor
# - Record locked by other user
# - Record locked by queue
# If the cache is outdated cacheOutdated will be set to True in the
# response.
perform_request_submit(recid=recid,
uid=uid,
data=data,
response=response)
elif request_type == 'revert':
revId = data['revId']
job_date = "%s-%s-%s %s:%s:%s" % re_revdate_split.search(revId).groups()
revision_xml = get_marcxml_of_revision(recid, job_date)
# Modify the 005 tag in order to merge with the latest version of record
last_revision_ts = data['lastRevId'] + ".0"
revision_xml = modify_record_timestamp(revision_xml, last_revision_ts)
save_xml_record(recid, uid, revision_xml)
if (cache_exists(recid, uid)):
delete_cache(recid, uid)
response['resultCode'] = 4
elif request_type == 'cancel':
# Cancel editing by deleting the cache file. Possible error situations:
# - Cache file modified in other editor
if cache_exists(recid, uid):
if get_cache_mtime(recid, uid) == data['cacheMTime']:
delete_cache(recid, uid)
response['resultCode'] = 5
else:
response['resultCode'] = 107
else:
response['resultCode'] = 5
elif request_type == 'deleteRecord':
# Submit the record. Possible error situations:
# - Record locked by other user
# - Record locked by queue
# As the user is requesting deletion we proceed even if the cache file
# is missing and we don't check if the cache is outdated or has
# been modified in another editor.
existing_cache = cache_exists(recid, uid)
pending_changes = []
- if has_copies(recid):
- response['resultCode'] = \
- cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_physical_copies_exist']
- elif existing_cache and cache_expired(recid, uid) and \
+ if existing_cache and cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = \
cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_rec_locked_by_user']
elif record_locked_by_queue(recid):
response['resultCode'] = \
cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_rec_locked_by_queue']
else:
if not existing_cache:
create_cache(recid, uid)
record_revision, record, pending_changes, \
deactivated_hp_changes, undo_list, redo_list = \
get_cache_contents(recid, uid)[1:]
else:
try:
dummy_cache_dirty, record_revision, record, \
pending_changes, deactivated_hp_changes, undo_list, \
redo_list = get_cache_contents(recid, uid)
except InvalidCache:
record_revision, record, pending_changes, \
deactivated_hp_changes = create_cache(recid, uid)
record_add_field(record, '980', ' ', ' ', '', [('c', 'DELETED')])
undo_list = []
redo_list = []
update_cache_contents(recid, uid, record_revision, record,
pending_changes, deactivated_hp_changes,
undo_list, redo_list)
save_xml_record(recid, uid)
delete_related_holdingpen_changes(recid) # we don't need any changes
# related to a deleted record
response['resultCode'] = 10
elif request_type == 'deleteRecordCache':
# Delete the cache file. Ignore the request if the cache has been
# modified in another editor.
if 'cacheMTime' in data:
if cache_exists(recid, uid) and get_cache_mtime(recid, uid) == \
data['cacheMTime']:
delete_cache(recid, uid)
response['resultCode'] = 11
elif request_type == 'updateCacheRef':
# Update cache with the contents coming from BibEdit JS interface
# Used when updating references using ref extractor
record_revision, record, pending_changes, \
deactivated_hp_changes, undo_list, redo_list = \
get_cache_contents(recid, uid)[1:]
record = create_record(data['recXML'])[0]
response['cacheMTime'] = update_cache_contents(recid,
uid,
record_revision,
record,
pending_changes,
deactivated_hp_changes,
undo_list,
redo_list)
response['cacheDirty'] = True
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['cache_updated_with_references']
elif request_type == 'prepareRecordMerge':
# We want to merge the cache with the current DB version of the record,
# so prepare an XML file from the file cache, to be used by BibMerge.
# Possible error situations:
# - Missing cache file
# - Record locked by other user
# - Record locked by queue
# We don't check if cache is outdated (a likely scenario for this
# request) or if it has been modified in another editor.
if not cache_exists(recid, uid):
response['resultCode'] = 106
elif cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = 104
elif record_locked_by_queue(recid):
response['resultCode'] = 105
else:
save_xml_record(recid, uid, to_upload=False, to_merge=True)
response['resultCode'] = 12
elif request_type == 'submittextmarc':
# Textmarc content coming from the user
textmarc_record = data['textmarc']
xml_conversion_status = get_xml_from_textmarc(recid, textmarc_record, uid)
if xml_conversion_status['resultMsg'] == "textmarc_parsing_error":
response.update(xml_conversion_status)
return response
# Simulate upload to catch errors
errors_upload = perform_upload_check(xml_conversion_status['resultXML'], '--replace')
if errors_upload:
response['resultCode'], response['errors'] = 113, \
errors_upload
return response
response.update(xml_conversion_status)
if xml_conversion_status['resultMsg'] == 'textmarc_parsing_success':
create_cache(recid, uid,
create_record(response['resultXML'])[0])
save_xml_record(recid, uid)
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']["record_submitted"]
return response
def perform_upload_check(xml_record, mode):
"""Perform a upload simulation with the given record and mode.
@return: string describing errors
@rtype: string
"""
import invenio.legacy.bibupload.engine as bibupload_module
from invenio.legacy.bibupload.engine import xml_marc_to_records, bibupload
from invenio.legacy.bibrecord import \
record_strip_empty_volatile_subfields, \
record_strip_empty_fields
error_cache = []
def my_writer(msg, stream=sys.stdout, verbose=1):
if verbose == 1:
if 'DONE' not in msg:
error_cache.append(msg.strip())
orig_writer = bibupload_module.write_message
bibupload_module.write_message = my_writer
error_cache.extend(perform_basic_upload_checks(xml_record))
if error_cache:
# There has been some critical error
return '\n'.join(error_cache)
recs = xml_marc_to_records(xml_record)
try:
upload_mode = mode[2:]
# Adapt input data for bibupload function
if upload_mode == "r insert-or-replace":
upload_mode = "replace_or_insert"
for record in recs:
if record:
record_strip_empty_volatile_subfields(record)
record_strip_empty_fields(record)
bibupload(record, opt_mode=upload_mode, pretend=True)
finally:
bibupload_module.write_message = orig_writer
return '\n'.join(error_cache)
def perform_basic_upload_checks(xml_record):
""" Performs tests that would provoke the bibupload task to fail with
an exit status 1, to prevent batchupload from crashing while alarming
the user wabout the issue
"""
from invenio.legacy.bibupload.engine import writing_rights_p
from invenio.legacy.bibrecord import create_records
errors = []
if not writing_rights_p():
errors.append("Error: BibUpload does not have rights to write fulltext files.")
recs = create_records(xml_record, 1, 1)
if recs == []:
errors.append("Error: Cannot parse MARCXML file.")
elif recs[0][0] is None:
errors.append("Error: MARCXML file has wrong format: %s" % recs)
return errors
def perform_request_update_record(request_type, recid, uid, cacheMTime, data,
hpChanges, undoRedoOp, isBulk=False):
"""
Handle record update requests like adding, modifying, moving or deleting
of fields or subfields. Possible common error situations::
- Missing cache file
- Cache file modified in other editor
@param undoRedoOp: Indicates in "undo"/"redo"/undo_descriptor operation is
performed by a current request.
"""
response = {}
if not cache_exists(recid, uid):
response['resultCode'] = 106
elif get_cache_mtime(recid, uid) != cacheMTime and isBulk is False:
# In case of a bulk request, the changes are deliberately performed
# immediately one after another
response['resultCode'] = 107
else:
record_revision, record, pending_changes, deactivated_hp_changes, \
undo_list, redo_list = get_cache_contents(recid, uid)[1:]
# process all the Holding Pen changes operations ... regardles the
# request type
if "toDisable" in hpChanges:
for changeId in hpChanges["toDisable"]:
pending_changes[changeId]["applied_change"] = True
if "toEnable" in hpChanges:
for changeId in hpChanges["toEnable"]:
pending_changes[changeId]["applied_change"] = False
if "toOverride" in hpChanges:
pending_changes = hpChanges["toOverride"]
if "changesetsToDeactivate" in hpChanges:
for changesetId in hpChanges["changesetsToDeactivate"]:
deactivated_hp_changes[changesetId] = True
if "changesetsToActivate" in hpChanges:
for changesetId in hpChanges["changesetsToActivate"]:
deactivated_hp_changes[changesetId] = False
# processing the undo/redo entries
if undoRedoOp == "undo":
try:
redo_list = [undo_list[-1]] + redo_list
undo_list = undo_list[:-1]
except:
raise Exception("An exception occured when undoing previous" +
" operation. Undo list: " + str(undo_list) +
" Redo list " + str(redo_list))
elif undoRedoOp == "redo":
try:
undo_list = undo_list + [redo_list[0]]
redo_list = redo_list[1:]
except:
raise Exception("An exception occured when redoing previous" +
" operation. Undo list: " + str(undo_list) +
" Redo list " + str(redo_list))
else:
# This is a genuine operation - we have to add a new descriptor
# to the undo list and cancel the redo unless the operation is
# a bulk operation
if undoRedoOp is not None:
undo_list = undo_list + [undoRedoOp]
redo_list = []
else:
assert isBulk is True
field_position_local = data.get('fieldPosition')
if field_position_local is not None:
field_position_local = int(field_position_local)
if request_type == 'otherUpdateRequest':
# An empty request. Might be useful if we want to perform
# operations that require only the actions performed globally,
# like modifying the holdingPen changes list
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV'][
'editor_modifications_changed']
elif request_type == 'deactivateHoldingPenChangeset':
# the changeset has been marked as processed ( user applied it in
# the editor). Marking as used in the cache file.
# CAUTION: This function has been implemented here because logically
# it fits with the modifications made to the cache file.
# No changes are made to the Holding Pen physically. The
# changesets are related to the cache because we want to
# cancel the removal every time the cache disappears for
# any reason
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV'][
'disabled_hp_changeset']
elif request_type == 'addField':
if data['controlfield']:
record_add_field(record, data['tag'],
controlfield_value=data['value'])
response['resultCode'] = 20
else:
record_add_field(record, data['tag'], data['ind1'],
data['ind2'], subfields=data['subfields'],
field_position_local=field_position_local)
response['resultCode'] = 21
elif request_type == 'addSubfields':
subfields = data['subfields']
for subfield in subfields:
record_add_subfield_into(record, data['tag'], subfield[0],
subfield[1], subfield_position=None,
field_position_local=field_position_local)
if len(subfields) == 1:
response['resultCode'] = 22
else:
response['resultCode'] = 23
elif request_type == 'addFieldsSubfieldsOnPositions':
#1) Sorting the fields by their identifiers
fieldsToAdd = data['fieldsToAdd']
subfieldsToAdd = data['subfieldsToAdd']
for tag in fieldsToAdd.keys():
positions = fieldsToAdd[tag].keys()
positions.sort()
for position in positions:
# now adding fields at a position
isControlfield = (len(fieldsToAdd[tag][position][0]) == 0)
# if there are n subfields, this is a control field
if isControlfield:
controlfieldValue = fieldsToAdd[tag][position][3]
record_add_field(record, tag,
field_position_local=int(position),
controlfield_value=controlfieldValue)
else:
subfields = fieldsToAdd[tag][position][0]
ind1 = fieldsToAdd[tag][position][1]
ind2 = fieldsToAdd[tag][position][2]
record_add_field(record, tag, ind1, ind2,
subfields=subfields,
field_position_local=int(position))
# now adding the subfields
for tag in subfieldsToAdd.keys():
for fieldPosition in subfieldsToAdd[tag].keys(): # now the fields
# order not important !
subfieldsPositions = subfieldsToAdd[tag][fieldPosition]. \
keys()
subfieldsPositions.sort()
for subfieldPosition in subfieldsPositions:
subfield = subfieldsToAdd[tag][fieldPosition][subfieldPosition]
record_add_subfield_into(record, tag, subfield[0], subfield[1],
subfield_position=int(subfieldPosition),
field_position_local=int(fieldPosition))
response['resultCode'] = \
cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['added_positioned_subfields']
elif request_type == 'modifyField': # changing the field structure
# first remove subfields and then add new... change the indices
subfields = data['subFields'] # parse the JSON representation of
# the subfields here
new_field = create_field(subfields, data['ind1'], data['ind2'])
record_replace_field(record, data['tag'], new_field,
field_position_local=data['fieldPosition'])
response['resultCode'] = 26
elif request_type == 'modifyContent':
if data['subfieldIndex'] is not None:
record_modify_subfield(record, data['tag'],
data['subfieldCode'], data['value'],
int(data['subfieldIndex']),
field_position_local=field_position_local)
else:
record_modify_controlfield(record, data['tag'], data["value"],
field_position_local=field_position_local)
response['resultCode'] = 24
elif request_type == 'modifySubfieldTag':
record_add_subfield_into(record, data['tag'], data['subfieldCode'],
data["value"], subfield_position= int(data['subfieldIndex']),
field_position_local=field_position_local)
record_delete_subfield_from(record, data['tag'], int(data['subfieldIndex']) + 1,
field_position_local=field_position_local)
response['resultCode'] = 24
elif request_type == 'modifyFieldTag':
subfields = record_get_subfields(record, data['oldTag'],
field_position_local=field_position_local)
record_add_field(record, data['newTag'], data['ind1'],
data['ind2'] , subfields=subfields)
record_delete_field(record, data['oldTag'], ind1=data['oldInd1'],
ind2=data['oldInd2'], field_position_local=field_position_local)
response['resultCode'] = 32
elif request_type == 'moveSubfield':
record_move_subfield(record, data['tag'],
int(data['subfieldIndex']), int(data['newSubfieldIndex']),
field_position_local=field_position_local)
response['resultCode'] = 25
elif request_type == 'moveField':
if data['direction'] == 'up':
final_position_local = field_position_local-1
else: # direction is 'down'
final_position_local = field_position_local+1
record_move_fields(record, data['tag'], [field_position_local],
final_position_local)
response['resultCode'] = 32
elif request_type == 'deleteFields':
to_delete = data['toDelete']
deleted_fields = 0
deleted_subfields = 0
for tag in to_delete:
#Sorting the fields in a edcreasing order by the local position!
fieldsOrder = to_delete[tag].keys()
fieldsOrder.sort(lambda a, b: int(b) - int(a))
for field_position_local in fieldsOrder:
if not to_delete[tag][field_position_local]:
# No subfields specified - delete entire field.
record_delete_field(record, tag,
field_position_local=int(field_position_local))
deleted_fields += 1
else:
for subfield_position in \
to_delete[tag][field_position_local][::-1]:
# Delete subfields in reverse order (to keep the
# indexing correct).
record_delete_subfield_from(record, tag,
int(subfield_position),
field_position_local=int(field_position_local))
deleted_subfields += 1
if deleted_fields == 1 and deleted_subfields == 0:
response['resultCode'] = 26
elif deleted_fields and deleted_subfields == 0:
response['resultCode'] = 27
elif deleted_subfields == 1 and deleted_fields == 0:
response['resultCode'] = 28
elif deleted_subfields and deleted_fields == 0:
response['resultCode'] = 29
else:
response['resultCode'] = 30
response['cacheMTime'] = update_cache_contents(recid,
uid,
record_revision,
record,
pending_changes,
deactivated_hp_changes,
undo_list, redo_list)
response['cacheDirty'] = True
return response
def perform_request_autocomplete(request_type, recid, uid, data):
"""
Perfrom an AJAX request associated with the retrieval of autocomplete
data.
@param request_type: Type of the currently served request
@param recid: the identifer of the record
@param uid: The identifier of the user being currently logged in
@param data: The request data containing possibly important additional
arguments
"""
response = {}
# get the values based on which one needs to search
searchby = data['value']
# we check if the data is properly defined
fulltag = ''
if 'maintag' in data and 'subtag1' in data and \
'subtag2' in data and 'subfieldcode' in data:
maintag = data['maintag']
subtag1 = data['subtag1']
subtag2 = data['subtag2']
u_subtag1 = subtag1
u_subtag2 = subtag2
if (not subtag1) or (subtag1 == ' '):
u_subtag1 = '_'
if (not subtag2) or (subtag2 == ' '):
u_subtag2 = '_'
subfieldcode = data['subfieldcode']
fulltag = maintag+u_subtag1+u_subtag2+subfieldcode
if (request_type == 'autokeyword'):
# call the keyword-form-ontology function
if fulltag and searchby:
items = get_kbt_items_for_bibedit(cfg['CFG_BIBEDIT_KEYWORD_TAXONOMY'],
cfg['CFG_BIBEDIT_KEYWORD_RDFLABEL'],
searchby)
response['autokeyword'] = items
if (request_type == 'autosuggest'):
# call knowledge base function to put the suggestions in an array..
if fulltag and searchby and len(searchby) > 3:
# add trailing '*' wildcard for 'search_unit_in_bibxxx()' if not already present
suggest_values = get_kbd_values_for_bibedit(fulltag, "", searchby+"*")
# remove ..
new_suggest_vals = []
for sugg in suggest_values:
if sugg.startswith(searchby):
new_suggest_vals.append(sugg)
response['autosuggest'] = new_suggest_vals
if (request_type == 'autocomplete'):
# call the values function with the correct kb_name
if fulltag in cfg['CFG_BIBEDIT_AUTOCOMPLETE_TAGS_KBS']:
kbname = cfg['CFG_BIBEDIT_AUTOCOMPLETE_TAGS_KBS'][fulltag]
# check if the seachby field has semicolons. Take all
# the semicolon-separated items..
items = []
vals = []
if searchby:
if searchby.rfind(';'):
items = searchby.split(';')
else:
items = [searchby.strip()]
for item in items:
item = item.strip()
kbrvals = get_kbr_values(kbname, item, '', 'e') # we want an exact match
if kbrvals and kbrvals[0]: # add the found val into vals
vals.append(kbrvals[0])
#check that the values are not already contained in other
#instances of this field
record = get_cache_contents(recid, uid)[2]
xml_rec = wash_for_xml(print_rec(record))
record, status_code, dummy_errors = create_record(xml_rec)
existing_values = []
if (status_code != 0):
existing_values = record_get_field_values(record,
maintag,
subtag1,
subtag2,
subfieldcode)
#get the new values.. i.e. vals not in existing
new_vals = vals
for val in new_vals:
if val in existing_values:
new_vals.remove(val)
response['autocomplete'] = new_vals
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['autosuggestion_scanned']
return response
def perform_request_bibcatalog(request_type, uid, data):
"""Handle request to BibCatalog (RT).
"""
response = {}
if request_type == 'getTickets':
# Insert the tickets data in the response, if possible
if not CFG_BIBCATALOG_SYSTEM or not CFG_CAN_SEARCH_FOR_TICKET:
response['tickets'] = ""
elif uid:
bibcat_resp = BIBCATALOG_SYSTEM.check_system(uid)
if bibcat_resp == "":
tickets_found = BIBCATALOG_SYSTEM.ticket_search(uid,
status=['new', 'open'], recordid=data['recID'])
tickets = []
for t_id in tickets_found:
ticket_info = BIBCATALOG_SYSTEM.ticket_get_info(
uid, t_id, ['url_display', 'url_close', 'subject', 'text', 'queue', 'created'])
t_url = ticket_info['url_display']
t_close_url = ticket_info['url_close']
t_subject = ticket_info['subject']
t_text = ticket_info['text']
t_queue = ticket_info['queue']
date_string = ticket_info['created']
date_splitted = date_string.split(" ")
# convert date to readable format
try:
t_date = date_splitted[2] + ' ' + date_splitted[1] +\
" " + date_splitted[4] + " " +\
date_splitted[3].split(":")[0] + ":" +\
date_splitted[3].split(":")[1]
except IndexError:
t_date = date_string
ticket = {"id": str(t_id), "queue": t_queue, "date": t_date, "url": t_url,
"close_url": t_close_url, "subject": t_subject, "text": t_text}
tickets.append(ticket)
response['tickets'] = tickets
response['resultCode'] = 31
else:
# put something in the tickets container, for debug
response['tickets'] = "Error connecting to RT"
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_rt_connection']
# closeTicket usecase
elif request_type == 'closeTicket':
if not CFG_BIBCATALOG_SYSTEM or not CFG_CAN_SEARCH_FOR_TICKET:
response['ticket_closed_description'] = ""
response['ticket_closed_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_ticket_closed']
elif uid:
bibcat_resp = BIBCATALOG_SYSTEM.check_system(uid)
if bibcat_resp == "":
un, pw = get_bibcat_from_prefs(uid)
if un and pw:
BIBCATALOG_SYSTEM.ticket_steal(uid, data['ticketid'])
ticket_closed = BIBCATALOG_SYSTEM.ticket_set_attribute(uid, data['ticketid'], 'status', 'resolved')
if ticket_closed == 1:
response['ticket_closed_description'] = 'Ticket resolved'
response['ticket_closed_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['ticket_closed']
else:
response['ticket_closed_description'] = 'Ticket could not be resolved.Try again'
response['ticket_closed_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_ticket_closed']
else:
response['ticket_closed_description'] = 'RT user does not exist'
response['ticket_closed_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_ticket_closed']
else:
#put something in the tickets container, for debug
response['ticket_closed_description'] = "Error connecting to RT"
response['ticket_closed_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_rt_connection']
response['ticketid'] = data['ticketid']
elif request_type == 'openTicket':
if not CFG_BIBCATALOG_SYSTEM or not CFG_CAN_SEARCH_FOR_TICKET:
response['ticket_opened_description'] = ""
response['ticket_opened_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_ticket_opened']
elif uid:
bibcat_resp = BIBCATALOG_SYSTEM.check_system(uid)
if bibcat_resp == "":
un, pw = get_bibcat_from_prefs(uid)
if un and pw:
ticket_opened = BIBCATALOG_SYSTEM.ticket_set_attribute(uid, data['ticketid'], 'status', 'open')
if ticket_opened == 1:
response['ticket_opened_description'] = 'Ticket opened'
response['ticket_opened_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['ticket_opened']
else:
response['ticket_opened_description'] = 'Ticket could not be opened.Try again'
response['ticket_opened_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_ticket_opened']
else:
response['ticket_opened_description'] = 'RT user does not exist'
response['ticket_opened_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_ticket_opened']
else:
#put something in the tickets container, for debug
response['ticket_opened_description'] = "Error connecting to RT"
response['ticket_opened_code'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['error_rt_connection']
response['ticketid'] = data['ticketid']
elif request_type == 'createTicket':
if BIBCATALOG_SYSTEM is None:
response['ticket_created_description'] = ""
response['ticket_created_code'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV['error_ticket_created']
elif BIBCATALOG_SYSTEM and uid:
bibcat_resp = BIBCATALOG_SYSTEM.check_system(uid)
if bibcat_resp == "":
un, pw = get_bibcat_from_prefs(uid)
if un and pw:
ticket_created = BIBCATALOG_SYSTEM.ticket_submit(uid, data['subject'], data['recID'],
data['text'], data['queue'], data['priority'], data['owner'], data['requestor'])
if ticket_created:
response['ticket_created_description'] = ticket_created
response['ticket_created_code'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV['ticket_created']
else:
response['ticket_created_description'] = 'Ticket could not be created.Try again'
response['ticket_created_code'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV['error_ticket_created']
else:
response['ticket_created_description'] = 'RT user does not exist'
response['ticket_created_code'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV['error_ticket_created']
else:
#put something in the tickets container, for debug
response['ticket_created_description'] = "Error connecting to RT"
response['ticket_created_code'] = CFG_BIBEDIT_AJAX_RESULT_CODES_REV['error_rt_connection']
elif request_type == 'getNewTicketRTInfo':
# Insert the tickets data in the response, if possible
response = get_new_ticket_RT_info(uid, data['recID'])
return response
def _add_curated_references_to_record(recid, uid, bibrec):
"""
Adds references from the cache that have been curated (contain $$9CURATOR)
to the bibrecord object
@param recid: record id, used to retrieve cache
@param uid: id of the current user, used to retrieve cache
@param bibrec: bibrecord object to add references to
"""
dummy1, dummy2, record, dummy3, dummy4, dummy5, dummy6 = get_cache_contents(recid, uid)
for field_instance in record_get_field_instances(record, "999", "C", "5"):
for subfield_instance in field_instance[0]:
if subfield_instance[0] == '9' and subfield_instance[1] == 'CURATOR':
# Add reference field on top of references, removing first $$o
field_instance = ([subfield for subfield in field_instance[0]
if subfield[0] != 'o'], field_instance[1],
field_instance[2], field_instance[3],
field_instance[4])
record_add_fields(bibrec, '999', [field_instance],
field_position_local=0)
def _xml_to_textmarc_references(bibrec):
"""
Convert XML record to textmarc and return the lines related to references
@param bibrec: bibrecord object to be converted
@return: textmarc lines with references
@rtype: string
"""
sysno = ""
options = {"aleph-marc": 0, "correct-mode": 1, "append-mode": 0,
"delete-mode": 0, "insert-mode": 0, "replace-mode": 0,
"text-marc": 1}
# Using deepcopy as function create_marc_record() modifies the record passed
textmarc_references = [line.strip() for line
in xmlmarc2textmarc.create_marc_record(copy.deepcopy(bibrec),
sysno, options).split('\n')
if '999C5' in line]
return textmarc_references
def perform_request_ref_extract_url(recid, uid, url):
"""
Making use of the refextractor API, extract references from the url
received from the client
@param recid: opened record id
@param uid: active user id
@param url: URL to extract references from
@return response to be returned to the client code
"""
response = {}
try:
recordExtended = replace_references(recid, uid, url=url)
except FullTextNotAvailable:
response['ref_xmlrecord'] = False
response['ref_msg'] = "File not found. Server returned code 404"
return response
except:
response['ref_xmlrecord'] = False
response['ref_msg'] = """Error while fetching PDF. Bad URL or file could
not be retrieved """
return response
if not recordExtended:
response['ref_msg'] = """No references were found in the given PDF """
return response
ref_bibrecord = create_record(recordExtended)[0]
_add_curated_references_to_record(recid, uid, ref_bibrecord)
response['ref_bibrecord'] = ref_bibrecord
response['ref_xmlrecord'] = record_xml_output(ref_bibrecord)
textmarc_references = _xml_to_textmarc_references(ref_bibrecord)
response['ref_textmarc'] = '
' + ' '.join(textmarc_references) + "
"
return response
def perform_request_ref_extract(recid, uid, txt=None):
""" Handle request to extract references in the given record
@param recid: record id from which the references should be extracted
@type recid: str
@param txt: string containing references
@type txt: str
@param uid: user id
@type uid: int
@return: xml record with references extracted
@rtype: dictionary
"""
text_no_references_found_msg = """ No references extracted. The automatic
extraction did not recognize any reference in the
pasted text.
If you want to add the references
manually, an easily recognizable format is:
[1] Phys. Rev A71 (2005) 42
[2] ATLAS-CMS-2007-333
"""
pdf_no_references_found_msg = """ No references were found in the attached
PDF.
"""
response = {}
response['ref_xmlrecord'] = False
recordExtended = None
try:
if txt:
recordExtended = replace_references(recid, uid,
txt=txt.decode('utf-8'))
if not recordExtended:
response['ref_msg'] = text_no_references_found_msg
else:
recordExtended = replace_references(recid, uid)
if not recordExtended:
response['ref_msg'] = pdf_no_references_found_msg
except FullTextNotAvailable:
response['ref_msg'] = """ The fulltext is not available.
"""
except:
response['ref_msg'] = """ An error ocurred while extracting references.
"""
if not recordExtended:
return response
ref_bibrecord = create_record(recordExtended)[0]
_add_curated_references_to_record(recid, uid, ref_bibrecord)
response['ref_bibrecord'] = ref_bibrecord
response['ref_xmlrecord'] = record_xml_output(ref_bibrecord)
textmarc_references = _xml_to_textmarc_references(ref_bibrecord)
response['ref_textmarc'] = '
' + ' '.join(textmarc_references) + "
"
return response
def perform_request_preview_record(request_type, recid, uid, data):
""" Handle request to preview record with formatting
"""
response = {}
if request_type == "preview":
if data["submitMode"] == "textmarc":
textmarc_record = data['textmarc']
xml_conversion_status = get_xml_from_textmarc(recid, textmarc_record, uid)
if xml_conversion_status['resultMsg'] == 'textmarc_parsing_error':
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['textmarc_parsing_error']
response.update(xml_conversion_status)
return response
record = create_record(xml_conversion_status["resultXML"])[0]
elif cache_exists(recid, uid):
dummy1, dummy2, record, dummy3, dummy4, dummy5, dummy6 = get_cache_contents(recid, uid)
else:
record = get_bibrecord(recid)
# clean the record from unfilled volatile fields
record_strip_empty_volatile_subfields(record)
record_strip_empty_fields(record)
response['html_preview'] = _get_formated_record(record, data['new_window'])
# clean the record from unfilled volatile fields
record_strip_empty_volatile_subfields(record)
record_strip_empty_fields(record)
response['html_preview'] = _get_formated_record(record, data['new_window'])
return response
def perform_request_get_pdf_url(recid):
""" Handle request to get the URL of the attached PDF
"""
response = {}
doc = get_pdf_doc(recid)
if doc:
response['pdf_url'] = doc.get_url()
else:
response['pdf_url'] = ""
return response
def perform_request_get_textmarc(recid, uid):
""" Get record content from cache, convert it to textmarc and return it
"""
textmarc_options = {"aleph-marc": 0, "correct-mode": 1, "append-mode": 0,
"delete-mode": 0, "insert-mode": 0, "replace-mode": 0,
"text-marc": 1}
bibrecord = get_cache_contents(recid, uid)[2]
record_strip_empty_fields(bibrecord)
record_strip_controlfields(bibrecord)
textmarc = xmlmarc2textmarc.create_marc_record(
copy.deepcopy(bibrecord), sysno="", options=textmarc_options)
return {'textmarc': textmarc}
def perform_request_get_tableview(recid, uid, data):
""" Convert textmarc inputed by user to marcxml and if there are no
parsing errors, create cache file
"""
response = {}
textmarc_record = data['textmarc']
if not textmarc_record:
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['tableview_change_success']
xml_conversion_status = get_xml_from_textmarc(recid, textmarc_record, uid)
response.update(xml_conversion_status)
if xml_conversion_status['resultMsg'] == 'textmarc_parsing_error':
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['textmarc_parsing_error']
else:
create_cache(recid, uid,
create_record(xml_conversion_status['resultXML'])[0], data['recordDirty'],
disabled_hp_changes=data['disabled_hp_changes'])
response['resultCode'] = cfg['CFG_BIBEDIT_AJAX_RESULT_CODES_REV']['tableview_change_success']
response['cacheMTime'] = get_cache_mtime(recid, uid)
return response
def _get_formated_record(record, new_window):
"""Returns a record in a given format
@param record: BibRecord object
@param new_window: Boolean, indicates if it is needed to add all the headers
to the page (used when clicking Preview button)
"""
from invenio.config import CFG_WEBSTYLE_TEMPLATE_SKIN
xml_record = wash_for_xml(record_xml_output(record))
result = ''
if new_window:
result = """ Record preview
""" % {'site_url': CFG_SITE_URL,
'cssskin': CFG_WEBSTYLE_TEMPLATE_SKIN != 'default' and '_' + CFG_WEBSTYLE_TEMPLATE_SKIN or ''
}
result += get_mathjax_header(True) + ''
result += "
Brief format preview
"
result += bibformat.format_record(0,
of="hb",
xml_record=xml_record) + " "
result += "
Detailed format preview
"
result += bibformat.format_record(0,
of="hd",
xml_record=xml_record)
#Preview references
result += "
References
"
result += bibformat.format_record(0,
'hdref',
xml_record=xml_record)
result += """
"""
if new_window:
result += ""
return result
########### Functions related to templates web interface #############
def perform_request_init_template_interface():
"""Handle a request to manage templates"""
errors = []
warnings = []
body = ''
# Add script data.
record_templates = get_record_templates()
record_templates.sort()
data = {'gRECORD_TEMPLATES': record_templates,
'gSITE_RECORD': '"' + CFG_SITE_RECORD + '"',
'gSITE_URL': '"' + CFG_SITE_URL + '"'}
body += '\n'
# Add scripts (the ordering is NOT irrelevant).
scripts = [
'vendors/json2/json2.js'
]
bibedit_scripts = ['display.js', 'template_interface.js']
for script in scripts:
body += ' \n' % (url_for('static', filename=script), )
for script in bibedit_scripts:
body += ' \n' % (url_for('editor.static',
filename='js/editor/' + script), )
body += ' \n'
body += ' \n'
return body, errors, warnings
def perform_request_ajax_template_interface(data):
"""Handle Ajax requests by redirecting to appropriate function."""
response = {}
request_type = data['requestType']
if request_type == 'editTemplate':
# Edit a template request.
response.update(perform_request_edit_template(data))
return response
def perform_request_edit_template(data):
""" Handle request to edit a template """
response = {}
template_filename = data['templateFilename']
template = get_record_template(template_filename)
if not template:
response['resultCode'] = 1
else:
response['templateMARCXML'] = template
return response
def perform_doi_search(doi):
"""Search for DOI on the dx.doi.org page
@return: the url returned by this page"""
response = {}
url = "http://dx.doi.org/"
val = {'hdl': doi}
url_data = urllib.urlencode(val)
cj = cookielib.CookieJar()
header = [('User-Agent', cfg['CFG_DOI_USER_AGENT'])]
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = header
try:
resp = opener.open(url, url_data)
except:
return response
else:
response['doi_url'] = resp.geturl()
return response
def check_hide_authors(record):
""" Check if authors should be hidden by default in the user interface """
return sum([len(record.get(tag, [])) for tag in cfg['CFG_BIBEDIT_DISPLAY_AUTHOR_TAGS']]) > cfg['CFG_BIBEDIT_AUTHOR_DISPLAY_THRESHOLD']
def perform_guess_affiliations(uid, data):
response = {}
recid = data["recID"]
record_revision, record, pending_changes, deactivated_hp_changes, \
undo_list, redo_list = get_cache_contents(recid, uid)[1:]
# Let's guess affiliations
result = {}
for tag in cfg['CFG_BIBEDIT_DISPLAY_AUTHOR_TAGS']:
result[tag] = {}
author_field_instances = record_get_field_instances(record, tag)
for field_pos, instance in enumerate(author_field_instances):
subfields_to_add = []
current_affilations = field_get_subfield_values(instance, code="u")
if not current_affilations or current_affilations[0].startswith("VOLATILE:"):
# This author does not have affiliation
try:
author_name = field_get_subfield_values(instance, code="a")[0]
except IndexError:
author_name = author_name[0]
aff_guess = get_affiliation_for_paper(recid, author_name)
if aff_guess:
for aff in aff_guess:
field_add_subfield(instance, code="u", value=aff)
subfields_to_add.append(["u", aff])
if subfields_to_add:
result[tag][field_pos] = subfields_to_add
response['cacheMTime'] = update_cache_contents(recid, uid, record_revision,
record, pending_changes,
deactivated_hp_changes,
undo_list, redo_list)
response['subfieldsToAdd'] = result
return response
def perform_request_submit(recid, uid, data, response):
if not cache_exists(recid, uid):
response['resultCode'] = 106
elif not get_cache_mtime(recid, uid) == data['cacheMTime']:
response['resultCode'] = 107
elif cache_expired(recid, uid) and \
record_locked_by_other_user(recid, uid):
response['resultCode'] = 104
elif record_locked_by_queue(recid):
response['resultCode'] = 105
else:
dummy_cache_dirty, record_revision, record, dummy_pending_changes, \
dummy_disabled_hp_changes, dummy_undo_list, dummy_redo_list \
= get_cache_contents(recid, uid)
xml_record = wash_for_xml(print_rec(record))
record, status_code, list_of_errors = create_record(xml_record)
# Simulate upload to catch errors
errors_upload = perform_upload_check(xml_record, '--replace')
if errors_upload:
response['resultCode'], response['errors'] = 113, \
errors_upload
return response
elif status_code == 0:
response['resultCode'], response['errors'] = 110, \
list_of_errors
if not data['force'] and not latest_record_revision(recid, record_revision):
response['cacheOutdated'] = True
else:
if record_is_conference(record):
new_cnum = add_record_cnum(recid, uid)
if new_cnum:
response["new_cnum"] = new_cnum
save_xml_record(recid, uid)
response['resultCode'] = 4
diff --git a/invenio/legacy/bibsched/bibtask_config.py b/invenio/legacy/bibsched/bibtask_config.py
index 93d051777..6779eb5ac 100644
--- a/invenio/legacy/bibsched/bibtask_config.py
+++ b/invenio/legacy/bibsched/bibtask_config.py
@@ -1,154 +1,154 @@
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2008, 2009, 2010, 2011, 2012, 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""Invenio Bibliographic Task Configuration."""
__revision__ = "$Id$"
import os
import sys
import time
from invenio.config import CFG_LOGDIR, CFG_PYLIBDIR, CFG_INSPIRE_SITE, \
CFG_BIBSCHED_LOGDIR
# Which tasks are recognized as valid?
CFG_BIBTASK_VALID_TASKS = ("bibindex", "bibupload", "bibreformat",
"webcoll", "bibtaskex", "bibrank",
"oaiharvest", "oairepositoryupdater", "inveniogc",
"bibclassify", "bibexport",
"dbdump", "bibencode",
- "bibtasklet", "refextract", "bibcircd", "bibsort",
+ "bibtasklet", "refextract", "bibsort",
"selfcites", "arxiv-pdf-checker", "bibcatalog",
"bibtex", "bibcheck")
# Tasks that should be run as standalone task
if CFG_INSPIRE_SITE:
CFG_BIBTASK_MONOTASKS = ("dbdump", "inveniogc")
else:
CFG_BIBTASK_MONOTASKS = ("bibupload", "dbdump", "inveniogc")
# Tasks that should be run during fixed times
CFG_BIBTASK_FIXEDTIMETASKS = ("oaiharvest", )
# Task that should not be reinstatiated
CFG_BIBTASK_NON_REPETITIVE_TASK = ('bibupload', )
# Default options for any bibtasks
# This is then overridden by each specific BibTask in
# CFG_BIBTASK_DEFAULT_TASK_SETTINGS
CFG_BIBTASK_DEFAULT_GLOBAL_TASK_SETTINGS = {
'version': '',
'task_stop_helper_fnc': None,
'task_name': os.path.basename(sys.argv[0]),
'task_specific_name': '',
'task_id': 0,
'user': '',
# If the task is not initialized (usually a developer debugging
# a single method), output all messages.
'verbose': 9,
'sleeptime': '',
'runtime': time.strftime("%Y-%m-%d %H:%M:%S"),
'priority': 0,
'runtime_limit': None,
'profile': [],
'post-process': [],
'sequence-id': None,
'stop_queue_on_error': not CFG_INSPIRE_SITE,
'fixed_time': False,
'email_logs_to': [],
}
# Default options for each bibtasks
# for each bibtask name are specified those settings that the bibtask expects
# to find initialized. Webcoll is empty because current webcoll algorithms
# relays on parameters not being initialized at all.
CFG_BIBTASK_DEFAULT_TASK_SETTINGS = {
'inveniogc': {
'logs': False,
'guests': False,
'bibxxx': False,
'documents': False,
'cache': False,
'tasks': False,
},
'oaiharvest': {
'repository': None,
'dates': None,
'fixed_time': True
},
'oairepositoryupdater': {
'no_upload': 0,
},
'bibupload': {
'mode': None,
'verbose': 1,
'tag': None,
'file_path': None,
'notimechange': 0,
'stage_to_start_from': 1,
'pretend': False,
'force': False,
},
'bibindex': {
'cmd': 'add',
'id': [],
'modified': [],
'collection': [],
'maxmem': 0,
'flush': 10000,
'windex': None,
'reindex': False,
},
'bibrank': {
'quick': 'yes',
'cmd': 'add',
'flush': 100000,
'collection': [],
'id': [],
'check': "",
'stat': "",
'modified': "",
'last_updated': 'last_updated',
'run': [],
},
'webcoll': {
},
'bibtaskex': {
'number': 30,
},
'bibexport': {
'wjob': None,
},
'dbdump': {
'output': CFG_LOGDIR,
'number': 5,
},
'bibencode': {
},
'refextract': {
'recids': [],
'collections': [],
},
}
CFG_BIBTASK_TASKLETS_PATH = os.path.join(
CFG_PYLIBDIR, 'invenio', 'bibsched_tasklets')
CFG_BIBSCHED_LOGDIR = os.path.join(CFG_LOGDIR, CFG_BIBSCHED_LOGDIR)
CFG_BIBTASK_LOG_FORMAT = ('%(asctime)s --> %(message)s', '%Y-%m-%d %H:%M:%S')
diff --git a/invenio/legacy/websession/templates.py b/invenio/legacy/websession/templates.py
index 6c1ac4338..c60c6b15c 100644
--- a/invenio/legacy/websession/templates.py
+++ b/invenio/legacy/websession/templates.py
@@ -1,2153 +1,2151 @@
# This file is part of Invenio.
# Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2014,
# 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
__revision__ = "$Id$"
import urllib
import cgi
from invenio.base.wrappers import lazy_import
from invenio.config import \
CFG_CERN_SITE, \
CFG_SITE_LANG, \
CFG_SITE_NAME, \
CFG_SITE_NAME_INTL, \
CFG_SITE_SUPPORT_EMAIL, \
CFG_SITE_SECURE_URL, \
CFG_SITE_URL, \
CFG_WEBSESSION_RESET_PASSWORD_EXPIRE_IN_DAYS, \
CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS, \
CFG_WEBSEARCH_MAX_RECORDS_IN_GROUPS, \
CFG_ACCESS_CONTROL_LEVEL_ACCOUNTS, \
CFG_SITE_RECORD
CFG_EXTERNAL_AUTH_USING_SSO = lazy_import('invenio.modules.access.local_config:CFG_EXTERNAL_AUTH_USING_SSO')
from invenio.utils.url import make_canonical_urlargd, create_url, create_html_link
from invenio.utils.html import escape_html, nmtoken_from_string
from invenio.base.i18n import gettext_set_language, language_list_long
from invenio.modules.apikeys.models import WebAPIKey
from invenio.legacy.websession.websession_config import CFG_WEBSESSION_GROUP_JOIN_POLICY
class Template:
def tmpl_back_form(self, ln, message, url, link):
"""
A standard one-message-go-back-link page.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'message' *string* - The message to display
- 'url' *string* - The url to go back to
- 'link' *string* - The link text
"""
out = """
""" % (key, value)
return out
def tmpl_external_user_settings(self, ln, html_settings):
_ = gettext_set_language(ln)
out = """
%(external_user_settings)s
%(html_settings)s
%(external_user_groups)s
%(consult_external_groups)s
""" % {
'external_user_settings' : _('External account settings'),
'html_settings' : html_settings,
'consult_external_groups' : _('You can consult the list of your external groups directly in the %(x_url_open)sgroups page%(x_url_close)s.', **{
'x_url_open' : '' % ln,
'x_url_close' : ''
}),
'external_user_groups' : _('External user groups'),
}
return out
def tmpl_user_api_key(self, ln=CFG_SITE_LANG, keys_info=None, csrf_token=''):
"""
Displays all the API key that the user owns the user
Parameters:
- 'ln' *string* - The language to display the interface in
- 'key_info' *tuples* - Contains the tuples with the key data (id, desciption, status)
- 'csrf_token' *string* - The CSRF token to verify the form origin.
"""
# load the right message language
_ = gettext_set_language(ln)
out = """
%(user_api_key)s
""" % {
'user_api_key' : _("API keys")
}
if keys_info and len(keys_info) != 0:
out += "
%(user_keys)s
" % {'user_keys': _("These are your current API keys")}
out += """
""" % {
'create_new_key' : _("If you want to create a new API key, please enter a description for it"),
'new_key_description_label' : _("Description for the new API key"),
'mandatory' : _("mandatory"),
'note' : _("Note"),
'new_key_description_note': _("The description should be something meaningful for you to recognize the API key"),
'create_new_key_button' : _("Create new key"),
'csrf_token': cgi.escape(csrf_token, True),
'sitesecureurl': CFG_SITE_SECURE_URL
}
return out
def tmpl_user_preferences(self, ln, email, email_disabled, password_disabled, nickname, csrf_token=''):
"""
Displays a form for the user to change his email/password.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'email' *string* - The email of the user
- 'email_disabled' *boolean* - If the user has the right to edit his email
- 'password_disabled' *boolean* - If the user has the right to edit his password
- 'nickname' *string* - The nickname of the user (empty string if user does not have it)
- 'csrf_token' *string* - The CSRF token to verify the form origin.
"""
# load the right message language
_ = gettext_set_language(ln)
out = """
""" % {
'change_user' : _("If you want to change your email or set for the first time your nickname, please set new values in the form below."),
'edit_params' : _("Edit login credentials"),
'nickname_label' : _("Nickname"),
'nickname' : nickname,
'csrf_token': cgi.escape(csrf_token, True),
'nickname_prefix' : nickname=='' and ' '+_("Example")+':johnd' or '',
'new_email' : _("New email address"),
'mandatory' : _("mandatory"),
'example' : _("Example"),
'note' : _("Note"),
'set_values' : _("Set new values"),
'email' : email,
'email_disabled' : email_disabled and "readonly" or "",
'sitesecureurl': CFG_SITE_SECURE_URL,
'fixed_nickname_note' : _('Since this is considered as a signature for comments and reviews, once set it can not be changed.')
}
if not password_disabled and not CFG_EXTERNAL_AUTH_USING_SSO:
out += """
%(change_pass)s
%(note)s:
%(old_password_note)s
%(note)s:
%(password_note)s
""" % {
'change_pass' : _("If you want to change your password, please enter the old one and set the new value in the form below."),
'mandatory' : _("mandatory"),
'old_password' : _("Old password"),
'new_password' : _("New password"),
'csrf_token': cgi.escape(csrf_token, True),
'optional' : _("optional"),
'note' : _("Note"),
'password_note' : _("The password phrase may contain punctuation, spaces, etc."),
'old_password_note' : _("You must fill the old password in order to set a new one."),
'retype_password' : _("Retype password"),
'set_values' : _("Set new password"),
'password_disabled' : password_disabled and "disabled" or "",
'sitesecureurl': CFG_SITE_SECURE_URL,
}
elif not CFG_EXTERNAL_AUTH_USING_SSO and CFG_CERN_SITE:
out += "
"
elif CFG_EXTERNAL_AUTH_USING_SSO and CFG_CERN_SITE:
out += "
" + _("""You can change or reset your CERN account password by means of the %(x_url_open)sCERN account system%(x_url_close)s.""") % \
{'x_url_open' : '', 'x_url_close' : ''} + "
"
return out
def tmpl_user_bibcatalog_auth(self, bibcatalog_username="", bibcatalog_password="", ln=CFG_SITE_LANG, csrf_token=''):
"""template for setting username and pw for bibcatalog backend"""
_ = gettext_set_language(ln)
out = """
""" % {
'update_settings' : _("Update settings"),
'select_group_records' : _("Number of search results per page"),
'csrf_token': cgi.escape(csrf_token, True),
}
return out
def tmpl_lost_password_form(self, ln):
"""
Displays a form for the user to ask for his password sent by email.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'msg' *string* - Explicative message on top of the form.
"""
# load the right message language
_ = gettext_set_language(ln)
out = "
" + _("If you have lost the password for your %(sitename)s %(x_fmt_open)sinternal account%(x_fmt_close)s, then please enter your email address in the following form in order to have a password reset link emailed to you.", **{'x_fmt_open' : '', 'x_fmt_close' : '', 'sitename' : CFG_SITE_NAME_INTL[ln]}) + "
" + _("Note that if you have been using an external login system, then we cannot do anything and you have to ask there.") + " "
out += _("Alternatively, you can ask %(x_name)s to change your login system from external to internal.",
x_name=("""%(email)s""" % { 'email' : CFG_SITE_SUPPORT_EMAIL })) + "
"
return out
def tmpl_account_info(self, ln, uid, guest, CFG_CERN_SITE):
"""
Displays the account information
Parameters:
- 'ln' *string* - The language to display the interface in
- 'uid' *string* - The user id
- 'guest' *boolean* - If the user is guest
- 'CFG_CERN_SITE' *boolean* - If the site is a CERN site
"""
# load the right message language
_ = gettext_set_language(ln)
out = """
%(account_offer)s
""" % {
'account_offer' : _("%(x_name)s offers you the possibility to personalize the interface, to set up your own personal library of documents, or to set up an automatic alert query that would run periodically and would notify you of search results by email.",
x_name=CFG_SITE_NAME_INTL[ln]),
}
if not guest:
out += """
""" % {
'ln' : ln,
'your_settings' : _("Your Settings"),
'change_account' : _("Set or change your account email address or password. Specify your preferences about the look and feel of the interface.")
}
out += """
""" % {
'ln' : ln,
'your_searches' : _("Your Searches"),
'search_explain' : _("View all the searches you performed during the last 30 days."),
}
out += """
%(basket_explain)s""" % {
'ln' : ln,
'your_baskets' : _("Your Baskets"),
'basket_explain' : _("With baskets you can define specific collections of items, store interesting records you want to access later or share with others."),
}
if not guest:
out += """
%(comments_explain)s""" % {
'ln' : ln,
'your_comments' : _("Your Comments"),
'comments_explain' : _("Display all the comments you have submitted so far."),
}
if CFG_CERN_SITE:
out += """
""" % {
'your_loans' : _("Your Loans"),
'explain_loans' : _("Check out book you have on loan, submit borrowing requests, etc. Requires CERN ID."),
'ln': ln,
'CFG_SITE_SECURE_URL': CFG_SITE_SECURE_URL
}
out += """
"""
return out
def tmpl_warning_guest_user(self, ln, type):
"""
Displays a warning message about the specified type
Parameters:
- 'ln' *string* - The language to display the interface in
- 'type' *string* - The type of data that will get lost in case of guest account (for the moment: 'baskets')
"""
# load the right message language
_ = gettext_set_language(ln)
if (type=='baskets'):
msg = _("You are logged in as a guest user, so your baskets will disappear at the end of the current session.") + ' '
msg += _("If you wish you can %(x_url_open)slogin or register here%(x_url_close)s.", **{'x_url_open': '',
'x_url_close': ''})
return """
%s
""" % msg
def tmpl_account_body(self, ln, user):
"""
Displays the body of the actions of the user
Parameters:
- 'ln' *string* - The language to display the interface in
- 'user' *string* - The username (nickname or email)
"""
# load the right message language
_ = gettext_set_language(ln)
out = _("You are logged in as %(x_user)s. You may want to a) %(x_url1_open)slogout%(x_url1_close)s; b) edit your %(x_url2_open)saccount settings%(x_url2_close)s.") %\
{'x_user': user,
'x_url1_open': '',
'x_url1_close': '',
'x_url2_open': '',
'x_url2_close': '',
}
return out + "
"
def tmpl_account_template(self, title, body, ln, url):
"""
Displays a block of the your account page
Parameters:
- 'ln' *string* - The language to display the interface in
- 'title' *string* - The title of the block
- 'body' *string* - The body of the block
- 'url' *string* - The URL to go to the proper section
"""
out ="""
""" % (url, title, body)
return out
def tmpl_account_page(self, ln, warnings, warning_list, accBody, baskets, alerts, searches, messages, loans, groups, submissions, approvals, tickets, administrative, comments):
"""
Displays the your account page
Parameters:
- 'ln' *string* - The language to display the interface in
- 'accBody' *string* - The body of the heading block
- 'baskets' *string* - The body of the baskets block
- 'alerts' *string* - The body of the alerts block
- 'searches' *string* - The body of the searches block
- 'messages' *string* - The body of the messages block
- 'groups' *string* - The body of the groups block
- 'submissions' *string* - The body of the submission block
- 'approvals' *string* - The body of the approvals block
- 'administrative' *string* - The body of the administrative block
- 'comments' *string* - The body of the comments block
"""
# load the right message language
_ = gettext_set_language(ln)
out = ""
if warnings == "1":
out += self.tmpl_general_warnings(warning_list)
out += self.tmpl_account_template(_("Your Account"), accBody, ln, '/youraccount/edit?ln=%s' % ln)
if messages:
out += self.tmpl_account_template(_("Your Messages"), messages, ln, '/yourmessages/display?ln=%s' % ln)
if loans:
out += self.tmpl_account_template(_("Your Loans"), loans, ln, '/yourloans/display?ln=%s' % ln)
if baskets:
out += self.tmpl_account_template(_("Your Baskets"), baskets, ln, '/yourbaskets/display?ln=%s' % ln)
if comments:
comments_description = _("You can consult the list of %(x_url_open)syour comments%(x_url_close)s submitted so far.")
comments_description %= {'x_url_open': '',
'x_url_close': ''}
out += self.tmpl_account_template(_("Your Comments"), comments_description, ln, '/yourcomments/?ln=%s' % ln)
if searches:
out += self.tmpl_account_template(_("Your Searches"), searches, ln, '/youralerts/display?ln=%s' % ln)
if groups:
groups_description = _("You can consult the list of %(x_url_open)syour groups%(x_url_close)s you are administering or are a member of.")
groups_description %= {'x_url_open': '',
'x_url_close': ''}
out += self.tmpl_account_template(_("Your Groups"), groups_description, ln, '/yourgroups/display?ln=%s' % ln)
if submissions:
submission_description = _("You can consult the list of %(x_url_open)syour submissions%(x_url_close)s and inquire about their status.")
submission_description %= {'x_url_open': '',
'x_url_close': ''}
out += self.tmpl_account_template(_("Your Submissions"), submission_description, ln, '/yoursubmissions.py?ln=%s' % ln)
if approvals:
approval_description = _("You can consult the list of %(x_url_open)syour approvals%(x_url_close)s with the documents you approved or refereed.")
approval_description %= {'x_url_open': '',
'x_url_close': ''}
out += self.tmpl_account_template(_("Your Approvals"), approval_description, ln, '/yourapprovals.py?ln=%s' % ln)
#check if this user might have tickets
if tickets:
ticket_description = _("You can consult the list of %(x_url_open)syour tickets%(x_url_close)s.")
ticket_description %= {'x_url_open': '',
'x_url_close': ''}
out += self.tmpl_account_template(_("Your Tickets"), ticket_description, ln, '/yourtickets?ln=%s' % ln)
if administrative:
out += self.tmpl_account_template(_("Your Administrative Activities"), administrative, ln, '/admin')
return out
def tmpl_account_emailMessage(self, ln, msg):
"""
Displays a link to retrieve the lost password
Parameters:
- 'ln' *string* - The language to display the interface in
- 'msg' *string* - Explicative message on top of the form.
"""
# load the right message language
_ = gettext_set_language(ln)
out =""
out +="""
%(msg)s %(try_again)s
""" % {
'ln' : ln,
'msg' : msg,
'try_again' : _("Try again")
}
return out
def tmpl_account_reset_password_email_body(self, email, reset_key, ip_address, ln=CFG_SITE_LANG):
"""
The body of the email that sends lost internal account
passwords to users.
"""
_ = gettext_set_language(ln)
out = """
%(intro)s
%(intro2)s
<%(link)s>
%(outro)s
%(outro2)s""" % {
'intro': _("Somebody (possibly you) coming from %(x_ip_address)s "
"has asked\nfor a password reset at %(x_sitename)s\nfor "
"the account \"%(x_email)s\"." % {
'x_sitename' :CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
'x_email' : email,
'x_ip_address' : ip_address,
}
),
'intro2' : _("If you want to reset the password for this account, please go to:"),
'link' : "%s/youraccount/resetpassword%s" %
(CFG_SITE_SECURE_URL, make_canonical_urlargd({
'ln' : ln,
'k' : reset_key
}, {})),
'outro' : _("in order to confirm the validity of this request."),
'outro2' : _("Please note that this URL will remain valid for about %(days)s days only.", days=CFG_WEBSESSION_RESET_PASSWORD_EXPIRE_IN_DAYS),
}
return out
def tmpl_account_address_activation_email_body(self, email, address_activation_key, ip_address, ln=CFG_SITE_LANG):
"""
The body of the email that sends email address activation cookie
passwords to users.
"""
_ = gettext_set_language(ln)
out = """
%(intro)s
%(intro2)s
<%(link)s>
%(outro)s
%(outro2)s""" % {
'intro': _("Somebody (possibly you) coming from %(x_ip_address)s "
"has asked\nto register a new account at %(x_sitename)s\nfor the "
"email address \"%(x_email)s\"." % {
'x_sitename' :CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME),
'x_email' : email,
'x_ip_address' : ip_address,
}
),
'intro2' : _("If you want to complete this account registration, please go to:"),
'link' : "%s/youraccount/access%s" %
(CFG_SITE_SECURE_URL, make_canonical_urlargd({
'ln' : ln,
'mailcookie' : address_activation_key
}, {})),
'outro' : _("in order to confirm the validity of this request."),
'outro2' : _("Please note that this URL will remain valid for about %(days)s days only.", days=CFG_WEBSESSION_ADDRESS_ACTIVATION_EXPIRE_IN_DAYS),
}
return out
def tmpl_account_emailSent(self, ln, email):
"""
Displays a confirmation message for an email sent
Parameters:
- 'ln' *string* - The language to display the interface in
- 'email' *string* - The email to which the message has been sent
"""
# load the right message language
_ = gettext_set_language(ln)
out =""
out += _("Okay, a password reset link has been emailed to %(x_email)s.", x_email=email)
return out
def tmpl_account_delete(self, ln):
"""
Displays a confirmation message about deleting the account
Parameters:
- 'ln' *string* - The language to display the interface in
"""
# load the right message language
_ = gettext_set_language(ln)
out = "
" + _("""Deleting your account""") + '
'
return out
def tmpl_lost_your_password_teaser(self, ln=CFG_SITE_LANG):
"""Displays a short sentence to attract user to the fact that
maybe he lost his password. Used by the registration page.
"""
_ = gettext_set_language(ln)
out = ""
out += """%(maybe_lost_pass)s""" % {
'ln' : ln,
'maybe_lost_pass': ("Maybe you have lost your password?")
}
return out
def tmpl_account_adminactivities(self, ln, uid, guest, roles, activities):
"""
Displays the admin activities block for this user
Parameters:
- 'ln' *string* - The language to display the interface in
- 'uid' *string* - The used id
- 'guest' *boolean* - If the user is guest
- 'roles' *array* - The current user roles
- 'activities' *array* - The user allowed activities
"""
# load the right message language
_ = gettext_set_language(ln)
out = ""
# guest condition
if guest:
return _("You seem to be a guest user. You have to %(x_url_open)slogin%(x_url_close)s first.",
x_url_open='',
x_url_close='')
# no rights condition
if not roles:
return "
" + _("You are not authorized to access administrative functions.") + "
"
# displaying form
out += "
" + _("You are enabled to the following roles: %(x_role)s.",
x_role=('' + ", ".join(roles) + "")) + '
'
if activities:
# print proposed links:
activities.sort(lambda x, y: cmp(x.lower(), y.lower()))
tmp_out = ''
for action in activities:
if action == "runbibedit":
tmp_out += """ %s""" % (CFG_SITE_URL, CFG_SITE_RECORD, _("Run Record Editor"))
- if action == "runbibcirculation":
- tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Run BibCirculation"))
if action == "runbibmerge":
tmp_out += """ %s""" % (CFG_SITE_URL, CFG_SITE_RECORD, _("Run Record Merger"))
if action == "cfgbibformat":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure BibFormat"))
if action == "cfgbibknowledge":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure BibKnowledge"))
if action == "cfgoaiharvest":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure OAI Harvest"))
if action == "cfgoairepository":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure OAI Repository"))
if action == "cfgbibindex":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure BibIndex"))
if action == "cfgbibrank":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure BibRank"))
if action == "cfgwebaccess":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure WebAccess"))
if action == "cfgwebcomment":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure WebComment"))
if action == "cfgwebsearch":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure WebSearch"))
if action == "cfgwebsubmit":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure WebSubmit"))
if action == "runbibdocfile":
tmp_out += """ %s""" % (CFG_SITE_URL, CFG_SITE_RECORD, ln, _("Run Document File Manager"))
if action == "cfgbibsort":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Configure BibSort"))
if action == "runinfomanager":
tmp_out += """ %s""" % (CFG_SITE_URL, ln, _("Run Info Space Manager"))
if tmp_out:
out += _("Here are some interesting web admin links for you:") + tmp_out
out += " " + _("For more admin-level activities, see the complete %(x_url_open)sAdmin Area%(x_url_close)s.",
x_url_open='',
x_url_close='')
return out
def tmpl_create_userinfobox(self, ln, url_referer, guest, username, submitter, referee, admin, usebaskets, usemessages, usealerts, usegroups, useloans, usestats):
"""
Displays the user block
Parameters:
- 'ln' *string* - The language to display the interface in
- 'url_referer' *string* - URL of the page being displayed
- 'guest' *boolean* - If the user is guest
- 'username' *string* - The username (nickname or email)
- 'submitter' *boolean* - If the user is submitter
- 'referee' *boolean* - If the user is referee
- 'admin' *boolean* - If the user is admin
- 'usebaskets' *boolean* - If baskets are enabled for the user
- 'usemessages' *boolean* - If messages are enabled for the user
- 'usealerts' *boolean* - If alerts are enabled for the user
- 'usegroups' *boolean* - If groups are enabled for the user
- 'useloans' *boolean* - If loans are enabled for the user
- 'usestats' *boolean* - If stats are enabled for the user
@note: with the update of CSS classes (cds.cds ->
invenio.css), the variables useloans etc are not used in
this function, since they are in the menus. But we keep
them in the function signature for backwards
compatibility.
"""
# load the right message language
_ = gettext_set_language(ln)
out = """ """ % CFG_SITE_URL
if guest:
out += """%(guest_msg)s ::
%(login)s""" % {
'sitesecureurl': CFG_SITE_SECURE_URL,
'ln' : ln,
'guest_msg' : _("guest"),
'referer' : url_referer and ('&referer=%s' % urllib.quote(url_referer)) or '',
'login' : _('login')
}
else:
out += """
%(username)s :: """ % {
'sitesecureurl' : CFG_SITE_SECURE_URL,
'ln' : ln,
'username' : username
}
out += """%(logout)s""" % {
'sitesecureurl' : CFG_SITE_SECURE_URL,
'ln' : ln,
'logout' : _("logout"),
}
return out
def tmpl_warning(self, warnings, ln=CFG_SITE_LANG):
"""
Display len(warnings) warning fields
@param infos: list of strings
@param ln=language
@return: html output
"""
if not((type(warnings) is list) or (type(warnings) is tuple)):
warnings = [warnings]
warningbox = ""
if warnings != []:
warningbox = "
\n Warning:\n"
for warning in warnings:
lines = warning.split("\n")
warningbox += "
"
for line in lines[0:-1]:
warningbox += line + " \n"
warningbox += lines[-1] + "
\n"
return errorbox
def tmpl_display_all_groups(self,
infos,
admin_group_html,
member_group_html,
external_group_html = None,
warnings=[],
ln=CFG_SITE_LANG):
"""
Displays the 3 tables of groups: admin, member and external
Parameters:
- 'ln' *string* - The language to display the interface in
- 'admin_group_html' *string* - HTML code for displaying all the groups
the user is the administrator of
- 'member_group_html' *string* - HTML code for displaying all the groups
the user is member of
- 'external_group_html' *string* - HTML code for displaying all the
external groups the user is member of
"""
_ = gettext_set_language(ln)
group_text = self.tmpl_infobox(infos)
group_text += self.tmpl_warning(warnings)
if external_group_html:
group_text += """
""" %(admin_group_html, member_group_html)
return group_text
def tmpl_display_admin_groups(self, groups, ln=CFG_SITE_LANG):
"""
Display the groups the user is admin of.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'groups' *list* - All the group the user is admin of
- 'infos' *list* - Display infos on top of admin group table
"""
_ = gettext_set_language(ln)
img_link = """
%(text)s
"""
out = self.tmpl_group_table_title(img="/img/group_admin.png",
text=_("You are an administrator of the following groups:") )
out += """
%s
%s
""" %(_("Group"), _("Description"))
if len(groups) == 0:
out += """
%s
""" %(_("You are not an administrator of any groups."),)
for group_data in groups:
(grpID, name, description) = group_data
edit_link = img_link % {'siteurl' : CFG_SITE_URL,
'grpID' : grpID,
'ln': ln,
'img':"webbasket_create_small.png",
'text':_("Edit group"),
'action':"edit"
}
members_link = img_link % {'siteurl' : CFG_SITE_URL,
'grpID' : grpID,
'ln': ln,
'img':"webbasket_usergroup.png",
'text':_("Edit %(x_num)s members", x_num=''),
'action':"members"
}
out += """
%s
%s
%s
%s
""" % (cgi.escape(name), cgi.escape(description), edit_link, members_link)
out += """
""" % {'ln': ln,
'write_label': _("Create new group"),
}
return out
def tmpl_display_member_groups(self, groups, ln=CFG_SITE_LANG):
"""
Display the groups the user is member of.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'groups' *list* - All the group the user is member of
"""
_ = gettext_set_language(ln)
group_text = self.tmpl_group_table_title(img="/img/webbasket_us.png", text=_("You are a member of the following groups:"))
group_text += """
""" % {'ln': ln,
'join_label': _("Join new group"),
'leave_label':_("Leave group")
}
return group_text
def tmpl_display_external_groups(self, groups, ln=CFG_SITE_LANG):
"""
Display the external groups the user is member of.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'groups' *list* - All the group the user is member of
"""
_ = gettext_set_language(ln)
group_text = self.tmpl_group_table_title(img="/img/webbasket_us.png", text=_("You are a member of the following external groups:"))
group_text += """
"""
return group_text
def tmpl_display_input_group_info(self,
group_name,
group_description,
join_policy,
act_type="create",
grpID=None,
warnings=[],
ln=CFG_SITE_LANG):
"""
Display group data when creating or updating a group:
Name, description, join_policy.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'group_name' *string* - name of the group
- 'group_description' *string* - description of the group
- 'join_policy' *string* - join policy
- 'act_type' *string* - info about action : create or edit(update)
- 'grpID' *int* - ID of the group(not None in case of group editing)
- 'warnings' *list* - Display warning if values are not correct
"""
_ = gettext_set_language(ln)
#default
hidden_id =""
form_name = "create_group"
action = CFG_SITE_URL + '/yourgroups/create'
button_label = _("Create new group")
button_name = "create_button"
label = _("Create new group")
delete_text = ""
if act_type == "update":
form_name = "update_group"
action = CFG_SITE_URL + '/yourgroups/edit'
button_label = _("Update group")
button_name = "update"
label = _('Edit group %(x_name)s', x_name=cgi.escape(group_name))
delete_text = """"""
delete_text %= (_("Delete group"),"delete")
if grpID is not None:
hidden_id = """"""
hidden_id %= grpID
out = self.tmpl_warning(warnings)
out += """
%(label)s
%(join_policy_label)s
%(join_policy)s
%(hidden_id)s
%(delete_text)s
"""
out %= {'action' : action,
'logo': CFG_SITE_URL + '/img/webbasket_create.png',
'label': label,
'form_name' : form_name,
'name_label': _("Group name:"),
'delete_text': delete_text,
'description_label': _("Group description:"),
'join_policy_label': _("Group join policy:"),
'group_name': cgi.escape(group_name, 1),
'group_description': cgi.escape(group_description, 1),
'button_label': button_label,
'button_name':button_name,
'cancel_label':_("Cancel"),
'hidden_id':hidden_id,
'ln': ln,
'join_policy' :self.__create_join_policy_selection_menu("join_policy",
join_policy,
ln)
}
return out
def tmpl_display_input_join_group(self,
group_list,
group_name,
group_from_search,
search,
warnings=[],
ln=CFG_SITE_LANG):
"""
Display the groups the user can join.
He can use default select list or the search box
Parameters:
- 'ln' *string* - The language to display the interface in
- 'group_list' *list* - All the group the user can join
- 'group_name' *string* - Name of the group the user is looking for
- 'group_from search' *list* - List of the group the user can join matching group_name
- 'search' *int* - User is looking for group using group_name
- 'warnings' *list* - Display warning if two group are selected
"""
_ = gettext_set_language(ln)
out = self.tmpl_warning(warnings)
search_content = ""
if search:
search_content = """
"""
out %= {'action' : CFG_SITE_URL + '/yourgroups/join',
'logo': CFG_SITE_URL + '/img/webbasket_create.png',
'label': _("Join group"),
'group_name': cgi.escape(group_name, 1),
'label2':_("or find it") + ': ',
'list_label':_("Choose group:"),
'ln': ln,
'find_label': _("Find group"),
'cancel_label':_("Cancel"),
'group_list' :self.__create_select_menu("grpID",group_list, _("Please select:")),
'search_content' : search_content
}
return out
def tmpl_display_manage_member(self,
grpID,
group_name,
members,
pending_members,
infos=[],
warnings=[],
ln=CFG_SITE_LANG):
"""Display current members and waiting members of a group.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'grpID *int* - ID of the group
- 'group_name' *string* - Name of the group
- 'members' *list* - List of the current members
- 'pending_members' *list* - List of the waiting members
- 'infos' *tuple of 2 lists* - Message to inform user about his last action
- 'warnings' *list* - Display warning if two group are selected
"""
_ = gettext_set_language(ln)
out = self.tmpl_warning(warnings)
out += self.tmpl_infobox(infos)
out += """
%(title)s
%(header1)s
%(member_text)s
%(header2)s
%(pending_text)s
%(header3)s
%(invite_text)s
"""
if members :
member_list = self.__create_select_menu("member_id", members, _("Please select:"))
member_text = """
""" % _("No members awaiting approval.")
header1 = self.tmpl_group_table_title(text=_("Current members"))
header2 = self.tmpl_group_table_title(text=_("Members awaiting approval"))
header3 = _("Invite new members")
write_a_message_url = create_url(
"%s/yourmessages/write" % CFG_SITE_URL,
{
'ln' : ln,
'msg_subject' : _('Invitation to join "%(x_name)s" group', x_name=escape_html(group_name)),
'msg_body' : _("""\
Hello:
I think you might be interested in joining the group "%(x_name)s".
You can join by clicking here: %(x_url)s.
Best regards.
""", **{'x_name': group_name,
'x_url': create_html_link("%s/yourgroups/join" % CFG_SITE_URL, { 'grpID' : grpID,
'join_button' : "1",
},
link_label=group_name, escape_urlargd=True, escape_linkattrd=True)})})
link_open = '' % escape_html(write_a_message_url)
invite_text = _("If you want to invite new members to join your group, please use the %(x_url_open)sweb message%(x_url_close)s system.",
**{'x_url_open': link_open, 'x_url_close': ''})
action = CFG_SITE_URL + '/yourgroups/members?ln=' + ln
out %= {'title':_('Group: %(x_name)s', x_name=escape_html(group_name)),
'member_text' : member_text,
'pending_text' :pending_text,
'action':action,
'grpID':grpID,
'header1': header1,
'header2': header2,
'header3': header3,
'img_alt_header1': _("Current members"),
'img_alt_header2': _("Members awaiting approval"),
'img_alt_header3': _("Invite new members"),
'invite_text': invite_text,
'imgurl': CFG_SITE_URL + '/img',
'cancel_label':_("Cancel"),
'ln':ln
}
return out
def tmpl_display_input_leave_group(self,
groups,
warnings=[],
ln=CFG_SITE_LANG):
"""Display groups the user can leave.
Parameters:
- 'ln' *string* - The language to display the interface in
- 'groups' *list* - List of groups the user is currently member of
- 'warnings' *list* - Display warning if no group is selected
"""
_ = gettext_set_language(ln)
out = self.tmpl_warning(warnings)
out += """
%(label)s
%(list_label)s
%(groups)s
%(submit)s
"""
if groups:
groups = self.__create_select_menu("grpID", groups, _("Please select:"))
list_label = _("Group list")
submit = """""" % _("Leave group")
else :
groups = _("You are not member of any group.")
list_label = ""
submit = ""
action = CFG_SITE_URL + '/yourgroups/leave?ln=%s'
action %= (ln)
out %= {'groups' : groups,
'list_label' : list_label,
'action':action,
'logo': CFG_SITE_URL + '/img/webbasket_create.png',
'label' : _("Leave group"),
'cancel_label':_("Cancel"),
'ln' :ln,
'submit' : submit
}
return out
def tmpl_confirm_delete(self, grpID, ln=CFG_SITE_LANG):
"""
display a confirm message when deleting a group
@param grpID *int* - ID of the group
@param ln: language
@return: html output
"""
_ = gettext_set_language(ln)
action = CFG_SITE_URL + '/yourgroups/edit'
out = """
%(message)s
"""% {'message': _("Are you sure you want to delete this group?"),
'ln':ln,
'yes_label': _("Yes"),
'no_label': _("No"),
'grpID':grpID,
'action': action
}
return out
def tmpl_confirm_leave(self, uid, grpID, ln=CFG_SITE_LANG):
"""
display a confirm message
@param grpID *int* - ID of the group
@param ln: language
@return: html output
"""
_ = gettext_set_language(ln)
action = CFG_SITE_URL + '/yourgroups/leave'
out = """
%(message)s
"""% {'message': _("Are you sure you want to leave this group?"),
'ln':ln,
'yes_label': _("Yes"),
'no_label': _("No"),
'grpID':grpID,
'action': action
}
return out
def __create_join_policy_selection_menu(self, name, current_join_policy, ln=CFG_SITE_LANG):
"""Private function. create a drop down menu for selection of join policy
@param current_join_policy: join policy as defined in CFG_WEBSESSION_GROUP_JOIN_POLICY
@param ln: language
"""
_ = gettext_set_language(ln)
elements = [(CFG_WEBSESSION_GROUP_JOIN_POLICY['VISIBLEOPEN'],
_("Visible and open for new members")),
(CFG_WEBSESSION_GROUP_JOIN_POLICY['VISIBLEMAIL'],
_("Visible but new members need approval"))
]
select_text = _("Please select:")
return self.__create_select_menu(name, elements, select_text, selected_key=current_join_policy)
def __create_select_menu(self, name, elements, select_text, multiple=0, selected_key=None):
""" private function, returns a popup menu
@param name: name of HTML control
@param elements: list of (key, value)
"""
if multiple :
out = """