Bug 14097 : Avoid issue if the number of syspref shared is modified
[koha.git] / t / db_dependent / UsageStats.t
1 # Copyright 2015 BibLibre
2 #
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, see <http://www.gnu.org/licenses>.
16
17 use Modern::Perl;
18 use Test::More tests => 549;
19 use t::lib::Mocks qw(mock_preference);
20 use POSIX qw(strftime);
21
22 BEGIN {
23     use_ok('C4::UsageStats');
24     use_ok('C4::Context');
25     use_ok('C4::Biblio');
26     use_ok( 'C4::AuthoritiesMarc', qw(AddAuthority) );
27     use_ok('C4::Reserves');
28     use_ok('MARC::Record');
29     use_ok('Koha::Acquisition::Order');
30 }
31
32 can_ok(
33     'C4::UsageStats', qw(
34       NeedUpdate
35       BuildReport
36       ReportToCommunity
37       _count )
38 );
39
40 my $dbh = C4::Context->dbh;
41 $dbh->{AutoCommit} = 0;
42 $dbh->{RaiseError} = 1;
43
44 $dbh->do('DELETE FROM issues');
45 $dbh->do('DELETE FROM biblio');
46 $dbh->do('DELETE FROM items');
47 $dbh->do('DELETE FROM auth_header');
48 $dbh->do('DELETE FROM old_issues');
49 $dbh->do('DELETE FROM old_reserves');
50 $dbh->do('DELETE FROM borrowers');
51 $dbh->do('DELETE FROM aqorders');
52 $dbh->do('DELETE FROM subscription');
53
54 #################################################
55 #             Testing Subs
56 #################################################
57
58 # ---------- Testing NeedUpdate -----------------
59
60 #Mocking C4::Context->preference("UsageStatsLastUpdateTime") to 0
61 my $now = strftime( "%s", localtime );
62 t::lib::Mocks::mock_preference( "UsageStatsLastUpdateTime", 0 );
63
64 my $update = C4::UsageStats->NeedUpdate;
65 is( $update, 1, "There is no last update, update needed" );
66
67 #Mocking C4::Context->preference("UsageStatsLastUpdateTime") to now
68 $now = strftime( "%s", localtime );
69 t::lib::Mocks::mock_preference( "UsageStatsLastUpdateTime", $now );
70
71 $update = C4::UsageStats->NeedUpdate;
72 is( $update, 0, "Last update just be done, no update needed " );
73
74 # ---------- Testing BuildReport ----------------
75
76 #Test report->library -----------------
77 #mock to 0
78 t::lib::Mocks::mock_preference( "UsageStatsID",          0 );
79 t::lib::Mocks::mock_preference( "UsageStatsLibraryName", 0 );
80 t::lib::Mocks::mock_preference( "UsageStatsLibraryUrl",  0 );
81 t::lib::Mocks::mock_preference( "UsageStatsLibraryType", 0 );
82 t::lib::Mocks::mock_preference( "UsageStatsCountry",     0 );
83
84 my $report = C4::UsageStats->BuildReport();
85
86 isa_ok( $report,            'HASH', '$report is a HASH' );
87 isa_ok( $report->{library}, 'HASH', '$report->{library} is a HASH' );
88 is( scalar( keys %{$report->{library}} ), 5,  "There are 5 fields in $report->{library}" );
89 is( $report->{library}->{id},             0,  "UsageStatsID           is good" );
90 is( $report->{library}->{name},           '', "UsageStatsLibraryName  is good" );
91 is( $report->{library}->{url},            '', "UsageStatsLibraryUrl   is good" );
92 is( $report->{library}->{type},           '', "UsageStatsLibraryType  is good" );
93 is( $report->{library}->{country},        '', "UsageStatsCountry      is good" );
94
95 #mock with values
96 t::lib::Mocks::mock_preference( "UsageStatsID",          1 );
97 t::lib::Mocks::mock_preference( "UsageStatsLibraryName", 'NAME' );
98 t::lib::Mocks::mock_preference( "UsageStatsLibraryUrl",  'URL' );
99 t::lib::Mocks::mock_preference( "UsageStatsLibraryType", 'TYPE' );
100 t::lib::Mocks::mock_preference( "UsageStatsCountry",     'COUNTRY' );
101
102 $report = C4::UsageStats->BuildReport();
103
104 isa_ok( $report,            'HASH', '$report is a HASH' );
105 isa_ok( $report->{library}, 'HASH', '$report->{library} is a HASH' );
106 is( scalar( keys %{$report->{library}} ), 5,         "There are 5 fields in $report->{library}" );
107 is( $report->{library}->{id},             1,         "UsageStatsID            is good" );
108 is( $report->{library}->{name},           'NAME',    "UsageStatsLibraryName   is good" );
109 is( $report->{library}->{url},            'URL',     "UsageStatsLibraryUrl    is good" );
110 is( $report->{library}->{type},           'TYPE',    "UsageStatsLibraryType   is good" );
111 is( $report->{library}->{country},        'COUNTRY', "UsageStatsCountry       is good" );
112
113 #Test report->volumetry ---------------
114 #with original values
115 $report = C4::UsageStats->BuildReport();
116
117 isa_ok( $report,              'HASH', '$report is a HASH' );
118 isa_ok( $report->{volumetry}, 'HASH', '$report->{volumetry} is a HASH' );
119 is( scalar( keys %{$report->{volumetry}} ), 8, "There are 8 fields in $report->{volumetry}" );
120 is( $report->{volumetry}->{biblio},         0, "There is no biblio" );
121 is( $report->{volumetry}->{items},          0, "There is no items" );
122 is( $report->{volumetry}->{auth_header},    0, "There is no auth_header" );
123 is( $report->{volumetry}->{old_issues},     0, "There is no old_issues" );
124 is( $report->{volumetry}->{old_reserves},   0, "There is no old_reserves" );
125 is( $report->{volumetry}->{borrowers},      0, "There is no borrowers" );
126 is( $report->{volumetry}->{aqorders},       0, "There is no aqorders" );
127 is( $report->{volumetry}->{subscription},   0, "There is no subscription" );
128
129 #after adding objects
130 construct_objects_needed();
131
132 $report = C4::UsageStats->BuildReport();
133
134 isa_ok( $report,              'HASH', '$report is a HASH' );
135 isa_ok( $report->{volumetry}, 'HASH', '$report->{volumetry} is a HASH' );
136 is( scalar( keys %{$report->{volumetry}} ), 8, "There are 8 fields in $report->{volumetry}" );
137 is( $report->{volumetry}->{biblio},         3, "There are 3 biblio" );
138 is( $report->{volumetry}->{items},          3, "There are 3 items" );
139 is( $report->{volumetry}->{auth_header},    2, "There are 2 auth_header" );
140 is( $report->{volumetry}->{old_issues},     1, "There is  1 old_issues" );
141 is( $report->{volumetry}->{old_reserves},   1, "There is  1 old_reserves" );
142 is( $report->{volumetry}->{borrowers},      3, "There are 3 borrowers" );
143 is( $report->{volumetry}->{aqorders},       1, "There is  1 aqorders" );
144 is( $report->{volumetry}->{subscription},   1, "There is  1 subscription" );
145
146 #Test report->systempreferences -------
147 #mock to 0
148 mocking_systempreferences_to_a_set_value(0);
149
150 $report = C4::UsageStats->BuildReport();
151 isa_ok( $report,                      'HASH', '$report is a HASH' );
152 isa_ok( $report->{systempreferences}, 'HASH', '$report->{systempreferences} is a HASH' );
153 verif_systempreferences_values( $report, 0 );
154
155 #mock with values
156 mocking_systempreferences_to_a_set_value(1);
157
158 $report = C4::UsageStats->BuildReport();
159 isa_ok( $report,                      'HASH', '$report is a HASH' );
160 isa_ok( $report->{systempreferences}, 'HASH', '$report->{systempreferences} is a HASH' );
161 verif_systempreferences_values( $report, 1 );
162
163 #Test if unwanted syspref are not sent
164 is( $report->{systempreferences}->{useDischarge}, undef, 'useDischarge should not be shared');
165 is( $report->{systempreferences}->{OpacUserJS},   undef, 'OpacUserJS   should not be shared');
166
167 # ---------- Testing ReportToCommunity ----------
168
169 # ---------- Testing _count ---------------------
170 my $query = '
171   SELECT count(*)
172   FROM   borrowers
173   ';
174 my $count = $dbh->selectrow_array($query);
175
176 my $nb_fields = C4::UsageStats::_count('borrowers');
177 is( $nb_fields, $count, "_count return the good number of fields" );
178
179 #################################################
180 #             Subs
181 #################################################
182
183 # Adding :
184 # 3 borrowers
185 # 4 biblio
186 # 3 biblio items
187 # 3 items
188 # 2 auth_header
189 # 1 old_issues
190 # 1 old_reserves
191 # 1 subscription
192 # 1 aqorders
193 sub construct_objects_needed {
194
195     # ---------- 3 borrowers  ---------------------
196     my $surname1     = 'Borrower 1';
197     my $surname2     = 'Borrower 2';
198     my $surname3     = 'Borrower 3';
199     my $firstname1   = 'firstname 1';
200     my $firstname2   = 'firstname 2';
201     my $firstname3   = 'firstname 3';
202     my $cardnumber1  = 'test_card1';
203     my $cardnumber2  = 'test_card2';
204     my $cardnumber3  = 'test_card3';
205     my $categorycode = Koha::Database->new()->schema()->resultset('Category')->first()->categorycode();
206     my $branchcode   = Koha::Database->new()->schema()->resultset('Branch')->first()->branchcode();
207
208     my $query = '
209     INSERT INTO borrowers
210       (surname, firstname, cardnumber, branchcode, categorycode)
211     VALUES (?,?,?,?,?)';
212     my $insert_sth = $dbh->prepare($query);
213     $insert_sth->execute( $surname1, $firstname1, $cardnumber1, $branchcode, $categorycode );
214     my $borrowernumber1 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
215     $insert_sth->execute( $surname2, $firstname2, $cardnumber2, $branchcode, $categorycode );
216     my $borrowernumber2 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
217     $insert_sth->execute( $surname3, $firstname3, $cardnumber3, $branchcode, $categorycode );
218     my $borrowernumber3 = $dbh->last_insert_id( undef, undef, 'borrowers', undef );
219
220     # ---------- 3 biblios -----------------------
221     my $title1  = 'Title 1';
222     my $title2  = 'Title 2';
223     my $title3  = 'Title 3';
224     my $author1 = 'Author 1';
225     my $author2 = 'Author 2';
226     my $author3 = 'Author 3';
227
228     $query = '
229     INSERT INTO biblio
230       (title, author)
231     VALUES (?,?)';
232     $insert_sth = $dbh->prepare($query);
233     $insert_sth->execute( $title1, $author1 );
234     my $biblionumber1 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
235     $insert_sth->execute( $title2, undef );
236     my $biblionumber2 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
237     $insert_sth->execute( $title3, $author3 );
238     my $biblionumber3 = $dbh->last_insert_id( undef, undef, 'biblio', undef );
239
240     # ---------- 3 biblio items  -------------------------
241     $query = '
242     INSERT INTO biblioitems
243       (biblionumber, itemtype, marcxml)
244     VALUES (?,?,?)';
245     $insert_sth = $dbh->prepare($query);
246     $insert_sth->execute( $biblionumber1, 'Book', '' );
247     my $biblioitemnumber1 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
248     $insert_sth->execute( $biblionumber2, 'Music', '' );
249     my $biblioitemnumber2 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
250     $insert_sth->execute( $biblionumber3, 'Book', '' );
251     my $biblioitemnumber3 = $dbh->last_insert_id( undef, undef, 'biblioitems', undef );
252
253     # ---------- 3 items  -------------------------
254     my $barcode1 = '111111';
255     my $barcode2 = '222222';
256     my $barcode3 = '333333';
257
258     $query = '
259     INSERT INTO items
260       (biblionumber, biblioitemnumber, barcode, itype)
261     VALUES (?,?,?,?)';
262     $insert_sth = $dbh->prepare($query);
263     $insert_sth->execute( $biblionumber1, $biblioitemnumber1, $barcode1, 'Book' );
264     my $item_number1 = $dbh->last_insert_id( undef, undef, 'items', undef );
265     $insert_sth->execute( $biblionumber2, $biblioitemnumber2, $barcode2, 'Music' );
266     my $item_number2 = $dbh->last_insert_id( undef, undef, 'items', undef );
267     $insert_sth->execute( $biblionumber3, $biblioitemnumber3, $barcode3, 'Book' );
268     my $item_number3 = $dbh->last_insert_id( undef, undef, 'items', undef );
269
270     # ---------- Add 2 auth_header
271     $query = '
272     INSERT INTO auth_header
273       (authtypecode)
274     VALUES (?)';
275     $insert_sth = $dbh->prepare($query);
276     $insert_sth->execute('authtypecode1');
277     my $authid1 = $dbh->last_insert_id( undef, undef, 'auth_header', undef );
278     $insert_sth->execute('authtypecode2');
279     my $authid2 = $dbh->last_insert_id( undef, undef, 'auth_header', undef );
280
281     # ---------- Add 1 old_issues
282     $query = '
283     INSERT INTO old_issues
284       (borrowernumber, branchcode, itemnumber)
285     VALUES (?,?,?)';
286     $insert_sth = $dbh->prepare($query);
287     $insert_sth->execute( $borrowernumber1, $branchcode, $item_number1 );
288     my $issue_id1 = $dbh->last_insert_id( undef, undef, 'old_issues', undef );
289
290     # ---------- Add 1 old_reserves
291     AddReserve( $branchcode, $borrowernumber1, $biblionumber1, 'a', '', 1, undef, undef, '', 'Title', undef, undef );
292     my $reserves1   = GetReservesFromBiblionumber( { biblionumber => $biblionumber1 } );
293     my $reserve_id1 = $reserves1->[0]->{reserve_id};
294     my $reserve1    = CancelReserve( { reserve_id => $reserve_id1 } );
295
296     # ---------- Add 1 aqbudgets
297     $query = '
298     INSERT INTO aqbudgets
299       (budget_amount)
300     VALUES (?)';
301     $insert_sth = $dbh->prepare($query);
302     $insert_sth->execute("20.0");
303     my $aqbudgets1 = $dbh->last_insert_id( undef, undef, 'aqbudgets', undef );
304
305     # ---------- Add 1 aqorders
306     $query = '
307     INSERT INTO aqorders
308       (budget_id, basketno, biblionumber, invoiceid, subscriptionid)
309     VALUES (?,?,?,?,?)';
310     $insert_sth = $dbh->prepare($query);
311     $insert_sth->execute( $aqbudgets1, undef, undef, undef, undef );
312     my $aqorders1 = $dbh->last_insert_id( undef, undef, 'aqorders', undef );
313
314     # --------- Add 1 subscription
315     $query = '
316     INSERT INTO subscription
317       (biblionumber)
318     VALUES (?)';
319     $insert_sth = $dbh->prepare($query);
320     $insert_sth->execute($biblionumber1);
321     my $subscription1 = $dbh->last_insert_id( undef, undef, 'subscription', undef );
322
323 }
324
325 #Change systempreferences values to $set_value
326 sub mocking_systempreferences_to_a_set_value {
327     my $set_value = shift;
328
329     foreach (
330         qw/
331         AcqCreateItem
332         AcqWarnOnDuplicateInvoice
333         AcqViewBaskets
334         BasketConfirmations
335         OrderPdfFormat
336         casAuthentication
337         casLogout
338         AllowPkiAuth
339         DebugLevel
340         delimiter
341         noItemTypeImages
342         virtualshelves
343         AutoLocation
344         IndependentBranches
345         SessionStorage
346         Persona
347         AuthDisplayHierarchy
348         AutoCreateAuthorities
349         BiblioAddsAuthorities
350         dontmerge
351         UseAuthoritiesForTracings
352         CatalogModuleRelink
353         hide_marc
354         IntranetBiblioDefaultView
355         LabelMARCView
356         OpacSuppression
357         SeparateHoldings
358         UseControlNumber
359         advancedMARCeditor
360         DefaultClassificationSource
361         EasyAnalyticalRecords
362         autoBarcode
363         item-level_itypes
364         marcflavour
365         PrefillItem
366         z3950NormalizeAuthor
367         SpineLabelAutoPrint
368         SpineLabelShowPrintOnBibDetails
369         BlockReturnOfWithdrawnItems
370         CalculateFinesOnReturn
371         AgeRestrictionOverride
372         AllFinesNeedOverride
373         AllowFineOverride
374         AllowItemsOnHoldCheckout
375         AllowNotForLoanOverride
376         AllowRenewalLimitOverride
377         AllowReturnToBranch
378         AllowTooManyOverride
379         AutomaticItemReturn
380         AutoRemoveOverduesRestrictions
381         CircControl
382         HomeOrHoldingBranch
383         HomeOrHoldingBranchReturn
384         InProcessingToShelvingCart
385         IssueLostItem
386         IssuingInProcess
387         ManInvInNoissuesCharge
388         OverduesBlockCirc
389         RenewalPeriodBase
390         RenewalSendNotice
391         RentalsInNoissuesCharge
392         ReturnBeforeExpiry
393         ReturnToShelvingCart
394         TransfersMaxDaysWarning
395         UseBranchTransferLimits
396         useDaysMode
397         UseTransportCostMatrix
398         UseCourseReserves
399         finesCalendar
400         FinesIncludeGracePeriod
401         finesMode
402         RefundLostItemFeeOnReturn
403         WhenLostChargeReplacementFee
404         WhenLostForgiveFine
405         AllowHoldDateInFuture
406         AllowHoldPolicyOverride
407         AllowHoldsOnDamagedItems
408         AllowHoldsOnPatronsPossessions
409         AutoResumeSuspendedHolds
410         canreservefromotherbranches
411         decreaseLoanHighHolds
412         DisplayMultiPlaceHold
413         emailLibrarianWhenHoldIsPlaced
414         ExpireReservesMaxPickUpDelay
415         OPACAllowHoldDateInFuture
416         OPACAllowUserToChooseBranch
417         ReservesControlBranch
418         ReservesNeedReturns
419         SuspendHoldsIntranet
420         SuspendHoldsOpac
421         TransferWhenCancelAllWaitingHolds
422         AllowAllMessageDeletion
423         AllowOfflineCirculation
424         CircAutocompl
425         CircAutoPrintQuickSlip
426         DisplayClearScreenButton
427         FilterBeforeOverdueReport
428         FineNotifyAtCheckin
429         itemBarcodeFallbackSearch
430         itemBarcodeInputFilter
431         previousIssuesDefaultSortOrder
432         RecordLocalUseOnReturn
433         soundon
434         SpecifyDueDate
435         todaysIssuesDefaultSortOrder
436         UpdateTotalIssuesOnCirc
437         UseTablesortForCirc
438         WaitingNotifyAtCheckin
439         AllowSelfCheckReturns
440         AutoSelfCheckAllowed
441         FRBRizeEditions
442         OPACFRBRizeEditions
443         AmazonCoverImages
444         OPACAmazonCoverImages
445         Babeltheque
446         BakerTaylorEnabled
447         GoogleJackets
448         HTML5MediaEnabled
449         IDreamBooksReadometer
450         IDreamBooksResults
451         IDreamBooksReviews
452         LibraryThingForLibrariesEnabled
453         LocalCoverImages
454         OPACLocalCoverImages
455         NovelistSelectEnabled
456         XISBN
457         OpenLibraryCovers
458         UseKohaPlugins
459         SyndeticsEnabled
460         TagsEnabled
461         CalendarFirstDayOfWeek
462         opaclanguagesdisplay
463         AuthoritiesLog
464         BorrowersLog
465         CataloguingLog
466         FinesLog
467         IssueLog
468         LetterLog
469         ReturnLog
470         SubscriptionLog
471         AuthorisedValueImages
472         BiblioDefaultView
473         COinSinOPACResults
474         DisplayOPACiconsXSLT
475         hidelostitems
476         HighlightOwnItemsOnOPAC
477         OpacAddMastheadLibraryPulldown
478         OPACDisplay856uAsImage
479         OpacHighlightedWords
480         OpacKohaUrl
481         OpacMaintenance
482         OpacPublic
483         OpacSeparateHoldings
484         OPACShowBarcode
485         OPACShowCheckoutName
486         OpacShowFiltersPulldownMobile
487         OPACShowHoldQueueDetails
488         OpacShowLibrariesPulldownMobile
489         OpacShowRecentComments
490         OPACShowUnusedAuthorities
491         OpacStarRatings
492         opacthemes
493         OPACURLOpenInNewWindow
494         OpacAuthorities
495         opacbookbag
496         OpacBrowser
497         OpacBrowseResults
498         OpacCloud
499         OPACFinesTab
500         OpacHoldNotes
501         OpacItemLocation
502         OpacPasswordChange
503         OPACPatronDetails
504         OPACpatronimages
505         OPACPopupAuthorsSearch
506         OpacTopissue
507         opacuserlogin
508         QuoteOfTheDay
509         RequestOnOpac
510         reviewson
511         ShowReviewer
512         ShowReviewerPhoto
513         SocialNetworks
514         suggestion
515         AllowPurchaseSuggestionBranchChoice
516         OpacAllowPublicListCreation
517         OpacAllowSharingPrivateLists
518         OpacRenewalAllowed
519         OpacRenewalBranch
520         OPACViewOthersSuggestions
521         SearchMyLibraryFirst
522         singleBranchMode
523         AnonSuggestions
524         EnableOpacSearchHistory
525         OPACPrivacy
526         opacreadinghistory
527         TrackClicks
528         PatronSelfRegistration
529         OPACShelfBrowser
530         AutoEmailOpacUser
531         AutoEmailPrimaryAddress
532         autoMemberNum
533         BorrowerRenewalPeriodBase
534         checkdigit
535         EnableBorrowerFiles
536         EnhancedMessagingPreferences
537         ExtendedPatronAttributes
538         intranetreadinghistory
539         memberofinstitution
540         patronimages
541         TalkingTechItivaPhoneNotification
542         uppercasesurnames
543         IncludeSeeFromInSearches
544         OpacGroupResults
545         QueryAutoTruncate
546         QueryFuzzy
547         QueryStemming
548         QueryWeightFields
549         TraceCompleteSubfields
550         TraceSubjectSubdivisions
551         UseICU
552         UseQueryParser
553         defaultSortField
554         displayFacetCount
555         OPACdefaultSortField
556         OPACItemsResultsDisplay
557         expandedSearchOption
558         IntranetNumbersPreferPhrase
559         OPACNumbersPreferPhrase
560         opacSerialDefaultTab
561         RenewSerialAddsSuggestion
562         RoutingListAddReserves
563         RoutingSerials
564         SubscriptionHistory
565         Display856uAsImage
566         DisplayIconsXSLT
567         StaffAuthorisedValueImages
568         template
569         yuipath
570         HidePatronName
571         intranetbookbag
572         StaffDetailItemSelection
573         viewISBD
574         viewLabeledMARC
575         viewMARC
576         ILS-DI
577         OAI-PMH
578         version
579         /
580       ) {
581         t::lib::Mocks::mock_preference( $_, $set_value );
582     }
583 }
584
585 #Test if all systempreferences are at $value_to_test
586 sub verif_systempreferences_values {
587     my ( $report, $value_to_test ) = @_;
588
589     foreach my $key ( keys %{$report->{systempreferences}} ) {
590         is( $report->{systempreferences}->{$key}, $value_to_test, "\$report->{systempreferences}->{$key} = $value_to_test" );
591     }
592 }
593
594 $dbh->rollback;