All payments in a date range with quick transaction view

A SQL report for Koha ILS

Yesterday was the last day of the year, when Sri Ashish Kumar Barik the young and enthusiastic librarian at Midnapore City College requested for a new custom SQL report that would allow him:

To see every payment made by every user in a given date range, sorted by MM/YY. It should show every type of payment made e.g. overdue fines, lost book fees, library card replacement. Basically everything that was charged to and paid by a patron

In this blog post we share it with all, so that others looking for something similar can have a ready template for their use. It’s our way to saying thank you and Happy New Year 2019 to all our readers, clients and well-wishers.

Putting it together

The report uses three tables in the Koha database – (a) accountlines; (b) borrowers and (c) categories.

The report adds a quick transaction view link next to each and every payment. For library staff wanting to find out the details of a particular payment, with this report that information is just a single click away.

The report metadata
Report name List all payments made by patrons between two dates
Report group Accounts
Notes List all payments made by patrons between two dates, sorted by date and patron name.
The SQL statement
SELECT 
    CONCAT("<a href=\"/cgi-bin/koha/members/boraccount.pl?borrowernumber=", T1.borrowernumber, "\" target=\"_blank\">View Transaction</a>") AS 'Click to view'
    , T2.cardnumber AS 'Card No.'
    , CONCAT(T2.firstname, " ", T2.surname) AS 'Name'
    , T3.description AS 'Category'
    , CONCAT(SUBSTRING(MONTHNAME(T1.timestamp), 1,3), " ", YEAR(T1.timestamp)) AS 'Billing Period'
    , DATE_FORMAT(DATE(T1.timestamp), "%d/%m/%Y") AS 'Txn Date'
    , CONCAT("₹", LPAD(REPLACE(ROUND(T1.amount, 2),"-", ""), 8, " ")) AS 'Paid' 
FROM 
    `accountlines` T1 
     LEFT JOIN borrowers T2 USING (borrowernumber) 
    LEFT JOIN categories T3 USING (categorycode) 
WHERE 
    T1.accounttype="PAY" 
    AND
   DATE(T1.timestamp) BETWEEN <<From date|date>> AND <<To date|date>> 
ORDER BY DATE(T1.timestamp), CONCAT(T2.firstname, " ", T2.surname)
See it in action

Here is a short 2 minute video of it for those who want to see it action.

Wishing everyone a Happy New Year 2019.

Extracting patron images from Koha DB

This is part of the series of blog posts on how to extract your data from a Koha system where you unable to access the DB directly, but where you have “superlibrarian” access. In this part, we talk about extracting the patron images stored inside the patronimage table in your Koha database.

Prequisites

  • You should be comfortable using the GNU/Linux command line
  • Familiarity with SQL syntax
  • The Koha DB schema reference for your version of Koha
  • A Linux system with cURL and LibreOffice installed
  • Superlibrarian userid and password of your Koha instance

Modus operandi

  1. Use the Koha Reports module to download the list of the borrowernumbers of patrons having their image in the db
  2. Remove the header line and save it as a text file, with one borrowernumber per line
  3. Use cURL to get the CGISESSID cookie using the authentication SVC API call
  4. Execute the BASH script, passing the authenticated session id and the file holding the list of borrowernumbers as command line parameters
  5. Use the Koha Reports module to generate the IDLINK.txt batch patron image uploader file

The background

Patron images in Koha are stored in the patronimage table of the database. The table has following schema:

Column Type Size Parents Comments
borrowernumber int 10 borrowers the borrowernumber of the patron this image is attached to (borrowers.borrowernumber)
mimetype varchar 15   the format of the image (png, jpg, etc)
imagefile mediumblob 16777215   the image

A blob is a “binary large object” which means it is not a text field. The contents won’t make any sense if we used the report module to SELECT imagefile FROM patronimage. This brings cURL into the picture.

The patron image is served on the OPAC / staff client using the patronimage.pl Perl script using an URL like this: http://<your_instance>/cgi-bin/koha/members/patronimage.pl?borrowernumber=<borrowernumber>.

But before we can run cURL on this URL, we must do one more thing. We need our BASH script to login using our superlibrarian userid and password using Koha authentication web service API call.

We need to do this for two reasons: (a) login into our Koha instance with superlibrarian access and (b) get hold of the CGISESSID cookie.

Putting it all together

  1. A simple SQL report as given below with fetch us the borrowernumber of patrons with their image stored in the DB.

    SELECT borrowernumber FROM patronimage

    We will download the result as Open Document spreadsheet.

    Next we copy and save the list of patron borrowernumbers into a text file (let’s call it list-of-pix.txt), with one borrowernumber per line.

  2. Lets put together our small BASH script. We shall call it get_pix.sh.
    #!/bin/bash
    
    mkdir patronimages
    
    while read LINE
        do  curl -b CGISESSID=$1  -o ./patronimages/$LINE.png http://<your_instance>/cgi-bin/koha/members/patronimage.pl?borrowernumber=$LINE
    done < $2

    NOTE: <your_instance> need to be changed with **your** actual server URL.
    Make the script executable by running chmod a+x get_pix.sh.

  3. From the command-line run the following command:
    $ curl -i http://<your_instance>/cgi-bin/koha/svc/authentication -d 'userid=<yourid>&password=<yourpass>'

    If we had put in the correct information, we shall see something like this:

    HTTP/1.1 200 OK
    Date: Thu, 20 Dec 2018 09:53:02 GMT
    Server: Apache/2.4.18 (Ubuntu)
    Set-Cookie: CGISESSID=4a732ae75d8991a994d7ad0df584f84c; path=/; HttpOnly
    Vary: Accept-Encoding
    Transfer-Encoding: chunked
    Content-Type: text/xml; charset=ISO-8859-1
    
    <?xml version='1.0' standalone='yes'?>
    <response>
      <status>ok</status>
    </response>

    This gives us the two things we need for the next step: (a) the CGISESSID and (b) the status as OK. OK signifies that we were successfully logged in.

  4. Now we run the get_pix.sh script
    ./get_pix.sh f03a894f1885e891e30f6d40e6e9838c ./list-of-pix.txt

    And we shall see the patron images getting downloaded.

  5. Once the patron images have all been downloaded to patronimages folder created by the get_pix.sh script, its time to generate the IDLINK.txt file, which we will place in the aforementioned patronimages folder. Again, we shall turn to Koha's Reports module with this small SQL script:
    SELECT CONCAT(borrowers.cardnumber,", ", patronimage.borrowernumber, ".png") AS 'IDLINK'
      FROM patronimage 
      LEFT JOIN borrowers ON patronimage.borrowernumber=borrowers.borrowernumber

    This will generate our listing for the IDLINK.txt. If you are not sure about what IDLINK.txt does, please read up from here.

  6. Download the report as Open Document Spreadsheet, remove the header line and copy the rest into a text file and save it as IDLINK.txt in the patronimages folder.
  7. Zip up the patronimages folder as mentioned here and we have the patron images ready for a batch upload.

Display the totals for fines & fees, payments made, the outstanding, written off and forgiven amounts between a specified date range

A nifty single line SQL report for accounting using Koha.

Earlier this week, Sri Kalipada Jana, librarian at our client-partner Basanti Devi College, Kolkata, filed a new custom SQL report request. He wanted a report that did the following:

To list the total fines accrued, total paid so far and the total outstanding fines / fee between 02 (two) given dates.

Now, the readers of this blog who are acquinted with ready-made, user contributed SQL report library on the Koha Community wiki will know that there are a quite a few reports available that generate reports similar to Kalipada’s requirement. However these ready-made SQL reports usually generate this data at one data point at a time e.g. one report will provide total fines, another will provide total outstanding fines and so on. Further (and perhaps left as a exercise to the reader) these ready reports usually do not take into account “reversed charges“, “partial payments” entered as credits etc.

The report

The report presents a consolidated, single line of the total fines & Fees (F + FU + N + A + M + L), amount outstanding (F + FU + N + A + M + L), paid (P + C), written off (W) and forgiven (FOR) between a date range. If you wish to learn more about the mnemonics used within the brackets, you should look at the “Hard Coded Values” entry on the Koha Wiki.

By itself, the report is simple, it aggregates the totals presented by 05 (five) SQL sub-queries and shows it together. One interesting thing to note in the report is the use of “runtime variables“. The two run-time variables @FromDate and @ToDate are used to hold the user specified start and end date, instead of asking for the same repeatedly for each sub query.

SELECT * FROM 

(SELECT (@FromDate:=<<From date|date>>) AS 'From (y-m-d)', (@ToDate:=<<To date|date>>) AS 'To (y-m-d)') AS T1, 

(SELECT
    IFNULL(ROUND(SUM(accountlines.amount), 2), "0.00") AS 'Total Fines/Fees' FROM accountlines 
WHERE 
    accounttype IN ('F', 'FU', 'N', 'A', 'M', 'L') AND  DATE(timestamp) BETWEEN @FromDate AND @ToDate) AS T2, 

(SELECT 
    IFNULL(ROUND(SUM(accountlines.amountoutstanding), 2), "0.00") AS 'Total O/S' FROM accountlines 
WHERE 
    accounttype IN ('F', 'FU', 'N', 'A', 'M', 'L') AND  DATE(timestamp) BETWEEN @FromDate AND @ToDate) AS T3, 

(SELECT
    IFNULL(REPLACE(ROUND(SUM(amount),2),"-",""), "0.00") AS 'Paid / Credited'  FROM accountlines 
WHERE
   accounttype IN ('PAY', 'C') AND description NOT LIKE "%Reversed%" AND DATE(timestamp) BETWEEN @FromDate AND @ToDate) AS T4, 

(SELECT
    IFNULL(REPLACE(ROUND(SUM(amount),2),"-",""),"0.00") AS 'Written off'  FROM accountlines 
WHERE 
    accounttype='W' AND DATE(timestamp) BETWEEN @FromDate AND @ToDate) AS T5, 

(SELECT
    IFNULL(REPLACE(ROUND(SUM(amount),2), "-", ""), "0.00") AS 'Forgiven'  FROM accountlines 
WHERE 
    accounttype='FOR' AND DATE(timestamp) BETWEEN @FromDate AND @ToDate) AS T6

Cheers!

Surendranath Law College partners with L2C2 Technologies to automate their library

136 year old Surendranath Law College selects L2C2 Technologies’ Koha support.

We are pleased to extend a warm welcome to the newest member of our growing client-partner family in Eastern India – Surendranath Law College, Kolkata. At 136 years, SNLC is regarded as one the oldest law college of the country. The SNLC library has gone live on Koha ILS 17.11 series on L2C2 Technologies‘s cloud hosting platform.

About Surendranath Law College

Surendranath Law College formerly known as Ripon College) is an undergraduate law college affiliated with the University of Calcutta in Kolkata, India. It was established in 1885 by a trust formed by the nationalist leader, scholar and educationist Surendranath Banerjee, a year after he founded Surendranath College. This is now regarded one of the oldest Law college of the country. Dr. Rajendra Prasad, the first president of the Republic of India is among the several notable alumni of the college.

Source: Wikipedia

AskALibrarian – Koha’s new feedback form plugin

A Koha plugin that adds user feedback functionality to Koha’s OPAC.

What is the ‘AskALibrarian’ Koha plugin?

It is a Koha plugin that adds a modal user feedback form to the Koha OPAC. It is written to utility the Koha Plugin System that was originally introduced into #kohails with version 3.12. This means that while the feature is an extension to a stock Koha installation, it is essentially a koha-native solution. Thus it is well-integrated within Koha as compared to any other third party solution. In terms of direct advantages it brings in (a) ease of maintainability across Koha upgrades, (b) ability to use the submitted data directly from Koha’s SQL reports, (c) data privacy – the data is stored directly inside your Koha database, as opposed to with any other 3rd party solution (something that assumes far greater significance in the GDPR era).

Why this plugin?

The Koha OPAC provides a lot of functionality to both the library staff as well as the library patrons. Below is a short list of things you can (there are more) and things you can not do.

Things you can ? Things you can’t ?
  • Login with your user account
  • Reserve a book
  • Renew a book
  • Pay a fine or fee
  • Update your contact information
  • Do a self-registration
  • Submit a purchase suggestion
  • Add star ratings
  • And much more
  • Leave a feedback for the library staff

Since a lot of L2C2 Technologies’s client partners seem to be wanting the facility of user feedback forms, we finally decided “Why not… let’s do a plugin!” And so the AskALibrarian plugin was born.

How does it work?

The plugin adds a bootstrap modal feedback form as a menu option on the navbar at the top of the Koha OPAC. On submission of the form by the user / visitor, the information is submitted via an AJAX call to a Perl script – askalibrarian.pl, on the staff client side. The script invokes the required sub-routines from the plugin to do two things : (a) send the user an acknowledgement of the submitted input to the user’s email address, it provided is reachable and (b) store the submitted data in the koha_plugin_com_l2c2technologies_askalibrarian_feedback table in the Koha database. A callback sends up an alert popup on the OPAC, informing if it has successfully captured the data.

How to get the plugin?

The plugin is published under GNU GPL v3.0 license and is available here from L2C2 Technologies‘s GitHub repository. Pull requests for bugs or improvements are welcome 🙂

Please show me step by step!

Given how our readers from the Indian sub-continent are fond of “step-by-step” instructions, we have a small video for our readers (about 11 mins) that shows how to setup and use plugin.

Enjoy! May the source be with you!

Koha Patron Image Packer helper script

One-click utility to help build bulk patron image loader zip archive for users accessing Koha ILS from their Windows PCs.

Academic libraries like the ones in colleges, typically have a need to bulk upload patron images (of students) at the start of every school year. The photos are usually made available from their admissions office, named and numbered as per either unique enrollment id or student id of each student. The college libraries typically also utilize these same numbers as their library card numbers.

Of course, when several hundred patron images have to be imported, Koha’s bulk patron image upload option comes in very handy. It is available at More > Tools > Patrons and Circulation > Upload Patron Images. We can create a ZIP archive with all these uniquely named and numbered photos along with a manifest file named either DATALINK.txt or IDLINK.txt. The structure of the manifest file is simple – <cardnumber><separator><filename>. The <separator> can be a comma or a tab character.

The only kink in this work flow is that quite often we would see people creating that manifest by hand. This, as expected, quite often led to errors, and as a result they often had to make multiple runs at uploading the photos along with wasting precious time identifying the errors in the manifest.

So when our client-partner Basanti Devi College Library wanted to upload several hundred patron images at one go, we decided to put together a small PowerShell script that could automate this function so that it could get done quickly, without any error and at the click of the mouse.

The Koha Patron Image Packer is the outcome. It is small PowerShell script that allows users working on Windows based system to build their bulk patron image batch loader zip file along with it’s IDLINK.txt manifest with just a single click. It’s minimum requirements are PowerShell v 3.0 script with .NET Framework 4.0.

Get the code

The code is available from https://gitlab.com/indradg/koha-patron-image-packer

Installation

Installation is nothing more than copying the datalinker.ps1 file over to folder which is holding your patron images named as per their cardnumbers in Koha.

However, before your Windows system may allow you to run an PowerShell script, it may be require you to set your ExecutionPolicy to RemoteSigned for your CurrentUser. To do that, go to Run and type in PowerShell and hit enter to open up the Windows PowerShell interactive console and type in the following command:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

To check if this has been set currently you can run the command and check the output by typing in

Get-ExecutionPolicy -List

Demostration

A screencast of this feature at work is available on Youtube. It is a short video under 2 minutes. Watch it at 720p at full-screen if supported on your bandwidth.

License

It is released under GNU GPL v3 or later, the same license as Koha.

Acknowledgment

A.J. Tomson, Librarian, Devagiri College, Kozhikode who wrote an early version of analogous script in Python in Koha 3.12 days.

Vimal Kumar V. whose blog post “A useful script to compress patron images to upload” had originally put the spotlight on Mr. Tomson’s work.

RTFM Series : Memcached and “DBI Connection failed: Access denied for user [..]”

Stumped by the Koha v 18.05’s refusal to access the database after a koha-remove followed by a koha-create using the same instance name? Then read on!

This post applies strictly to Koha 18.05 which was released on May 24, 2018. The new version with its new features has created a lot of excitement among the user. However the version has some major changes and unless you **CLOSELY** read and understand the release notes you will asking for trouble.

In this post we are going to talk about Memcached which is turned on by default from 18.05. If you overlook this fact, you may see yourself wasting hours trying to troubleshoot a problem, which may inexplicably (not quite even though it looks that way) go away after re-starting your system.

Last weekend my young friend Jayanta Nayek spent nearly a day trying to understand why he was getting the error – “DBI Connection failed: Access denied for user” whenever he tried to access the web-installer part of the staff client on his new 18.05 instance. Since he was on a test system, he had followed the old rinse-and-repeat routine. So when his installation did not work out for the first time, he ran sudo koha-remove library and then re-ran sudo koha-create --create-db library to start afresh.

When he re-created the instance i.e. “library”, he was stumped with the following error :

Software error:

DBIx::Class::Storage::DBI::catch {...} (): DBI Connection failed: Access denied for user 'koha_library'@'localhost' (using password: YES) at /usr/share/perl5/DBIx/Class/Storage/DBI.pm line 1490. at /usr/share/koha/lib/Koha/Database.pm line 103

Of course, when he tried to access the koha_library database from the mysql command-line client using the user and pass from his /etc/koha/sites/library/koha-conf.xml, it worked perfectly. But if he came back to the browser and tried to access the web-installer, the error would return.

So what was happening here? In one word – memcached! Memcached is an open source, distributed memory object caching system that alleviates database load to speed up dynamic Web applications. The system caches data and objects in memory to minimize the frequency with which an external database or API (application program interface) must be accessed. (Source: What is Memcached?).

In simple terms what this means for Koha is that memcached caches the frequent database queries fired off by Koha. And if an SQL result set has not changed since it was last queried *and* is already stored into memcached, it offers the data from in-memory hashes rather than using a more time-consuming database lookup process. Memcached (along with plack is intended to make Koha work faster under heavier loads).

When Jayanta would run sudo koha-remove library and followed it up with sudo koha-create --create-db library the Memcached server was not restarted, and kept holding on to the *original* database access hashes. Whereas following koha-create command to re-create the instance, the database authentication credentials (user & pass values from koha-conf.xml) were changed. That is why when he tried to directly access via the mysql command line client, it worked as the CLI client did not know about memcached. But when he tried to access the web-installer it failed as the connection query hash offered up from memcached had the old and not longer existing credentials.

So, if any reader of this blog should find themselves facing a problem like this, simple run the command sudo service memcached restart and once memcached has restarted, access the web-installer. It will work this time. Since memcached is an in-memory storage, the restart clears up the hashes and when the web-installer tries to access the database, it leads to what is called a “cache-miss” and thus the queries get run against the actual DB using the access credentials stored in koha-conf.xml.

And for goodness sake READ THE RELEASE NOTES 😉

Generate a single sheet custom MARC21 framework in 2 minutes

For intermediate Koha ILS users who wish to quickly generate a single tab MARC framework.

Last Thursday, Ashish Kumar Barik, librarian at our new client-partner Midnapore City College filed a support ticket asking for a custom single sheet MARC21 framework or what is more commonly referred to by LIS professionals as a “worksheet“. He wrote that he wanted the following tags 000, 003, 005, 008, 020, 040, 041, 044, 082, 100, 245, 250, 260, 300, 440, 490, 500, 504, 650, 700, 942 and that the sub-tags/fields should be set as in the default marc framework shipped with Koha. We promised him his new framework. Being new to this side of Koha, he of course had missed out two key fields without which his system would be rendered practically useless i.e. the two local use tags952 and 999. Koha uses 952 to handle holdings (item) information and 999 is purely an internal tag used to track the bibliographic records.

Now anyone who has ever setup a new MARC framework knows that it can be a laborious and time consuming task. Further, there are chances of introducing inadvertent human errors that may lead to error or bad data when used as a part of the framework. As a result, at L2C2 Technologies we have developed several well defined strategies to manage custom marc frameworks for our clients. In today’s blog, we are going to share the simplest of the techniques we use in cases like this. The outcome of this exercise is a 100% error free marc framework generated in less than 2 minutes.

LEGAL DISCLAIMER: The next steps involve directly accessing and making changes in the the Koha database. So use these instructions at your own risk, if you face any data loss, corruption or system errors we are not responsible.

The Steps

  1. We used a regex capable editor like Notepad++ to quote the fields mentioned by Ashish, so that 000, 003, 005, 008, 020, 040, 041, 044, 082, 100, 245, 250, 260, 300, 440, 490, 500, 504, 650, 700, 942 became ‘000’, ‘003’, ‘005’, ‘008’, ‘020’, ‘040’, ‘041’, ‘044’, ‘082’, ‘100’, ‘245’, ‘250’, ‘260’, ‘300’, ‘440’, ‘490’, ‘500’, ‘504’, ‘650’, ‘700’, ‘942’. And while we did that, we also added the following fields missing in his list i.e. ‘952’, ‘999’.
  2. Next we defined a new framework MCC1 (MCC Framework) by visiting Home -> Administration -> MARC bibliographic framework -> New Framework
  3. Next we copied the default framework into MCC1 as its base, since that is what Ashish had wanted. At this point, the MCC1 framework is exactly same as the default framework of Koha.
  4. Next we fired up the MySQL console and logged in with the user id and passwd from MCC’s koha-conf.xml, and chose Ashish’s database in this case koha_mcc for the next steps.
  5. Fired the following SQL query :
    UPDATE
       `marc_subfield_structure` 
    SET
       tab=0
    WHERE 
       `frameworkcode`='MCC1' 
    AND 
       `tagfield` IN ('000', '003', '005', '008', '020', '040', '041', '044', '082', '100', '245', '250', '260', '300', '440', '490', '500', '504', '650', '700', '942')
    AND
       `tab`!=0;

    MySQL client told us 152 rows were affected.

    EXPLANATION: This moved all 1XX to 9XX (except 952 and 999) marc fields into Tab 0. The images below help illustrate the condition after this step:

  6. The next step was to set the rest of the fields outside the list supplied by Ashish *plus* 952 and 999 to be ‘ignored’ by Koha when using the MCC1 framework. And thus the following SQL query:
    UPDATE 
        `marc_subfield_structure` 
    SET 
        `tab`='-1' 
    WHERE
        `frameworkcode`='MCC1'
    AND 
        `tagfield` NOT IN ('000', '003', '005', '008', '020', '040', '041', '044', '082', '100', '245', '250', '260', '300', '440', '490', '500', '504', '650', '700', '942', '952', '999') 
    AND
        `tab`!=0;

    This time MySQL reported that 3416 rows were updated.

  7. Our last step at the MySQL command line was the following query that removed the unwanted 0XX fields from Tab 0 :
    UPDATE 
        `marc_subfield_structure` 
    SET 
        `tab`='-1' 
    WHERE
        `frameworkcode`='MCC1'
    AND 
        `tagfield` NOT IN ('000', '003', '005', '008', '020', '040', '041', '044', '082', '100', '245', '250', '260', '300', '440', '490', '500', '504', '650', '700', '942', '952', '999');

    MySQL reported 341 rows were affected.

  8. Coming back to MCC’s Koha staff client, we did the most important thing i.e. running MARC Bibliographic framework test. The test came out clean without any error.
  9. That’s it! MCC’s custom MARC framework is ready for use. Click on the image below and then zoom in to see the details up close.

Ramakrishna Sarada Mission Vivekananda Vidyabhavan moves to L2C2’s cloud based Koha platform

We are happy to announce that after nearly 2 years of being an L2C2 Technologies client-partner Ramakrishna Sarada Mission Vivekananda Vidyabhaban (RKSMVV) have decided to move entirely to L2C2’s cloud based Koha hosting platform from the academic session of 2018-19. The college had so far hosted their OPAC with us while running their day to day operations on a local system running a very old Koha 3.08.4. This is a major jump from them since they will by upgrading directly to 17.11 (the latest stable version of Koha) from a version that is nearly 6 years old.

About RKSMVV

Ramakrishna Sarada Mission Vivekananda Vidyabhavan is a partly residential degree college for women affiliated with the West Bengal State University, India. Colloquially more commonly known as “Sarada Mission College” or simply as “Sarada College”, it was the first educational institution started by Ramakrishna Sarada Mission. It came into existence in 1961 as an effort to carry out Swami Vivekananda’s ideals of education among women. Housed initially in a one-roomed makeshift structure, with thirty one students and a handful of young, idealistic and enthusiastic teachers and monastic members, the college today stands among the premier women’s institutions of the state with an ‘A’ Level by National Assessment and Accreditation Council

(Source: Wikipedia)

About L2C2 Technologies

Based out of Kolkata, India, L2C2 Technologies is an active Koha developer and library technology service provider.

Displaying unique title and volume count on the Koha staff client – Part 2

In this followup to our previous post on upgrade-friendly way of displaying unique title and copies’ count on the staff client, we explore a few variant use-cases reported by our readers.

Last December when we posted about the nifty little trick of displaying unique title and volume count on the Koha staff client, we didn’t realize that so many people would find something to be so useful. We received quite a few comments from all over the world. In this post, we are going to try and look at some of these use-cases that people thought could use something like this. So, if you are reading this and haven’t read the original post, it may be helpful to read Part 1 first.

The questions we received were:

(a) what if we have multiple branches?
(b) How to show the stats for the user’s logged in branch only?
(c) How do we show the overall totals if we have multiple branches?

Recently, the library at Our Lady Queen of the Mission School, Salt Lake had started to catalog both their junior library as well as the senior library. So, they presented the perfect opportunity to showcase these 3 use-cases.

1. What if we have multiple branches?

This was a question that came from Hussein Al-Nasri from Egypt. Hussein had tried the code snippet, but since it was hard-coded to handle only one single branch (the first on in the list of the JSON data returned), it wasn’t showing him what he wanted – the data for each of his branches.

The solution
$(document).ready(function() {
  if ( $('#main_intranet-main').length ) {
  $.getJSON("https://qmsl-staff.l2c2.co.in/cgi-bin/koha/svc/report?id=1&annotated=1.", function(data) {
    if ( data.length ) {
      $('#news1').prepend('<div class="newsitem" id="mystats"><table class="table table-striped" style="width: 100%; background: none;"><thead><th colspan="3" style="text-align: center; font-weight: bold; padding: 8px; line-height: 1.42857143; vertical-align: middle; text-transform: uppercase;">Library Statistics</thead><tbody><tr id="mystatstb"><td><strong>Branch</strong></td><td><strong>Unique titles</strong></td><td><strong>Total Copies</strong></td></tr></tbody></table></div>');
      for ( var key in data ) {
        $('<tr id=\"tr'+ key + '"><td class="text-center">' + data[key].homebranch + '</td><td class="text-center">' + data[key].bibs + '</td><td class="text-center">' + data[key].items + '</td></tr>').insertAfter( $( '#mystatstb' ) );
      }
    }
  });
  }
});

2. How to show stats only for the logged in branch?

This came from Freddy Enrique Pelayo from Peru, South America. He left a comment on the blog post asking:

if the system were to have more than 2 branches, will the screen show information according to the branch the user logged in?

The solution
$(document).ready(function() {
  if ( $('#main_intranet-main').length ) {
  $.getJSON("https://qmsl-staff.l2c2.co.in/cgi-bin/koha/svc/report?id=1&annotated=1.", function(data) {
    if ( data.length ) {
      $('#news1').prepend('<div class="newsitem" id="mystats"><table class="table table-striped" style="width: 100%; background: none;"><thead><th colspan="3" style="text-align: center; font-weight: bold; padding: 8px; line-height: 1.42857143; vertical-align: middle; text-transform: uppercase;">Library Statistics</thead><tbody><tr id="mystatstb"><td><strong>Branch</strong></td><td><strong>Unique titles</strong></td><td><strong>Total Copies</strong></td></tr></tbody></table></div>');
      for ( var key in data ) {
        if ( $('#logged-in-branch-code').html() == data[key].homebranch ) {
          $('<tr id=\"tr'+ key + '"><td class="text-center">' + data[key].homebranch + '</td><td class="text-center">' + data[key].bibs + '</td><td class="text-center">' + data[key].items + '</td></tr>').insertAfter( $( '#mystatstb' ) );
        }
      }
    }
  });
  }
});

Explanation

The key line here is $('#logged-in-branch-code').html() == data[key].homebranch. Whenever an user logs into the Koha staff client, the hidden <span> element with the id logged-in-branch-code holds the code for the user’s logged in branch. In the above snippet, we simply introduce a check to see if the code matches the homebranch code in the JSON array. If it does, we show the value for that branch and not for the other branches.

3. How to show the total for all branches?

This scenario was pointed to by Dr. Apurba Jyoti Mazumdar, Assistant Librarian, Assam Univerity, Silchar, India.

The solution

$(document).ready(function() {
    if ( $('#main_intranet-main').length ) {
    $.getJSON("https://qmsl-staff.l2c2.co.in/cgi-bin/koha/svc/report?id=1&annotated=1.", function(data) {
        if ( data.length ) {
            $('#news1').prepend('<div class="newsitem" id="mystats"><table class="table table-striped" style="width: 100%; background: none;"><thead><th colspan="3" style="text-align: center; font-weight: bold; padding: 8px; line-height: 1.42857143; vertical-align: middle; text-transform: uppercase;">Library Statistics</thead><tbody><tr id="mystatstb"><td><strong>Branch</strong></td><td><strong>Unique titles</strong></td><td><strong>Total Copies</strong></td></tr></tbody></table></div>');
            var totalbibs = 0;
            var totalitems = 0;
            for ( var key in data ) {
                $('<tr id=\"tr'+ key + '"><td class="text-center">' + data[key].homebranch + '</td><td class="text-center">' + data[key].bibs + '</td><td class="text-center">' + data[key].items + '</td></tr>').insertAfter( $( '#mystatstb' ) );
                 totalbibs = totalbibs + parseInt(data[key].bibs);
                 totalitems = totalitems +  parseInt(data[key].items); 
            }
            $( '<tr><td><strong>TOTAL</strong></td><td class="text-center"><strong>' + totalbibs + '</strong></td><td  class="text-center"><strong>' + totalitems + '</strong></td></tr>' ).insertAfter(  $('#mystats tr:last')  ); 
        }
    });
    }
});

Conclusion

As you may have noticed, in this version, we added an extra check which ensured that we only display this grid of data *only if* any data is returned. We hope that by answering a few of your questions, this post is of some use to some of you.